Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

微信支付 HTML5 頁面 WAP 端接入實戰

編輯:Android 開發實例

      一、前言

公司的營收主要來自支付寶與微信支付。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代碼
  1. public String CreateWapUrl(String outTradeNo, String ip) throws SDKRuntimeException {    
  2.     HashMap<String, Object> param = new HashMap<String, Object>();    
  3.     param.put("appid", WxPayConfig.APPID);    
  4.     param.put("mch_id", WxPayConfig.MCHID);    
  5.     param.put("nonce_str", CommonUtil.CreateNoncestr());    
  6.     param.put("body", "產品測試");    
  7.     param.put("out_trade_no", outTradeNo);    
  8.     param.put("total_fee", 1);    
  9.     param.put("spbill_create_ip", ip);    
  10.     param.put("notify_url", WxPayConfig.NOTIFYURL);    
  11.     param.put("trade_type", "WAP");    
  12.     param.put("sign", getSign(param));    
  13.     return CommonUtil.MapToXml(param);    
  14. }    

(2) 取得簽名值

Java代碼
  1. public String getSign(HashMap<String, Object> param) throws SDKRuntimeException {    
  2.     String sign="";    
  3.     String content = CommonUtil.FormatParamMap(param);    
  4.     sign =  Sign(content, WxPayConfig.KEY);    
  5.     return sign;    
  6. }    
  7.     
  8. public static String Sign(String content, String key) throws SDKRuntimeException {    
  9.     String signStr = "";    
  10.     if ("" == key) {    
  11.         throw new SDKRuntimeException("財付通簽名key不能為空!");    
  12.     }    
  13.     if ("" == content) {    
  14.         throw new SDKRuntimeException("財付通簽名內容不能為空");    
  15.     }    
  16.     signStr = content + "&key=" + key;    
  17.     return MD5Util.MD5(signStr).toUpperCase();    
  18. }    

(3) 工具類方法

Java代碼
  1. public static boolean IsNumeric(String str) {    
  2.     if (str.matches("\\d *")) {    
  3.         return true;    
  4.     } else {    
  5.         return false;    
  6.     }    
  7. }    
  8.     
  9. //map轉成xml    
  10. public static String MapToXml(HashMap<String, Object> arr) {    
  11.     String xml = "<xml>";    
  12.         
  13.     Iterator<Entry<String, Object>> iter = arr.entrySet().iterator();    
  14.     while (iter.hasNext()) {    
  15.         Entry<String, Object> entry = iter.next();    
  16.         String key = entry.getKey();    
  17.         String val = entry.getValue()+"";    
  18.         if (IsNumeric(val)) {    
  19.             xml += "<" + key + ">" + val + "</" + key + ">";    
  20.     
  21.         } else    
  22.         xml += "<" + key + "><![CDATA[" + val + ]]></" + key + ">";    
  23.     }    
  24.     
  25.     xml += "</xml>";    
  26.     return xml;    
  27. }    
  28.     
  29. //xml轉成map    
  30. @SuppressWarnings("unchecked")    
  31. public static Map<String, String> parseXml(String xml) throws Exception {    
  32.       Map<String, String> map = new HashMap<String, String>();    
  33.       Document document = DocumentHelper.parseText(xml);    
  34.       Element root = document.getRootElement();    
  35.       List<Element> elementList = root.elements();    
  36.       for (Element e : elementList) {    
  37.          map.put(e.getName(), e.getText());    
  38.       }    
  39.       return map;    
  40. }    
  41.     
  42.     
  43. public static String FormatParamMap(HashMap<String, Object> parameters) throws SDKRuntimeException {    
  44.     String buff = "";    
  45.     try {    
  46.         List<Map.Entry<String, Object>> infoIds = new ArrayList<Map.Entry<String, Object>>(    
  47.                 parameters.entrySet());    
  48.         Collections.sort(infoIds,    
  49.                 new Comparator<Map.Entry<String, Object>>() {    
  50.                    public int compare(Map.Entry<String, Object> o1,    
  51.                             Map.Entry<String, Object> o2) {    
  52.                               return (o1.getKey()).toString().compareTo(    
  53.                                 o2.getKey());    
  54.                       }    
  55.                 });    
  56.     
  57.         for (int i = 0; i < infoIds.size(); i++) {    
  58.             Map.Entry<String, Object> item = infoIds.get(i);    
  59.             if (item.getKey() != "") {    
  60.                 buff += item.getKey() + "="    
  61.                         + URLEncoder.encode(item.getValue()+"", "utf-8") + "&";    
  62.             }    
  63.         }    
  64.         if (buff.isEmpty() == false) {    
  65.             buff = buff.substring(0, buff.length() - 1);    
  66.         }    
  67.     } catch (Exception e) {    
  68.         throw new SDKRuntimeException(e.getMessage());    
  69.     }    
  70.     return buff;    
  71. }    
  72.     
  73. public static String CreateNoncestr() {    
  74.     String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";    
  75.     String res = "";    
  76.     for (int i = 0; i < 16; i++) {    
  77.         Random rd = new Random();    
  78.         res += chars.charAt(rd.nextInt(chars.length() - 1));    
  79.     }    
  80.     return res;    
  81. }    

