微信公众号开发之调起微信支付接口

参考公众号支付开发者文档


我们要做的就是上图标红的部分。

理一遍流程:

1.进行js-sdk的验签流程

2.发起请求,对统一下单的传入参数进行参数签名,签名通过后,把签名也封装到参数中

3.调起微信统一下单接口,生成预订单(在公司已经申请了商户号的前提下,商户的申请配置在这里就不讲述了,自行百度。值得注意的是支付的授权目录为支付请求的上一级目录,要请求的全路径)

4.在预订单中取出prepay_id(生成预订单主要目的就是这个prepay_id,能得到prepay_id就已经成功一半了)

5.获得prepay_id后,调起微信支付 wx.chooseWXPay({});(业务逻辑根据项目需求自行处理)

6.支付成功后,回调支付成功通知,通知微信支付结果(业务逻辑根据项目需求自行处理)

具体代码实现如下:

depositPay.jsp(/wechat/jsapisign部分的验签在这里就不讲述了,在微信公众号开发之调起微信扫一扫接口中有详细介绍)

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
    <!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
    <link rel="stylesheet" href="../../../resources/css/example.css"/>
    <link rel="stylesheet" href="../../../resources/css/weui.min.css"/>
    <script src="http://res.wx.qq.com/open/js/jweixin-1.1.0.js"></script>
    <script src="../../../resources/js/jquery.min.js"></script>
    <title>押金支付</title>
</head>
<body>
<div class="container">
    <div class="page__bd">
        <div class="weui-btn-area" style="padding-top: 40px;">
            <button class="weui-btn weui-btn_primary" id="deposit">押金充值</button>
        </div>
    </div>
</div>
<script type="text/javascript">
    $.ajax({
        url: "${pageContext.request.contextPath}/wechat/jsapisign",
        type: "post",
        data: {
            url: location.href.split('#')[0]
        },
        contentType: 'application/x-www-form-urlencoded;charset=utf-8',
        async: true,
        success: function (data) {
            wx.config({
                debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
                appId: data.appid, // 必填,公众号的唯一标识
                timestamp: data.timestamp, // 必填,生成签名的时间戳
                nonceStr: data.nonceStr, // 必填,生成签名的随机串
                signature: data.signature,// 必填,签名,见附录1
                jsApiList: ["chooseWXPay"] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
            });
        }
    });
    wx.ready(function () {
        document.querySelector("#deposit").onclick = function () {
            $.ajax({
                url: "${basePath}/wechat/paySubmit?totalFee=1&openId=${openid}&outTradeNo=${outTradeNo}",
                type: "get",
                dataType: "json",
                success: function (result) {
                     wx.chooseWXPay({
                        timestamp: result.timeStamp, // 支付签名时间戳,注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
                        nonceStr: result.nonceStr, // 支付签名随机串,不长于 32 位
                        package: "prepay_id=" + result.prepay_id,
                        signType: 'MD5', // 签名方式,默认为'SHA1',使用新版支付需传入'MD5'
                        paySign: result.paySign, // 支付签名
                        success: function (res) {
                           window.location.href="${basePath}/wechat/paySuccess"
                        }
                     });
                },
                error: function (data) {
                    alert(data);
                }
            })
        }
    });
</script>
</body>
</html

/wechat/paySubmit请求的详细代码,统一下单的请求和返回参数参照微信公众号支付统一下单部分

