微信支付總結--小程序與H5頁面微信支付

項目開發過程中,涉及到了微信支付功能,這裏做一個詳細的記錄。

小程序和H5的後端代碼是通用的,前端調用不同的代碼實現,這裏不是重點,會簡單的給出相關的代碼。

微信支付,官方給了開發文檔,但是其中還是有一部分需要自己去摸索一下,剛開始接觸走一點彎路踩一點坑也比較正常。

當然微信支付這邊涉及到商戶平臺,需要進行驗證,使用的是公司的賬號,個人小程序沒有支付的權限。

1.開發之前的認知

先了解一下鋪墊的知識,會讓開發的思路更加的清楚,當時覺得這些沒啥用,現在回想回想這些流程確實會更加的明確開發的流程,這張時序圖就很清楚的描述了流程。這裏是小程序的支付模式。

 這裏知道了大概流程就可以了,是在沒辦法開發時比對自己的代碼邏輯,會發現跟這個時序圖還是完全吻合的。

需要:appid,商戶mchid,商戶祕鑰key

支付的開發步驟:

這裏官方文檔羅列了JSAPI與JSSDK之間的整體流程和一些小區別。H5進行支付時需要在後臺設置授權域名,當然也都需要設置微信支付通知的回調接口url,微信會向接口發送支付結果的通知,會按照一定的時間間隔進行通知,接收到支付結果的服務器返回微信成功或失敗結果,微信接收到成功結果便不會再進行消息的通知。

 2.代碼邏輯

瞭解了基本的流程之後,附上代碼爲敬。

 (1)前端簡單的流程就是點擊支付按鈕

(2)將支付金額等數據傳到後臺,後臺進行處理,並生成預支付訂單

//Controller方法 返回給小程序端需要的參數Map集合 
Map<String, Object> resultMap = new HashMap<String, Object>();
public class IpUtil {
	/** 
     * IpUtils工具類方法 
     * 獲取真實的ip地址 
     * @param request 
     * @return 
     */  
    public static 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();  
    }
}

 