(4) 發送請求的方法

Java代碼
  1. public static String sendPost(String url, String param,String charset) {    
  2.         PrintWriter out = null;    
  3.         BufferedReader in = null;    
  4.         String result = "";    
  5.         try {    
  6.             URL realUrl = new URL(url);    
  7.             // 打開和URL之間的連接    
  8.             URLConnection conn = realUrl.openConnection();    
  9.             // 設置通用的請求屬性    
  10.             conn.setRequestProperty("accept", "*/*");    
  11.             conn.setRequestProperty("connection", "Keep-Alive");    
  12.             conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");    
  13.                
  14.             // 發送POST請求必須設置如下兩行    
  15.             conn.setDoOutput(true);    
  16.             conn.setDoInput(true);    
  17.             // 獲取URLConnection對象對應的輸出流    
  18.             out = new PrintWriter(conn.getOutputStream());    
  19.             // 發送請求參數    
  20.             out.print(new String(param.getBytes(),charset));    
  21.             // flush輸出流的緩沖    
  22.             out.flush();    
  23.             // 定義BufferedReader輸入流來讀取URL的響應    
  24.             in = new BufferedReader(new InputStreamReader(conn.getInputStream(), charset));    
  25.             String line;    
  26.             while ((line = in.readLine()) != null) {    
  27.                 result += line;    
  28.             }    
  29.         } catch (Exception e) {    
  30.             e.printStackTrace();    
  31.         }    
  32.         //使用finally塊來關閉輸出流、輸入流    
  33.         finally{    
  34.             try{    
  35.                 if(out!=null){    
  36.                     out.close();    
  37.                }    
  38.                 if(in!=null){    
  39.                     in.close();    
  40.                }    
  41.             }    
  42.             catch(IOException ex){    
  43.                 ex.printStackTrace();    
  44.             }    
  45.         }    
  46.         return result;    
  47.     }      

(5) 執行接口

Java代碼
  1. //網頁版微信支付接口    
  2. public String wxWapPay() throws Exception {    
  3.     String result = SUCCESS;    
  4.     String message = "";    
  5.     int code = 0;    
  6.     try {    
  7.         String ip = getIpAddr(request);    
  8.         String outTradeNo = new SimpleDateFormat("YYYYMMDDHHmmssSSS").format(new Date())+"-wap";    
  9.         String param = new WxPayHelper().CreateWapUrl(outTradeNo, ip);    
  10.         String resp = HttpRequest.sendPost(WxPayConfig.UNIFIEDORDER_INTERFACE, param, "utf-8");    
  11.         Map<String, String> res = CommonUtil.parseXml(resp);    
  12.             
  13.         if(res.get("return_code") == "SUCCESS") {    
  14.             if(res.get("result_code") == "SUCCESS") {    
  15.                 message = res.get("code_url");    
  16.             }else {    
  17.                 code = -1;    
  18.                 message = res.get("err_code_des");    
  19.                 logger.error("wxWapPay error code"+res.get("err_code")+", reason is "+res.get("err_code_des"));    
  20.             }    
  21.         }else {    
  22.             code = -1;    
  23.             message = res.get("return_msg");    
  24.             logger.error("wxWapPay error reason is "+res.get("return_msg"));    
  25.         }    
  26.     } catch (Exception e) {    
  27.         code = -1;    
  28.         logger.error("wxWapPay Exception reason is "+ e);    
  29.         e.printStackTrace();    
  30.     }    
  31.     dataMap = new HashMap<String, Object>();    
  32.     dataMap.put("code", code);    
  33.     dataMap.put("message", message);    
  34.         
  35.     return result;    
  36. }    
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved