一、前言
公司的營收主要來自支付寶與微信支付。App 端已經成功接入,這次要挑戰的是 WAP 端。這個功能需要前端頁面與後端接口協同完成,於是便有了這篇記錄整個接入過程的文章。
二、接口接入
由於微信支付版本更新,網上能找到的 demo 大多是 V2.5 版,已經無法使用。翻了不少資料後,我鎖定了最新的 V3 版本。
我找到了一個統一下單接口,文件入口可供查閱。它的接口位址為:
https://api.mch.weixin.qq.com/pay/unifiedorder
接著,就開始接入 WAP 端所需的參數。其中幾個關鍵參數是 Appid、mch_id 與 key。appid 和 mch_id 在公眾平台取得;key 值則在商戶平台(pay.weixin.qq.com)的「賬戶設置 → API 安全 → 密鑰設置」中自行設定。
坑一:若 key 值設定不正確,會出現「支付權限查詢失敗」的錯誤。此時請檢查 appid、mch_id 所屬公眾號對應商戶號的 key 是否正確。
坑二:開發過程中我還遇到「您沒有 WAP 支付權限」的錯誤。網上翻很久都找不到同樣案例,只好發郵件給微信支付(weixinpay@tencent.com、wepayTS@tencent.com),結果石沉大海。後來打通了商戶平台客服電話(0755-86018333),客服MM大概不碰技術問題,要我去提問平台提交問題,說技術人員看到會回覆,但何時回覆也說不準。打開客服給的網址才發現,表單裡既沒有 WAP 端選項,也沒有「統一下單」這個說法,最後只能選「網頁(JSAPI)支付」提交,系統提示七天內回覆——業務那麼急,實在等不起。
三、程式碼編寫
(1) 取得統一下單參數
Java代碼
- public String CreateWapUrl(String outTradeNo, String ip) throws SDKRuntimeException {
- HashMap<String, Object> param = new HashMap<String, Object>();
- param.put("appid", WxPayConfig.APPID);
- param.put("mch_id", WxPayConfig.MCHID);
- param.put("nonce_str", CommonUtil.CreateNoncestr());
- param.put("body", "產品測試");
- param.put("out_trade_no", outTradeNo);
- param.put("total_fee", 1);
- param.put("spbill_create_ip", ip);
- param.put("notify_url", WxPayConfig.NOTIFYURL);
- param.put("trade_type", "WAP");
- param.put("sign", getSign(param));
- return CommonUtil.MapToXml(param);
- }
(2) 取得簽名值
Java代碼
- public String getSign(HashMap<String, Object> param) throws SDKRuntimeException {
- String sign="";
- String content = CommonUtil.FormatParamMap(param);
- sign = Sign(content, WxPayConfig.KEY);
- return sign;
- }
-
- public static String Sign(String content, String key) throws SDKRuntimeException {
- String signStr = "";
- if ("" == key) {
- throw new SDKRuntimeException("財付通簽名key不能為空!");
- }
- if ("" == content) {
- throw new SDKRuntimeException("財付通簽名內容不能為空");
- }
- signStr = content + "&key=" + key;
- return MD5Util.MD5(signStr).toUpperCase();
- }
(3) 工具類方法
Java代碼
- public static boolean IsNumeric(String str) {
- if (str.matches("\\d *")) {
- return true;
- } else {
- return false;
- }
- }
-
- //map轉成xml
- public static String MapToXml(HashMap<String, Object> arr) {
- String xml = "<xml>";
-
- Iterator<Entry<String, Object>> iter = arr.entrySet().iterator();
- while (iter.hasNext()) {
- Entry<String, Object> entry = iter.next();
- String key = entry.getKey();
- String val = entry.getValue()+"";
- if (IsNumeric(val)) {
- xml += "<" + key + ">" + val + "</" + key + ">";
-
- } else
- xml += "<" + key + "><![CDATA[" + val + ]]></" + key + ">";
- }
-
- xml += "</xml>";
- return xml;
- }
-
- //xml轉成map
- @SuppressWarnings("unchecked")
- public static Map<String, String> parseXml(String xml) throws Exception {
- Map<String, String> map = new HashMap<String, String>();
- Document document = DocumentHelper.parseText(xml);
- Element root = document.getRootElement();
- List<Element> elementList = root.elements();
- for (Element e : elementList) {
- map.put(e.getName(), e.getText());
- }
- return map;
- }
-
-
- public static String FormatParamMap(HashMap<String, Object> parameters) throws SDKRuntimeException {
- String buff = "";
- try {
- List<Map.Entry<String, Object>> infoIds = new ArrayList<Map.Entry<String, Object>>(
- parameters.entrySet());
- Collections.sort(infoIds,
- new Comparator<Map.Entry<String, Object>>() {
- public int compare(Map.Entry<String, Object> o1,
- Map.Entry<String, Object> o2) {
- return (o1.getKey()).toString().compareTo(
- o2.getKey());
- }
- });
-
- for (int i = 0; i < infoIds.size(); i++) {
- Map.Entry<String, Object> item = infoIds.get(i);
- if (item.getKey() != "") {
- buff += item.getKey() + "="
- + URLEncoder.encode(item.getValue()+"", "utf-8") + "&";
- }
- }
- if (buff.isEmpty() == false) {
- buff = buff.substring(0, buff.length() - 1);
- }
- } catch (Exception e) {
- throw new SDKRuntimeException(e.getMessage());
- }
- return buff;
- }
-
- public static String CreateNoncestr() {
- String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
- String res = "";
- for (int i = 0; i < 16; i++) {
- Random rd = new Random();
- res += chars.charAt(rd.nextInt(chars.length() - 1));
- }
- return res;
- }
(4) 發送請求的方法
Java代碼
- public static String sendPost(String url, String param,String charset) {
- PrintWriter out = null;
- BufferedReader in = null;
- String result = "";
- try {
- URL realUrl = new URL(url);
- // 打開和URL之間的連接
- URLConnection conn = realUrl.openConnection();
- // 設置通用的請求屬性
- conn.setRequestProperty("accept", "*/*");
- conn.setRequestProperty("connection", "Keep-Alive");
- conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
-
- // 發送POST請求必須設置如下兩行
- conn.setDoOutput(true);
- conn.setDoInput(true);
- // 獲取URLConnection對象對應的輸出流
- out = new PrintWriter(conn.getOutputStream());
- // 發送請求參數
- out.print(new String(param.getBytes(),charset));
- // flush輸出流的緩沖
- out.flush();
- // 定義BufferedReader輸入流來讀取URL的響應
- in = new BufferedReader(new InputStreamReader(conn.getInputStream(), charset));
- String line;
- while ((line = in.readLine()) != null) {
- result += line;
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- //使用finally塊來關閉輸出流、輸入流
- finally{
- try{
- if(out!=null){
- out.close();
- }
- if(in!=null){
- in.close();
- }
- }
- catch(IOException ex){
- ex.printStackTrace();
- }
- }
- return result;
- }
(5) 執行接口
Java代碼
- //網頁版微信支付接口
- public String wxWapPay() throws Exception {
- String result = SUCCESS;
- String message = "";
- int code = 0;
- try {
- String ip = getIpAddr(request);
- String outTradeNo = new SimpleDateFormat("YYYYMMDDHHmmssSSS").format(new Date())+"-wap";
- String param = new WxPayHelper().CreateWapUrl(outTradeNo, ip);
- String resp = HttpRequest.sendPost(WxPayConfig.UNIFIEDORDER_INTERFACE, param, "utf-8");
- Map<String, String> res = CommonUtil.parseXml(resp);
-
- if(res.get("return_code") == "SUCCESS") {
- if(res.get("result_code") == "SUCCESS") {
- message = res.get("code_url");
- }else {
- code = -1;
- message = res.get("err_code_des");
- logger.error("wxWapPay error code"+res.get("err_code")+", reason is "+res.get("err_code_des"));
- }
- }else {
- code = -1;
- message = res.get("return_msg");
- logger.error("wxWapPay error reason is "+res.get("return_msg"));
- }
- } catch (Exception e) {
- code = -1;
- logger.error("wxWapPay Exception reason is "+ e);
- e.printStackTrace();
- }
- dataMap = new HashMap<String, Object>();
- dataMap.put("code", code);
- dataMap.put("message", message);
-
- return result;
- }