public static Map<String, Object> wxPay(String ip,UserInfo user,int inviteAnswerId) throws Exception
	{	
		InviteAnswer answer = seekHelpAnswerService.getInviteAnswer(inviteAnswerId);
		
		Question question = seekHelpQuestionService.getQuestion(answer.questionId);//直接調固定的方法
		
		Account myAccount = seekHelpPayService.getUserAccount(user.id);
		
		BigDecimal qMoney = new BigDecimal(question.money.toString());
		
		BigDecimal totalMoney = new BigDecimal("0");
		
		if(null != answer.helperId && null != question.extraAward && question.extraAward != QuestionExtraAwardType.暫無.code)
		{
			totalMoney = SeniorBigDecimalUtil.add(qMoney, question.extraAwardMoney);
			
		}else{
			
			totalMoney = qMoney;
			
		}
		
		BigDecimal needPayMoney = SeniorBigDecimalUtil.sub(myAccount.money, totalMoney).abs();
		
		BigDecimal needPayMoneyFormatCent = SeniorBigDecimalUtil.mul(needPayMoney, new BigDecimal("100"));//將需要支付的金額轉換爲以分爲單位的金額
		
		Integer totalFee = needPayMoneyFormatCent.intValue();
		//Integer totalFee = 1;
		
        String nonce_str = WxPayOperate.getRandomStringByLength(32);  //生成的隨機字符串        
        
        String body = "求助支付";   //商品名稱            
        
        String out_trade_no = DateTimeOper.getStrForDate(new Date()) + inviteAnswerId;//充值訂單號
        
        
        Map<String, String> packageParams = new HashMap<String, String>();  //組裝參數,用戶生成統一下單接口的簽名  
        packageParams.put("appid", WxPayConfig.appid);  
        packageParams.put("mch_id", WxPayConfig.mch_id);  
        packageParams.put("nonce_str", nonce_str);  
        packageParams.put("body", body);  
        packageParams.put("out_trade_no", out_trade_no);//商戶訂單號  
        packageParams.put("total_fee", String.valueOf(totalFee));//支付金額,這邊需要轉成字符串類型,否則後面的簽名會失敗  
        packageParams.put("ip", ip);  
        packageParams.put("notify_url", WxPayConfig.notify_url);//支付成功後的回調地址  
        packageParams.put("trade_type", WxPayConfig.TRADETYPE);//支付方式  
        packageParams.put("openid", user.openId);
        
        String prestr = PayUtil.createLinkString(packageParams); // 把數組所有元素,按照“參數=參數值”的模式用“&”字符拼接成字符串   
        
        
        String mysign = PayUtil.sign(prestr, WxPayConfig.key, "utf-8").toUpperCase();//MD5運算生成簽名,這裏是第一次簽名,用於調用統一下單接口  
        

        String xml = "<xml>" + "<appid>" + WxPayConfig.appid + "</appid>"     //拼接統一下單接口使用的xml數據,要將上一步生成的簽名一起拼接進去  
                + "<body><![CDATA[" + body + "]]></body>"   
                + "<mch_id>" + WxPayConfig.mch_id + "</mch_id>"   
                + "<nonce_str>" + nonce_str + "</nonce_str>"   
                + "<notify_url>" + WxPayConfig.notify_url + "</notify_url>"   
                + "<openid>" + user.openId + "</openid>"   
                + "<out_trade_no>" + out_trade_no + "</out_trade_no>"   
                + "<ip>" + ip+ "</ip>"   
                + "<total_fee>" + String.valueOf(totalFee) + "</total_fee>"  
                + "<trade_type>" + WxPayConfig.TRADETYPE + "</trade_type>"   
                + "<sign>" + mysign + "</sign>"  
                + "</xml>";
        
        String result = PayUtil.httpRequest(WxPayConfig.pay_url, "POST", xml);//調用統一下單接口,並接受返回的結果        
  
        Map<?, ?> map = PayUtil.doXMLParse(result);// 將解析結果存儲在HashMap中   
        
        String return_code = (String) map.get("return_code");//返回狀態碼
        
        Map<String, Object> resultMap = new HashMap<String, Object>();//返回給小程序端需要的參數 
        
        if(return_code.equals("SUCCESS"))
        {     
        	
          String result_code = (String)map.get("result_code");       
          
          if(result_code.equals("SUCCESS"))
          {
        	  String prepay_id = (String) map.get("prepay_id");//返回的預付單信息     	      	  
        	  
              resultMap.put("nonceStr", nonce_str);                           
              
              resultMap.put("package", "prepay_id=" + prepay_id);  
              
              Long timeStamp = System.currentTimeMillis() / 1000;     

              resultMap.put("timeStamp", timeStamp + "");//這邊要將返回的時間戳轉化成字符串,不然小程序端調用wx.requestPayment方法會報簽名錯誤  
              
              String stringSignTemp = "appId=" + WxPayConfig.appid + "&nonceStr=" + nonce_str + "&package=prepay_id=" + prepay_id+ "&signType=MD5&timeStamp=" + timeStamp;  //拼接簽名需要的參數     
             
              String paySign = PayUtil.sign(stringSignTemp, WxPayConfig.key, "utf-8").toUpperCase();   //再次簽名,這個簽名用於小程序端調用wx.requesetPayment方法  
                  
              resultMap.put("paySign", paySign);             
              
          }else{
        	  return_code = "FAIL";//result_code決定最終請求結果,result_code爲FAIL,則表示請求支付失敗,return_code也置爲FAIL
        	  
        	  String err_code = (String)map.get("err_code");
        	  
        	  String err_code_des = (String) map.get("err_code_des");
        	  
        	  order.err_code = err_code;
        	  
        	  order.err_code_des = err_code_des;
          }
           
        }  
          
        resultMap.put("appid", WxPayConfig.appid); 
        
        resultMap.put("flag", return_code);
        
        resultMap.put("tradeNo", out_trade_no);
          
        return resultMap;
	}

不好的習慣,代碼的註釋寫的很少。大致的流程就是就官方要求的參加添加到Map中,然後將元素轉換成“參數=參數值”的模式用“&”字符拼接成字符串,使用PayUtil.sign方法與商戶祕鑰key進行參數第一次簽名,後面統一下單接口調用需要使用。

