您好,登錄后才能下訂單哦!
這篇文章主要為大家詳細介紹了小程序后端開發,文中示例代碼介紹的非常詳細,零基礎也能參考此文章,感興趣的小伙伴們可以參考一下。
PayController
@Api(tags = "支付模塊") @RestController @RequestMapping("") public class PayController { @ApiOperation(value = "請求支付接口") @RequestMapping(value = "/wxPay", method = RequestMethod.POST) public JSONObject wxPay(HttpServletRequest request) { try { //生成的隨機字符串 String nonce_str = getRandomStringByLength(32); //商品名稱 String body = "測試商品名稱"; //獲取客戶端的ip地址 String spbill_create_ip = getIpAddr(request); //組裝參數,用戶生成統一下單接口的簽名 Map<String, String> packageParams = new HashMap<>(); packageParams.put("appid", WechatConfig.appid); packageParams.put("mch_id", WechatConfig.mch_id); packageParams.put("nonce_str", nonce_str); packageParams.put("body", body); packageParams.put("out_trade_no", payOrderId + "");//商戶訂單號,自己的訂單ID packageParams.put("total_fee", 100 + "");//支付金額,這邊需要轉成字符串類型,否則后面的簽名會失敗 packageParams.put("spbill_create_ip", spbill_create_ip); packageParams.put("notify_url", WechatConfig.notify_url);//支付成功后的回調地址 packageParams.put("trade_type", WechatConfig.TRADETYPE);//支付方式 packageParams.put("openid", openId + "");//用戶的openID,自己獲取 String prestr = PayUtil.createLinkString(packageParams); // 把數組所有元素,按照“參數=參數值”的模式用“&”字符拼接成字符串 //MD5運算生成簽名,這里是第一次簽名,用于調用統一下單接口 String mysign = PayUtil.sign(prestr, WechatConfig.key, "utf-8").toUpperCase(); //拼接統一下單接口使用的xml數據,要將上一步生成的簽名一起拼接進去 String xml = "<xml>" + "<appid>" + WechatConfig.appid + "</appid>" + "<body><![CDATA[" + body + "]]></body>" + "<mch_id>" + WechatConfig.mch_id + "</mch_id>" + "<nonce_str>" + nonce_str + "</nonce_str>" + "<notify_url>" + WechatConfig.notify_url + "</notify_url>" + "<openid>" + openid + "</openid>" + "<out_trade_no>" + payOrderId + "</out_trade_no>" + "<spbill_create_ip>" + spbill_create_ip + "</spbill_create_ip>" + "<total_fee>" + 100 + "</total_fee>"//支付的金額,單位:分 + "<trade_type>" + WechatConfig.TRADETYPE + "</trade_type>" + "<sign>" + mysign + "</sign>" + "</xml>"; //調用統一下單接口,并接受返回的結果 String result = PayUtil.httpRequest(WechatConfig.pay_url, "POST", xml); // 將解析結果存儲在HashMap中 Map map = PayUtil.doXMLParse(result); String return_code = (String) map.get("return_code");//返回狀態碼 String result_code = (String) map.get("result_code");//返回狀態碼 Map<String, Object> response = new HashMap<String, Object>();//返回給小程序端需要的參數 if (return_code == "SUCCESS" && return_code.equals(result_code)) { String prepay_id = (String) map.get("prepay_id");//返回的預付單信息 response.put("nonceStr", nonce_str); response.put("package", "prepay_id=" + prepay_id); Long timeStamp = System.currentTimeMillis() / 1000; response.put("timeStamp", timeStamp + "");//這邊要將返回的時間戳轉化成字符串,不然小程序端調用wx.requestPayment方法會報簽名錯誤 //拼接簽名需要的參數 String stringSignTemp = "appId=" + WechatConfig.appid + "&nonceStr=" + nonce_str + "&package=prepay_id=" + prepay_id + "&signType=MD5&timeStamp=" + timeStamp; //再次簽名,這個簽名用于小程序端調用wx.requesetPayment方法 String paySign = PayUtil.sign(stringSignTemp, WechatConfig.key, "utf-8").toUpperCase(); response.put("paySign", paySign); } response.put("appid", WechatConfig.appid); return Response.succ(response); } catch (Exception e) { e.printStackTrace(); } return null; } //這里是支付回調接口,微信支付成功后會自動調用 @RequestMapping(value = "/wxNotify", method = RequestMethod.POST) public void wxNotify(HttpServletRequest request, HttpServletResponse response) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream())); String line = null; StringBuilder sb = new StringBuilder(); while ((line = br.readLine()) != null) { sb.append(line); } br.close(); //sb為微信返回的xml String notityXml = sb.toString(); String resXml = ""; Map map = PayUtil.doXMLParse(notityXml); String returnCode = (String) map.get("return_code"); if ("SUCCESS".equals(returnCode)) { //驗證簽名是否正確 Map<String, String> validParams = PayUtil.paraFilter(map); //回調驗簽時需要去除sign和空值參數 String prestr = PayUtil.createLinkString(validParams); //根據微信官網的介紹,此處不僅對回調的參數進行驗簽,還需要對返回的金額與系統訂單的金額進行比對等 if (PayUtil.verify(prestr, (String) map.get("sign"), WechatConfig.key, "utf-8")) { /**此處添加自己的業務邏輯代碼start**/ //注意要判斷微信支付重復回調,支付成功后微信會重復的進行回調 /**此處添加自己的業務邏輯代碼end**/ //通知微信服務器已經支付成功 resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>" + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> "; } } else { resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[報文為空]]></return_msg>" + "</xml> "; } BufferedOutputStream out = new BufferedOutputStream( response.getOutputStream()); out.write(resXml.getBytes()); out.flush(); out.close(); } //獲取隨機字符串 private 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(); } //獲取IP private String getIpAddr(HttpServletRequest request) { String ip = request.getHeader("X-Forwarded-For"); if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) { //多次反向代理后會有多個ip值,第一個ip才是真實ip int index = ip.indexOf(","); if (index != -1) { return ip.substring(0, index); } else { return ip; } } ip = request.getHeader("X-Real-IP"); if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) { return ip; } return request.getRemoteAddr(); } }
上面代碼用到了PayUtil和WechatConfig這兩個類,一個是配置類,一個是工具類,代碼如下:
PayUtil
public class PayUtil { /** * 簽名字符串 * * @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 java.security.SignatureException * @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; } result.put(key, value); } return result; } /** * 把數組所有元素排序,并按照“參數=參數值”的模式用“&”字符拼接成字符串 * * @param params 需要排序并參與字符拼接的參數組 * @return 拼接后字符串 */ public static String createLinkString(Map<String, String> params) { List<String> keys = new ArrayList<>(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.net.URLEncoder.encode(source, "UTF-8"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return result; } /** * 解析xml,返回第一級元素鍵值對。如果第一級元素有子節點,則此節點的值是子節點的xml數據。 * * @param strxml * @return * @throws org.jdom2.JDOMException * @throws IOException */ public static Map doXMLParse(String strxml) throws Exception { if (null == strxml || "".equals(strxml)) { return null; } Map m = new HashMap(); InputStream in = String2Inputstream(strxml); SAXBuilder builder = new SAXBuilder(); Document doc = builder.build(in); Element root = doc.getRootElement(); List list = root.getChildren(); Iterator it = list.iterator(); while (it.hasNext()) { Element e = (Element) it.next(); String k = e.getName(); String v = ""; List children = e.getChildren(); if (children.isEmpty()) { v = e.getTextNormalize(); } else { v = getChildrenText(children); } m.put(k, v); } //關閉流 in.close(); return m; } /** * 獲取子結點的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()) { sb.append(getChildrenText(list)); } sb.append(value); sb.append("</" + name + ">"); } } return sb.toString(); } public static InputStream String2Inputstream(String str) { return new ByteArrayInputStream(str.getBytes()); } }
WechatConfig
public class WechatConfig { //小程序appid public static final String appid = ""; //微信支付的商戶id public static final String mch_id = ""; //微信支付的商戶密鑰 public static final String key = ""; //支付成功后的服務器回調url,這里填PayController里的回調函數地址 public static final String notify_url = ""; //簽名方式,固定值 public static final String SIGNTYPE = "MD5"; //交易類型,小程序支付的固定值為JSAPI public static final String TRADETYPE = "JSAPI"; //微信統一下單接口地址 public static final String pay_url = "https://api.mch.weixin.qq.com/pay/unifiedorder"; }
在剛剛開始接觸小程序支付的時候,也覺得比較的棘手,因為自己并沒有寫過支付相關的代碼。后來通過百度查找資料和閱讀官方文檔,最后把這個支付的controller完成了。最后,一定要多讀幾遍官方文檔,然后結合PayController的代碼去看,就會發現其實支付也不是很難。
以上就是小程序后端的具體操作,代碼詳細清楚,如果在日常工作遇到這個問題,希望你能通過這篇文章解決問題。如果想了解更多相關內容,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。