微信小程序接入微信支付(二):后台调用统一下单接口

微信统一支付官方文档:https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=9_1

因该接口需要商户系统中自己的订单编号,笔者先在后台生成订单后将订单编号传到了小程序端,通过wx.request传到后台并触发调用统一支付接口

目录:

微信小程序接入微信支付(一):大概流程与准备需知
微信小程序接入微信支付(二):后台调用统一下单接口
微信小程序接入微信支付(三):小程序端调用支付接口
微信小程序接入微信支付(四):接收支付结果通知与沙箱测试

调用接口流程:

1. 签名
a. 将官方文档中的必选项参数以键值对的形式放入Map中(”sign“值为空或先不放入)
b. 将除sign的键值对按照属性名排序并拼接成字符串,并接上”key“的值
c. 把该字符串进行MD5运算并转为大写,生成的值即为”sign“的值
d. 把sign值对放入Map中

2. 生成参数
将整个Map转义为xml格式的字符串,该字符串为调用接口的参数

3. 发送请求
后台发送post请求到URL地址:https://api.mch.weixin.qq.com/pay/unifiedorder,并传递上一步参数

4. 处理回调结果
处理微信返回的结果,如果各项无误的话我们会接收到"prepay_id"(注意微信返回的结果也是xml格式的字符串,需要我们处理成自己喜欢的形式,如Map)

5. 返回支付接口所需参数到小程序端
支付接口所需参数,以及生成签名所需参数请参考https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=7_7&index=5
a. 将”prepay_id“拼接为”package“,与其他所需参数按照上述第一步中的签名方式生成签名,赋值给”paySign“
b. 将参数传递到前台

直接上代码

java后端

/**
	 * 调用微信支付统一下单接口,获取prepay_id等信息
	 * 获取到prepay_id后,向前台发送wx.requestPayment所需参数
	 * @param order_code  订单编号
	 * @param pay_money  订单金额
	 * @return
	 * @throws Exception 
	 */
	@GetMapping("/uniorder")
    @ResponseBody
	public JSONObject uniOrder(@Param("order_code") String order_code, @Param("pay_money") Double pay_money,
			@Param("openid") String openid) throws Exception {
			
		//微信支付统一下单接口用的参数先存放在Map中
		Map<String, String> map = new HashMap<>();
		map.put("appid", appId);
		map.put("mch_id", mchId);
		//用户标识 openid
		map.put("openid", openid);
		//订单编号
		map.put("out_trade_no", order_code);
		//订单支付金额,单位为分 String.valueOf((int)(pay_money * 100))
		map.put("total_fee", String.valueOf((int)(pay_money * 100)));
		//32位随机字符串 
		map.put("nonce_str", getRandomString());
		//支持IPV4和IPV6两种格式的IP地址。调用微信支付API的机器IP,写服务器IP即可
		map.put("spbill_create_ip", spbillCreateIp);
		//商品描述
		map.put("body", new String(("RPH-ORDER").getBytes("utf-8")));
		//异步接收微信支付结果通知的回调地址
		map.put("notify_url", notifyUrl);
		//支付类型 小程序取值如下:JSAPI
		map.put("trade_type", tradeType);
		
		//生成符合规格的签名串
		String stringSignTemp = getParamStr(map,realKey);  //realKey == key
		//进行MD5运算,并转为大写,获得sign参数的值
		String signValue = MD5(stringSignTemp.toString()).toUpperCase();
		//把sign放入map中
		map.put("sign",signValue);
		
		//当sign参数有值时
		if (map.get("sign").trim().length()>0) {
			//map转义为xml格式 
			String requestParam = new String(mapToXml(map).getBytes(),"utf-8");
			LOG.info("----uniorder requestParam: " + requestParam);
			//发送请求
			String result = sendPostParam(orderApplyUrl, requestParam);  //统一下单接口URL地址
			LOG.info("----uniorder result: " + result);
			//将返回的结果从xml字符串转义为map
			Map<String, String> resultMap = xmlToMap(result);
			//初步处理验证返回的结果
			String return_code;
	        if (resultMap.containsKey("return_code")) {
	            return_code = resultMap.get("return_code");
	        }
	        else {
	            throw new Exception(String.format("No `return_code` in XML: %s", result));
	        }

	        if (return_code.equals("FAIL")) {
	        	throw new Exception("return_code : fail, the result xml string is :" + result);
	        }
	        else if (return_code.equals("SUCCESS")) {
	        	//return_code和result_code都为SUCCESS时返回prepay_id
	        	if (resultMap.get("result_code").equals("SUCCESS")) {
		        	//验证签名。
		    		//将返回结果生成符合规格的签名串
		    		String stringResultSignTemp = getParamStr(resultMap,realKey);
		    		//进行MD5运算,并转为大写,获得sign参数的值
		    		String signResultValue = MD5(stringResultSignTemp.toString()).toUpperCase();
		           if (signResultValue.equals(resultMap.get("sign"))) {
		        	   //签名验证成功后向前台传送wx.requestPayment所需参数
		        	   //所需参数位timeStamp, nonceStr, package, signType, paySign
		        	   String timeStamp = String.valueOf(System.currentTimeMillis());
		        	   String nonceStr = getRandomString();
		        	   String packageStr = "prepay_id="+resultMap.get("prepay_id");
		        	   
		        	   //准备paySign签名
		        	   Map<String, String> paymentMap = new HashMap<>();
		        	   paymentMap.put("appId", appId);
		        	   paymentMap.put("timeStamp", timeStamp);
		        	   paymentMap.put("nonceStr", nonceStr);
		        	   paymentMap.put("package", packageStr);
		        	   paymentMap.put("signType", "MD5");
		        	   //生成符合规格的签名串
		        	   String stringPaySignTemp = getParamStr(paymentMap,realKey);
		        	   //进行MD5运算,并转为大写,获得paySign参数的值
			       	   String paySignValue = MD5(stringPaySignTemp.toString()).toUpperCase();
			       	   
			       	   //把值放入json对象传给前台
			       	   JSONObject payInfo = new JSONObject();
			       	   payInfo.put("timeStamp", timeStamp);
			       	   payInfo.put("nonceStr", nonceStr);
			       	   payInfo.put("package", packageStr);
			       	   payInfo.put("paySign", paySignValue);
		        	   
		               return payInfo;
		           }
		           else {
		               throw new Exception(String.format("Invalid sign value in XML: %s", result));
		           }
	        		
	        	}else {
	        		return null;
	        	}
	        }
	        else {
	            throw new Exception(String.format("return_code value %s is invalid in XML: %s", return_code, result));
	        }
		}
			
		return null;
	}