拼接統一下單接口使用的xml數據,post請求統一下單接口,https://api.mch.weixin.qq.com/pay/unifiedorder,獲取統一下單接口返回的xml格式數據,解析返回的xml數據,保存在map中,根據返回的狀態碼判斷下單是否成功。如果成功,將成功的信息返回給小程序端準備調用微信app的支付功能。

這部分多看看官方的文檔,會有比較詳細的流程,下單請求需要的參數,以及返回的數據字段等等。

  • 元素轉換成“參數=參數值”的模式用“&”字符拼接成字符串
/**   
     * 把數組所有元素排序,並按照“參數=參數值”的模式用“&”字符拼接成字符串   
     * @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(value != null && (!key.equals("sign")))
            {
            	if (i == keys.size() - 1) {// 拼接時,不包括最後一個&字符     
                    prestr = prestr + key + "=" + value;     
                } else {     
                    prestr = prestr + key + "=" + value + "&";     
                } 
            }
                
        }     
        return prestr;     
    } 
  •  MD5運算簽名
    /**   
     * 簽名字符串   
     * @param text需要簽名的字符串   
     * @param key 密鑰   
     * @param input_charset編碼格式   
     * @return 簽名結果   
	 * @throws Exception 
     */     
    public static String sign(String text, String key, String input_charset) throws Exception {     
        text = text + "&key=" + key;        
        return MD5(text).toUpperCase();
    }

 

    /**
     * 生成 MD5
     *
     * @param data 待處理數據
     * @return MD5結果
     */
    public static String MD5(String data) throws Exception {
        java.security.MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] array = md.digest(data.getBytes("UTF-8"));
        StringBuilder sb = new StringBuilder();
        for (byte item : array) {
            sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
        }
        return sb.toString().toUpperCase();
    }

 

  • 拼接xml格式數據 
  • post請求統一下單地址

使用了最基本的HttpURLConnection方式,這裏可以自己更好的實現,目的是獲取返回的結果

    /**   
     *   
     * @param requestUrl請求地址   
     * @param requestMethod請求方法   
     * @param outputStr參數   
     */     
    public static String httpRequest(String requestUrl,String requestMethod,String outputStr){        
        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);     
            }     
        }catch(Exception e){     
            e.printStackTrace();     
        }  
        return buffer.toString();  
    
  • 解析xml數據
    /** 
     * 解析xml,返回第一級元素鍵值對。如果第一級元素有子節點,則此節點的值是子節點的xml數據。 
     * @param strxml 
     * @return 
     * @throws JDOMException 
     * @throws IOException 
     */  
    public static Map<String, String> doXMLParse(String strxml) throws Exception {  
        if(null == strxml || "".equals(strxml)) {  
            return null;  
        }  
          
        Map<String, String> m = new HashMap<String, String>();  
        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) throws UnsupportedEncodingException {  
        return new ByteArrayInputStream(str.getBytes("UTF-8"));  
    }
  •  重要的地方,二次簽名
//拼接簽名需要的參數
String stringSignTemp = "appId=" + WxPayConfig.appid + "&nonceStr=" + nonce_str + "&package=prepay_id=" + prepay_id+ "&signType=MD5&timeStamp=" + timeStamp;       
             
//再次簽名,這個簽名用於小程序端調用wx.requesetPayment方法
String paySign = PayUtil.sign(stringSignTemp, WxPayConfig.key, "utf-8").toUpperCase();     

 3.小程序端獲取預支付訂單數據,調用支付組件

/**
 * 充值並支付成功回調
 */
function rechargeAndPaySuc(data) {
  if (data.flag === "SUCCESS") {
    var timeStamp = data.timeStamp;
    var nonceStr = data.nonceStr;
    var pack = data.package;
    var paySign = data.paySign;
    tradeNo = data.tradeNo;
    wx.requestPayment({
      timeStamp: timeStamp,
      nonceStr: nonceStr,
      package: pack,
      signType: 'MD5',
      paySign: paySign,
      success: function (re) {
        //支付成功 
        
      },
      fail: function (re) {
        
      //  cancalPay();
      },
      complete: function (re) {

        if (re.errMsg == "requestPayment:fail cancel") {
         cancalPay();
        } else if (re.errMsg == "requestPayment:ok") {
         //進行一些頁面邏輯的處理
        } else {        
          cancalPay();
        }

      }
    })
  } else {
    //調用微信支付接口生成預付訂單失敗
    cancalPay();
  }
}