统一下单接口为:"https://api.mch.weixin.qq.com/pay/unifiedorder"

 @RequestMapping(value = "/pay", method = RequestMethod.GET, produces = MEDIATYPE_CHARSET_JSON_UTF8)
    public @ResponseBody String pay(HttpSession httpSession, HttpServletRequest request, String totalFee, String openId, String outTradeNo) {
	String paramContent = "";
        String sign = "";
	String nonceStr = CheckUtil.generateNonceStr();
	Map<String, String> param = new HashMap<>();
        param.put("appid", appId); //公众号id
        param.put("mch_id", mchId);//商户平台id
        param.put("device_info", "WEB");
        param.put("nonce_str", nonceStr);      
        param.put("body", "xiaodoujieyue");//订单标题
        param.put("out_trade_no", outTradeNo);//订单ID
        param.put("total_fee", totalFee); //订单需要支付的金额
        param.put("trade_type", "JSAPI");//交易类型 JSAPI 公众号支付 NATIVE 扫码支付 APP APP支付        
        param.put("notify_url", WXConstants.BASE_SERVER+"/wechat/payNotify");//notify_url 支付成功之后 微信会进行异步回调的地址
        param.put("openid", openId);//微信授权获取openId
        param.put("sign_type", "MD5");
	String spbill_create_ip = CheckUtil.getIpAddr(request);
	if (StringUtils.isEmpty(spbill_create_ip)) {
		map.put("spbill_create_ip", "192.168.0.1");// 消费IP地址
	} else {
		map.put("spbill_create_ip", spbill_create_ip);// 消费IP地址
	}
        sign = CheckUtil.generateSignature(param, key, "MD5");
        param.put("sign", sign);
        paramContent = CheckUtil.getXMLFromMap(param);
        logger.info("预订单参数信息" + paramContent);
        String orderInfo = OkHttpUtil.getInstance().doPost("https://api.mch.weixin.qq.com/pay/unifiedorder", paramContent);
        logger.info("生成预订单的信息xml" + orderInfo);
	String prepay_id;
	try {
            Map<String, String> orderInfoMap = CheckUtil.xmlToMap(orderInfo);
            if (orderInfoMap.get("return_code").equals("SUCCESS") && orderInfoMap.get("result_code").equals("SUCCESS")) {
                //预支付id
                prepay_id = orderInfoMap.get("prepay_id");
                String timestamp = CheckUtil.create_timestamp();
                HashMap<String, String> pageParam = new HashMap<>();
                pageParam.put("appId", appId);
                pageParam.put("nonceStr", nonceStr);
                pageParam.put("package", "prepay_id=" + prepay_id);
                pageParam.put("timeStamp", timestamp);
                pageParam.put("signType", "MD5");
                String pageSign = CheckUtil.generateSignature(pageParam, key, "MD5");
                pageParam.put("paySign", pageSign);
                pageParam.put("prepay_id", prepay_id);
                logger.info("参与签名的参数:appId:" + appId + "nonceStr:" + nonceStr + "package:prepay_id=" + prepay_id + "timeStamp" + timestamp + "signType:MD5" + "paySign:" + pageSign);                
		return JSON.toJSONString(pageParam);
	    }
        } catch (Exception e) {
            logger.error("生成的预订单格式xml转map异常" + e.getMessage() + "异常原因" + e.getCause());
            return null;
        }
        return null;
    }

支付回调  