上述代码中用到的方法,在后续会一直用到

/**
	 * 生成32位随机字符串
	 * @return
	 */
	public static String getRandomString() {
		String temp = "123456789qazwsxedcrfvtgbyhnujmikolp";
		Random random=new Random(); 
		StringBuffer sb=new StringBuffer();
		for(int i = 0; i< 32; i++) {
		  int number=random.nextInt(32);
		  sb.append(temp.charAt(number));
		}
		return sb.toString().toUpperCase();		
	}
	
	/**
	 * 将Map转换为签名字符串
	 * @param map
	 * @return
	 */
    private static String getParamStr(Map<String, String> map, String key) {
        Set<String> keySet = map.keySet();
        String[] keyArray = keySet.toArray(new String[keySet.size()]);
        Arrays.sort(keyArray);
        StringBuilder sb = new StringBuilder();
        //将除sign的其他非空参数按照ASCII码排序,并拼接位URL键值对形式的字符串
        for (String k : keyArray) {
        	//遇到sign参数跳过不处理
        	if (k.equals("sign")) {
        		continue;
        	}
            if (map.get(k).trim().length() > 0) // 参数值为空,则不参与签名
                sb.append(k).append("=").append(map.get(k).trim()).append("&");
        }
        //结尾拼接key
        sb.append("key=").append(key);
        return sb.toString();
    }
    
    /**
     * 生成 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();
    }
	
    /**
     * 将Map转换为XML格式的字符串
     *
     * @param data Map类型数据
     * @return XML格式的字符串
     * @throws Exception
     */
    public static String mapToXml(Map<String, String> data) throws Exception {
    	DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        org.w3c.dom.Document document = documentBuilderFactory.newDocumentBuilder().newDocument();
        //document.setXmlStandalone(true);
        org.w3c.dom.Element root = document.createElement("xml");
        document.appendChild(root);
        for (String key: data.keySet()) {
            String value = data.get(key);
            if (value == null) {
                value = "";
            }
            value = value.trim();
            org.w3c.dom.Element filed = document.createElement(key);
            filed.appendChild(document.createTextNode(value));
            root.appendChild(filed);
        }
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        DOMSource source = new DOMSource(document);
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    	//transformer.setOutputProperty(OutputKeys.STANDALONE, "yes");
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        transformer.transform(source, result);
        String output = writer.getBuffer().toString(); 
        try {
            writer.close();
        }
        catch (Exception ex) {
        }
        return output;
    	
    }
    
    /**
     * 发送post请求
     *
     * @param url   地址
     * @param param 参数 name1=value1&name2=value2
     * @return
     */
    public static String sendPostParam(String url, String param) {
        String result = "";
        try {
            URL realUrl = new URL(url);
            //打开url连接
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            //设置通用请求属性
            connection.setRequestMethod("POST");
            connection.setConnectTimeout(3000);
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36");
            // 发送POST请求必须设置如下两行
            connection.setDoOutput(true);
            connection.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            PrintWriter pw = new PrintWriter(connection.getOutputStream());
            // 发送请求参数
            pw.print(param);
            // flush输出流的缓冲
            pw.flush();
            // 定义BufferedReader输入流来读取URL的响应
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String s;
            StringBuffer stringBuffer = new StringBuffer();
            while ((s = br.readLine()) != null) {
                stringBuffer.append(s);
            }
            result = stringBuffer.toString();
            //关闭输入输出流
            br.close();
            pw.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
    
    /**
     * 将XML格式的字符串转化为Map
     * 
     * @param xml格式字符串
     * @return map
     */
    public static Map<String, String> xmlToMap(String strXML) throws Exception {
        try {
            Map<String, String> data = new HashMap<String, String>();
        	DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            InputStream stream = new ByteArrayInputStream(strXML.getBytes("UTF-8"));
            org.w3c.dom.Document doc = documentBuilder.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) {
        	Logger logger = LoggerFactory.getLogger("wxpay java");
        	logger.warn("Invalid XML, can not convert to map. Error message: {}. XML content: {}", ex.getMessage(), strXML);
            throw ex;
        }

    }

小程序端

//触发后台调用微信支付统一下单接口
wx.request({
    url: app.globalData.url+'/neigou/pay/uniorder',
    method: 'get',
    data: {
      order_code: res.data.order_code,
      pay_money: that.data.order.pay_money,
      openid: that.data.userInfo.openid
    },
    success: function(r){
      console.log(r.data)
      //返回结果如果不为空
      if(r.data != null && r.data.paySign != null){
          //调用微信支付
      }else{
          wx.showToast({
            title: '统一下单出现异常',
            icon: 'none'
          })
      }
    }
  })
  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值