⼩程序实现⽀付前端后端代码
⼩程序实现⽀付前端后端代码
公司根据业务需求,要做⽀付功能,⽹上查了些资料花了两天时间实现的⽀付流程,⽀付是必须开通商户号,然后绑定要实现的⽀付的⼩程序。
1.后端代码
需要创建⼀些配置类package com .asa .utils .wxpay ;/** * ⽀付配置类 */public class WxPayConfig { //⼩程序appid public static final String appid = "***********; //⽀付的商户id public static final String mch_id = "**********;//商户号 //⽀付的商户密钥 public static final String key = "fsdgegwe24EDGFDGgegfetrfrwefger2";//商户的key //⽀付成功后的服务器回调url,回调函数的地址(就是⾃⼰写在Controller ⾥的回调函数)但是不许外⽹能访问(可以进⾏内⽹穿透) public static final String notify_url = "*********/asa/wmp/wxNotify"; //签名⽅式 public static final String SIGNTYPE = "MD5"; //交易类型 public static final String TRADETYPE = "JSAPI"; //统⼀下单接⼝地址 public static final String pay_url = "h.weixin.qq/pay/unifiedorder"; //AppSecret(⼩程序密钥) public static final String app_secret ="fb19e7c6f590ec17cfcd2ef8e2315acc";}
1
代码转换2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com .asa .utils .wxpay ;import java .util .Random ;/** * */public class StringUtils extends org .apache mons .lang .StringUtils { /** * StringUtils ⼯具类⽅法 * 获取⼀定长度的随机字符串,范围0-9,a-z * @param length :指定字符串长度 * @return ⼀定长度的随机字符串 */ public static String getRandomStringByLength (int length ) { String base = "abcdefghijklmnopqrstuvwxyz0123456789"; Random random = new Random (); StringBuffer sb = new StringBuffer (); for (int i = 0; i < length ; i ++) { int number = random .nextInt (base .length ()); sb .append (base .charAt (number )); } return sb .toString (); }}1234567891011121314151617181920212223242526272829package com .asa .utils .wxpay ;public class RandomUtil { public String getRandomCode (int codeLen ) { java .util .Random randomCode = new java .util .Random (); String strCode = ""; while (codeLen > 0) { int charCode = randomCode .nextInt (9); strCode += charCode ; codeLen --; } return strCode ; }}12345678910111213141516package com .asa .utils .wxpay ;import org .apache mons .codec .digest .DigestUtils ;import org .w3c .dom .Node ;import org .w3c .dom .NodeList ;import javax .xml .XMLConstants ;import javax .xml .parsers .DocumentBuilde
rFactory ;import java .io .*;import java .HttpURLConnection ;import java .URL ;import java .util .*;public class PayUtil {
12345678910111213141516
/** * 签名字符串 * @param "text 需要签名的字符串" * @param key 密钥 * @param "input_charset 编码格式" * @return 签名结果 */ public static String sign (String text , String key , String input_charset ) { text = text + "&key=" + key ; return DigestUtils .md5Hex (getContentBytes (text , input_charset )); } /** * 签名字符串 * @param "text 需要签名的字符串" * @param sign 签名结果 * @param "key 密钥" * @param input_charset 编码格式 * @return 签名结果 */ public static boolean verify (String text , String sign , String key , String input_charset ) { text = text + key ; String mysign = DigestUtils .md5Hex (getContentBytes (text , input_charset )); if (mysign .equals (sign )) { return true ; } else { return false ; } } /** * @param content * @param charset * @return * @throws * @throws UnsupportedEncodingException */ public static byte [] getContentBytes (String content , String charset ) { if (charset == null || "".equals (charset )) { return content .getBytes (); } try { return content .getBytes (charset ); } catch (UnsupportedEncodingException e ) { throw new RuntimeException ("MD5签名过程中出现错
误,指定的编码集不对,您⽬前指定的编码集是:" + charset ); } } private static boolean isValidChar (char ch ) { if ((ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) return true ; if ((ch >= 0x4e00 && ch <= 0x7fff ) || (ch >= 0x8000 && ch <= 0x952f )) return true ;// 简体中⽂汉字编码 return false ; } /** * 除去数组中的空值和签名参数 * @param "sArray" 签名参数组 * @return 去掉空值与签名参数后的新签名参数组 */ public static Map <String , String > paraFilter (Map <String , String > sArray ) { Map <String , String > result = new HashMap <String , String >(); if (sArray == null || sArray .size () <= 0) { return result ; } for (String key : sArray .keySet ()) { String value = sArray .get (key ); if (value == null || value .equals ("") || key .equalsIgnoreCase ("sign") || key .equalsIgnoreCase ("sign_type")) { continue ; }161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
} result .put (key , value ); } return result ; } /** * 把数组所有元素排序,并按照“参数=参数值”的模式⽤“&”字符拼接成字符串 * @param "params" 需要排序并参与字符拼接的参数组 * @return 拼接后字符串 */ public static String createLinkString (Map <String , String > params ) { List <String > keys = new ArrayList <String >(params .keySet ()); Collections .sort (keys ); String prestr = ""; for (int i = 0; i < keys .size (); i ++) { String key = keys .
get (i ); String value = params .get (key ); if (i == keys .size () - 1) {// 拼接时,不包括最后⼀个&字符 prestr = prestr + key + "=" + value ; } else { prestr = prestr + key + "=" + value + "&"; } } return prestr ; } /** * * @param "requestUrl 请求地址" * @param "requestMethod 请求⽅法" * @param "outputStr 参数" */ public static String httpRequest (String requestUrl ,String requestMethod ,String outputStr ){ // 创建SSLContext StringBuffer buffer = null ; try { URL url = new URL (requestUrl ); HttpURLConnection conn = (HttpURLConnection ) url .openConnection (); conn .setRequestMethod (requestMethod ); conn .setDoOutput (true ); conn .setDoInput (true ); conn .connect (); //往服务器端写内容 if (null !=outputStr ){ OutputStream os =conn .getOutputStream (); os .write (outputStr .getBytes ("utf-8")); os .close (); } // 读取服务器端返回的内容 InputStream is = conn .getInputStream (); InputStreamReader isr = new InputStreamReader (is , "utf-8"); BufferedReader br = new BufferedReader (isr ); buffer = new StringBuffer (); String line = null ; while ((line = br .readLine ()) != null ) { buffer .append (line ); } br .close (); }catch (Exception e ){ e .printStackTrace (); } return buffer .toString (); } public static String urlEncodeUTF8(String source ){ String result =source ; try { result =java .URLEncoder .encode (source , "UTF-8"); } catch (UnsupportedEncodingException e ) {
81828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
} catch (UnsupportedEncodingException e ) { // TODO Auto-generated catch block e .printStackTrace (); } return result ; } /** * 解析xml,返回第⼀级元素键值对。如果第⼀级元素有⼦节点,则此节点的值是⼦节点的xml 数据。 * @param strxml * @return * @throws JDOMException * @throws IOException */ public static Map doXMLParse (String strxml ) throws Exception { if (null == strxml || "".equals (strxml )) { return null ; } /*============= 注意,修复了官⽅反馈的漏洞,更新于2018-10-16 ===========*/ try { Map <String , String > data = new HashMap <String , String >(); // TODO 在这⾥更换 DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory .newInstance (); documentBuilderFactory .setFeature ("/xml/features/disallow-doctype-decl", true ); documentBuilderFactory .setFeature ("/sax/features/external-general-entities", false ); documentBuilderFactory .setFeature ("/sax/features/external-parameter-entities", false ); documentBuilderFactory .setFeature ("/xml/features/nonvalidating/load-external-dtd", false ); documentBuilderFactory .setFeature (XMLConstants .FEATURE_SECURE_PROCESSING , true ); documentBuilderFactory .setXIncludeAware (fa
lse ); documentBuilderFactory .setExpandEntityReferences (false ); InputStream stream = new ByteArrayInputStream (strxml .getBytes ("UTF-8")); org .w3c .dom .Document doc = documentBuilderFactory .newDocumentBuilder ().parse (stream ); doc .getDocumentElement ().normalize (); NodeList nodeList = doc .getDocumentElement ().getChildNodes (); for (int idx = 0; idx < nodeList .getLength (); ++idx ) { Node node = nodeList .item (idx ); if (node .getNodeType () == Node .ELEMENT_NODE ) { org .w3c .dom .Element element = (org .w3c .dom .Element ) node ; data .put (element .getNodeName (), element .getTextContent ()); } } try { stream .close (); } catch (Exception ex ) { // do nothing } return data ; } catch (Exception ex ) { throw ex ; } }// /**// * 获取⼦结点的xml // * @param children // * @return String // */// public static String getChildrenText(List children) {// StringBuffer sb = new StringBuffer();// if(!children.isEmpty()) {// Iterator it = children.iterator();// while(it.hasNext()) {// Element e = (Element) it.next();// String name = e.getName();// String value = e.getTextNormalize();// List list = e.getChildren();// sb.append("<" + name + ">");// if(!list.isEmpty()) {146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论