@RequestMapping("/payNotify")
    public synchronized String payNotify(HttpServletRequest request, HttpServletResponse response) {
        Map<String, String> returnData = new HashMap<>();
        String returnXML = "";
        String retStr = "";
        try {
            retStr = new String(readInput(request.getInputStream()), "utf-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        logger.info("支付回调信息:" + retStr);
        try {
            Map<String, String> responseResult = CheckUtil.xmlToMap(retStr);
            String localSign = CheckUtil.generateSignature(responseResult, key, "MD5");
            String sign = responseResult.get("sign");
            String openid = responseResult.get("openid");
            logger.info("签名信息:localSign-->" + localSign + "sign:-->" + sign);
            if (Objects.equals(sign, localSign)) {
                if (!responseResult.get("return_code").toString().equals("SUCCESS") || !responseResult.get("result_code").toString().equals("SUCCESS")) {
                    returnData.put("return_code", "FAIL");
                    returnData.put("return_msg", "return_code不正确");
                } else {
				   //todo 你的业务逻辑
                   returnData.put("return_code", "SUCCESS");
                   returnData.put("return_msg", "ok");                 
                }
            } else {
                returnData.put("return_code", "FAIL");
                returnData.put("return_msg", "签名错误");
            }
        } catch (Exception e) {
            logger.error("支付回调错误" + e.getMessage());
            returnData.put("return_code", "FAIL");
            returnData.put("return_msg", "支付回调失败");
            returnXML = CheckUtil.getXMLFromMap(returnData);                 
			return returnXML;
        }
		returnXML = CheckUtil.getXMLFromMap(returnData);                 
        logger.info("支付回调返回的信息" + returnXML);
        return returnXML;
    }
    public static byte[] readInput(InputStream in) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int len = 0;
        byte[] buffer = new byte[1024];
        while ((len = in.read(buffer)) > 0) {
            out.write(buffer, 0, len);
        }
        out.close();
        in.close();
        return out.toByteArray();
    }

用到的工具类 CheckUtil.java

public class CheckUtil {
	/**
     * 生成签名. 注意,若含有sign_type字段,必须和signType参数保持一致。
     * @param data 待签名数据
     * @param key API密钥
     * @param signType 签名方式
     * @return 签名
     */
    public static String generateSignature(final Map<String, String> data, String key, SignType signType) throws Exception {
        Set<String> keySet = data.keySet();
        String[] keyArray = keySet.toArray(new String[keySet.size()]);
        Arrays.sort(keyArray);
        StringBuilder sb = new StringBuilder();
        for (String k : keyArray) {
            if (k.equals(WXPayConstants.FIELD_SIGN)) {
                continue;
            }
            if (data.get(k).trim().length() > 0) // 参数值为空,则不参与签名
                sb.append(k).append("=").append(data.get(k).trim()).append("&");
        }
        sb.append("key=").append(key);
        if (SignType.MD5.equals(signType)) {
            return MD5(sb.toString()).toUpperCase();
        }
        else if (SignType.HMACSHA256.equals(signType)) {
            return HMACSHA256(sb.toString(), key);
        }
        else {
            throw new Exception(String.format("Invalid sign_type: %s", signType));
        }
    }
	 /**
     * 通过HttpServletRequest返回IP地址
     * @param request HttpServletRequest
     * @return ip String
     * @throws Exception
     */
    public static String getIpAddr(HttpServletRequest request) throws Exception {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
	public static String generateNonceStr() {
        return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
    }
	public static String getXMLFromMap(Map<String, String> map) throws Exception {
        StringBuffer sb = new StringBuffer();
        sb.append("<xml>");
        Set<String> set = map.keySet();
        Iterator<String> it = set.iterator();
        while (it.hasNext()) {
            String key = it.next();
            sb.append("<" + key + ">").append(map.get(key)).append("</" + key + ">");
        }
        sb.append("</xml>");
        return sb.toString();
    }
    /**
     * XML格式字符串转换为Map
     *
     * @param strXML XML字符串
     * @return XML数据转换后的Map
     * @throws Exception
     */
    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) {
            throw ex;
        }
    }
    public static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }
}

OkHttpUtil.java

public class OkHttpUtil {
    private static OkHttpUtil okHttpUtil;
    private static OkHttpClient okHttpClient;
    private OkHttpUtil() {
        /**
         * OkHttp是一个第三方类库,
         * 用于android中请求网络
         * 创建OkHttpClient对象
         */
        okHttpClient = new OkHttpClient();
    }
    public static OkHttpUtil getInstance() {
        if (okHttpUtil == null) {
            okHttpUtil = new OkHttpUtil();
        }
        return okHttpUtil;
    }

    public String doGet(String url) {
        /**
         * 请求接口
         * 创建Request对象
         */
        Request request = new Request.Builder()
                .url(url)
                .build();
        //得到request对象
        Call call = okHttpClient.newCall(request);
        try {
            Response response = call.execute();
            return response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public String doPost(String url, Map<String, String> param) {
        FormBody.Builder builder = new FormBody.Builder();
        for (Map.Entry<String, String> entry : param.entrySet()) {
            builder.add(entry.getKey(), entry.getValue());
        }
        RequestBody body = builder.build();
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        Call call = okHttpClient.newCall(request);
        try {
            Response response = call.execute();
            return response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public String doPostParam(String url, Map<String, Object> param) {
        FormBody.Builder builder = new FormBody.Builder();
        for (Map.Entry<String, Object> entry : param.entrySet()) {
            builder.add(entry.getKey(), (String) entry.getValue());
        }
        RequestBody body = builder.build();
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        Call call = okHttpClient.newCall(request);
        try {
            Response response = call.execute();
            return response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public String doPost(String url, String param) {
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(JSON, param);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        Call call = okHttpClient.newCall(request);
        try {
            Response response = call.execute();
            return response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}


猜你喜欢

转载自blog.csdn.net/qq_23543983/article/details/80253762