這裏選擇在complete回調函數進行頁面的處理,但是真正的業務邏輯確認需要在微信通知結果獲取後進行處理,這裏的返回結果並不一定準確。

4.微信通知支付結果,根據設置的結果回調url進行處理

    /**
	* @Title: wxPayNotify
	* @Description: 支付回調通知  微信異步通知
	* 訂單待確認狀態
	* 
	* 如果訂單確認,則進行賬戶金額的劃轉
	* 
	* 如果訂單沒有支付成功,則返回給失敗狀態給客戶端
	* 
	* @param @param request
	* @param @param response
	* @param @throws Exception    
	* @return String    
	* @throws
	*/ 
	@RequestMapping("/wxPayNotify")
	@ResponseBody
	public String wxPayNotify(HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		InputStream inputStream = null;
		
		inputStream = request.getInputStream();
		
		StringBuffer sb = new StringBuffer();
		
		BufferedReader in = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
		
		String line = null;
		
		while((line = in.readLine()) != null)
		{
			sb.append(line);
		}
		
		in.close();
			
		inputStream.close();
		
		String result = seekHelpPayService.processWxPayNotifyInfoToDB(sb.toString());
		
		String xml = null;
		
		if(result.equals("success"))
		{
			xml = "<xml>" + "<return_code><![CDATA[" + "SUCCESS" + "]]></return_code>"   
	                + "<return_msg><![CDATA[" + "OK" + "]]></return_msg>"  
	                + "</xml>";
		}
		
		return xml;
	}

這裏就是對獲取的微信支付通知結果進行的處理。

整個單機系統的微信支付流程就完成了,首先最重要的還是要看微信的官方文檔,明白開發的流程,理解了流程,剩下就是業務邏輯的處理了,對於開發人員並沒有太大的難度。

H5頁面與小程序端對比,前端調用有所不同,這裏的H5支付是在微信環境中的H5

H5頁面js:

        $.ajax({
    		url:urlHeader + "/xxx/xxxx",
    		type:"post",
    		dataType:"json",
    		data:{
    			xxxxxx		
    		},
    		success:function(data){
    			console.log("預支付訂單請求成功:");
    			if(data.flag == "SUCCESS"){
        			appId = data.appid;
        			timeStamp = data.timeStamp;
        			nonceStr = data.nonceStr;
        			packageStr = data.packageStr;
        			signType = data.signType;
        			paySign = data.paySign;
        			out_trade_no = data.tradeNo;
    			}		
    			
    			callPay();
    		},
    		error:function(data){
    			console.log(data);
    			alert("支付失敗");
    		}
    	})

下面的兩個js方法是官方提供的,大致意思是調用微信內置的js 

function onBridgeReady(){
	console.log("申請支付頁面");	
	
	WeixinJSBridge.invoke(
		      'getBrandWCPayRequest', {
		    	  "appId":appId,
		    	  "timeStamp":timeStamp,
		    	  "nonceStr":nonceStr,
		    	  "package":packageStr,
		    	  "signType":signType,
		    	  "paySign":paySign
		      },
		      function(res){
		    	  console.log("支付請求返回結果");
		    	  console.log(res);
		      if(res.err_msg == "get_brand_wcpay_request:ok" ){
		      // 使用以上方式判斷前端返回,微信團隊鄭重提示:
		      //res.err_msg將在用戶支付成功後返回ok,但並不保證它絕對可靠。
		    	  //執行成功後的頁面邏輯

		      }else if(res.err_msg == "get_brand_wcpay_request:fail"){
		    	  alert("支付失敗");
		      } 
		   });
}

function callPay(){
	if (typeof WeixinJSBridge == "undefined"){
		   if( document.addEventListener ){
		       document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
		   }else if (document.attachEvent){
		       document.attachEvent('WeixinJSBridgeReady', onBridgeReady); 
		       document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
		   }
		}else{
		   onBridgeReady();
		}
}

 

基本的流程就是這樣了,代碼寫的比較差,持續努力中。

如有問題,歡迎添加我的微信:llbbaa

一起交流,共同學習。。。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章