微信公众号网页支付开发

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_36113180/article/details/82819899

 

 最近做的游戏公众号项目需要实现在微信公众号网页进行支付,虽然是一个小的功能,初次接触支付还是犯了很多错误,在此记录一下大体的开发流程。

准备工作

第一步:申请微信商户号,配置JSAPI支付授权目录(注:发起支付的前端页面所在的请求目录,去掉最后一个/后面内容):

例如我的支付页面请求路径是http://www.xxxxx.com/wxpay/jsPay/getPayPage,

需要配置的JSAPI支付授权目录就是:http://www.xxxxx.com/wxpay/jsPay/,后边的统一下单接口也必须在这个目录下

格式:http://www.xxxxx.com/wxpay/jsPay/ (注:域名后必须至少配置两层路径)

商户号支付授权目录

 

 

第二步:仔细阅读支付相关文档,仔细阅读支付相关文档,仔细阅读支付相关文档。

              文档连接:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=7_1

 

第三步:引入微信JS文件,http://res.wx.qq.com/open/js/jweixin-1.4.0.js,详见文档https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115

开发步骤

第一步:前端页面点击支付按钮,需要传参商品名称和商品总价给后端,后台调用统一下单接口,获取支付授权参数,返回给页面(注意对照参数,长度和类型对应,订单总total_fee参数单位为分,需在后端转为单位分对应的总价金额)

所有支付的第一步都是请求统一下单,统一下单,统一下单,请求URL地址:https://api.mch.weixin.qq.com/pay/unifiedorder。统一下单的目的是拿到预支付交易会话标识prepay_id,这个是必须的。所有的支付调用都是通过prepay_id来识别。

 

下面是后台请求支付授权参数代码:

接口:

public void wxPay(){
        String gamePlayId = getPara("gamePlayId");
        String userId = getPara("userId");
        BizOrder userOrder = new BizOrder();
        userOrder.setCreateTime(new Date());
        userOrder.setGamePlayId(gamePlayId);
        userOrder.setTotalFee(0.01F);
        userOrder.setUserId(userId);
        userOrder.save();
        Map<String, Object> map = null;
        try {
            //统一下单,调用工具类请求下单方法,返回xml,用return_code判断统一下单结果,获取prepay_id等预支付成功信息
            String prePayInfoXml = WxPayUtil.unifiedOrder("PRO版报告", System.currentTimeMillis() + WxPayUtil.getNonceStr6(),
                    (new BigDecimal(userOrder.getTotalFee().toString()).multiply(new BigDecimal(100))).intValue(),
                    WxPayUtil.getIpAddr(getRequest()), getSessionAttr("openId").toString(),gamePlayId);
            //生成包含prepay_id的map,map传入前端
            log.info(prePayInfoXml);
            map = WxPayUtil.getPayMap(prePayInfoXml);
            //将订单号放入map,用以支付后处理
            map.put("orderNo", userOrder.getId());
            System.out.println("支付授权参数:"+JSON.toJSONString(map));
        }catch (Exception e){
            log.error(e.getMessage());
        }

        renderJson(map);
    }

工具类:

​

public class WxPayUtil {
    private static Logger logger = Logger.getLogger(WxPayUtil.class);
    /**
     * 根据code获取openid
     * @param code
     * @return
     * @throws IOException
     */
    public static Map<String,Object> getOpenIdByCode(String code) throws IOException {
        //请求该链接获取access_token
        HttpPost httppost = new HttpPost("https://api.weixin.qq.com/sns/oauth2/access_token");
        //组装请求参数
        String reqEntityStr = "appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
        reqEntityStr = reqEntityStr.replace("APPID", WXConstant.APPID);
        reqEntityStr = reqEntityStr.replace("SECRET", WXConstant.APP_SECRET);
        reqEntityStr = reqEntityStr.replace("CODE", code);
        StringEntity reqEntity = new StringEntity(reqEntityStr);
        //设置参数
        httppost.setEntity(reqEntity);
        //设置浏览器
        CloseableHttpClient httpclient = HttpClients.createDefault();
        //发起请求
        CloseableHttpResponse response = httpclient.execute(httppost);
        //获得请求内容
        String strResult = EntityUtils.toString(response.getEntity(), Charset.forName("utf-8"));
        //获取openid
        JSONObject jsonObject = JSON.parseObject(strResult);

        Map<String,Object> map = new HashMap<String,Object>();
        map.put("openid",jsonObject.get("openid"));
        map.put("access_token",jsonObject.get("access_token"));
        map.put("refresh_token",jsonObject.get("refresh_token"));
        return map;
    }
    /**
     * 统一下单
     * @param body 商品描述
     * @param out_trade_no 商户订单号,自定义,一般为时间戳+6位随机字符串
     * @param total_fee 商品总价,单位为分
     * @param IP APP和网页支付提交用户端ip地址
     * @param openid 用户在本公众号的唯一标识
     * @param gamePlayId 附加数据信息,对应attach参数,根据自己业务需要
     * @return
     * @throws IOException
     */
    public static String unifiedOrder(String body,String out_trade_no,Integer total_fee,String IP,String openid,String gamePlayId)throws IOException {
        //设置访问路径
        HttpPost httppost = new HttpPost("https://api.mch.weixin.qq.com/pay/unifiedorder");

        String nonce_str = getNonceStr().toUpperCase();//随机
        //组装请求参数,按照ASCII排序
        String sign = "appid=" + WXConstant.APPID +
                "&attach=" + gamePlayId +
                "&body=" + body +
                "&mch_id=" + WXConstant.MCH_ID +
                "&nonce_str=" + nonce_str +
                "&notify_url=" + WXConstant.NOTIFY_URL+
                "&openid=" + openid +
                "&out_trade_no=" + out_trade_no +
                "&spbill_create_ip=" + IP +
                "&total_fee=" + total_fee.toString() +
                "&trade_type=" + WXConstant.TRADE_TYPE_JS +
                "&key=" + WXConstant.KEY;//这个字段是用于之后MD5加密的,字段要按照ascii码顺序排序
        sign = MD5Util.getMD5(sign).toUpperCase();

        //组装包含openid用于请求统一下单返回结果的XML
        StringBuilder sb = new StringBuilder("");
        sb.append("<xml>");
        setXmlKV(sb,"appid",WXConstant.APPID);
        setXmlKV(sb,"attach",gamePlayId);
        setXmlKV(sb,"body",body);
        setXmlKV(sb,"mch_id",WXConstant.MCH_ID);
        setXmlKV(sb,"nonce_str",nonce_str);
        setXmlKV(sb,"notify_url",WXConstant.NOTIFY_URL);
        setXmlKV(sb,"openid",openid);
        setXmlKV(sb,"out_trade_no",out_trade_no);
        setXmlKV(sb,"spbill_create_ip",IP);
        setXmlKV(sb,"total_fee",total_fee.toString());
        setXmlKV(sb,"trade_type",WXConstant.TRADE_TYPE_JS);
        setXmlKV(sb,"sign",sign);
        sb.append("</xml>");
        System.out.println("统一下单请求:" + sb);

        StringEntity reqEntity = new StringEntity(new String (sb.toString().getBytes("UTF-8"),"ISO8859-1"));//这个处理是为了防止传中文的时候出现签名错误
        httppost.setEntity(reqEntity);
        CloseableHttpClient httpclient = HttpClients.createDefault();
        CloseableHttpResponse response = httpclient.execute(httppost);
        String strResult = EntityUtils.toString(response.getEntity(), Charset.forName("utf-8"));
        System.out.println("统一下单返回xml:" + strResult);

        return strResult;
    }
    /**
     * XML-->MAP 根据统一下单返回预支付订单的id和其他信息生成签名并拼装为map(调用微信支付)
     * @param prePayInfoXml
     * @return
     */
    public static Map<String,Object> getPayMap(String prePayInfoXml){
        Map<String,Object> map = new HashMap<String,Object>();

        String prepay_id = getXmlPara(prePayInfoXml,"prepay_id");//统一下单返回xml中prepay_id
        String timeStamp = String.valueOf((System.currentTimeMillis()/1000));//1970年到现在的秒数
        String nonceStr = getNonceStr().toUpperCase();//随机数据字符串
        String packageStr = "prepay_id=" + prepay_id;
        String signType = "MD5";
        String paySign =
                "appId=" + WXConstant.APPID +
                        "&nonceStr=" + nonceStr +
                        "&package=prepay_id=" + prepay_id +
                        "&signType=" + signType +
                        "&timeStamp=" + timeStamp +
                        "&key="+ WXConstant.KEY;//注意这里的参数要根据ASCII码 排序
        paySign = MD5Util.getMD5(paySign).toUpperCase();//将数据MD5加密

        map.put("appId",WXConstant.APPID);
        map.put("timeStamp",timeStamp);
        map.put("nonceStr",nonceStr);
        map.put("packageStr",packageStr);
        map.put("signType",signType);
        map.put("paySign",paySign);
        map.put("prepay_id",prepay_id);
        return map;
    }
    /**
     * 修改订单状态,获取微信回调结果
     * @param request
     * @return
     */
    public static String getNotifyResult(HttpServletRequest request){
        String inputLine;
        String notifyXml = "";
        String resXml = "";
        try {
            while ((inputLine = request.getReader().readLine()) != null){
                notifyXml += inputLine;
            }
            request.getReader().close();
        } catch (Exception e) {
            logger.debug("xml获取失败:" + e);
            e.printStackTrace();
        }
        System.out.println("接收到的xml:" + notifyXml);
        logger.debug("收到微信异步回调:");
        logger.debug(notifyXml);
        if(StrKit.notBlank(notifyXml)){
            logger.debug("xml为空:");
        }

        String appid = getXmlPara(notifyXml,"appid");;
        String bank_type = getXmlPara(notifyXml,"bank_type");
        String cash_fee = getXmlPara(notifyXml,"cash_fee");
        String fee_type = getXmlPara(notifyXml,"fee_type");
        String is_subscribe = getXmlPara(notifyXml,"is_subscribe");
        String mch_id = getXmlPara(notifyXml,"mch_id");
        String nonce_str = getXmlPara(notifyXml,"nonce_str");
        String openid = getXmlPara(notifyXml,"openid");
        String out_trade_no = getXmlPara(notifyXml,"out_trade_no");
        String result_code = getXmlPara(notifyXml,"result_code");
        String return_code = getXmlPara(notifyXml,"return_code");
        String sign = getXmlPara(notifyXml,"sign");
        String time_end = getXmlPara(notifyXml,"time_end");
        String total_fee = getXmlPara(notifyXml,"total_fee");
        String trade_type = getXmlPara(notifyXml,"trade_type");
        String transaction_id = getXmlPara(notifyXml,"transaction_id");

        //根据返回xml计算本地签名
        String localSign =
                "appid=" + appid +
                        "&bank_type=" + bank_type +
                        "&cash_fee=" + cash_fee +
                        "&fee_type=" + fee_type +
                        "&is_subscribe=" + is_subscribe +
                        "&mch_id=" + mch_id +
                        "&nonce_str=" + nonce_str +
                        "&openid=" + openid +
                        "&out_trade_no=" + out_trade_no +
                        "&result_code=" + result_code +
                        "&return_code=" + return_code +
                        "&time_end=" + time_end +
                        "&total_fee=" + total_fee +
                        "&trade_type=" + trade_type +
                        "&transaction_id=" + transaction_id +
                        "&key=" + WXConstant.KEY;//注意这里的参数要根据ASCII码 排序
        localSign = MD5Util.getMD5(localSign).toUpperCase();//将数据MD5加密

        System.out.println("本地签名是:" + localSign);
        logger.debug("本地签名是:" + localSign);
        logger.debug("微信支付签名是:" + sign);

        //本地计算签名与微信返回签名不同||返回结果为不成功
        if(!sign.equals(localSign) || !"SUCCESS".equals(result_code) || !"SUCCESS".equals(return_code)){
            System.out.println("验证签名失败或返回错误结果码");
            logger.error("验证签名失败或返回错误结果码");
            resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[FAIL]]></return_msg>" + "</xml> ";
        }else{
            System.out.println("支付成功");
            logger.debug("公众号支付成功,out_trade_no(订单号)为:" + out_trade_no);
            resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>" + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
        }
        return resXml;
    }
    /**
     * 获取32位随机字符串
     * @return
     */
    public static String getNonceStr(){
        String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        StringBuilder sb = new StringBuilder();
        Random rd = new Random();
        for(int i = 0 ; i < 32 ; i ++ ){
            sb.append(str.charAt(rd.nextInt(str.length())));
        }
        return sb.toString();
    }
    /**
     * 获取32位随机字符串
     * @return
     */
    public static String getNonceStr6(){
        String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        StringBuilder sb = new StringBuilder();
        Random rd = new Random();
        for(int i = 0 ; i < 6 ; i ++ ){
            sb.append(str.charAt(rd.nextInt(str.length())));
        }
        return sb.toString();
    }
    /**
     * 插入XML标签
     * @param sb
     * @param Key
     * @param value
     * @return
     */
    public static StringBuilder setXmlKV(StringBuilder sb,String Key,String value){
        sb.append("<");
        sb.append(Key);
        sb.append(">");

        sb.append(value);

        sb.append("</");
        sb.append(Key);
        sb.append(">");

        return sb;
    }

    /**
     * 解析XML 获得名称为para的参数值
     * @param xml
     * @param para
     * @return
     */
    public static String getXmlPara(String xml,String para){
        int start = xml.indexOf("<"+para+">");
        int end = xml.indexOf("</"+para+">");

        if(start < 0 && end < 0){
            return null;
        }
        return xml.substring(start + ("<"+para+">").length(),end).replace("<![CDATA[","").replace("]]>","");
    }

    /**
     * 获取ip地址
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) {
        InetAddress addr = null;
        try {
            addr = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            return request.getRemoteAddr();
        }
        byte[] ipAddr = addr.getAddress();
        String ipAddrStr = "";
        for (int i = 0; i < ipAddr.length; i++) {
            if (i > 0) {
                ipAddrStr += ".";
            }
            ipAddrStr += ipAddr[i] & 0xFF;
        }
        return ipAddrStr;
    }
}

​

第二步:获取到统一下单接口返回的支付授权参数后,在回调函数中调用微信JS接口发起支付

以下为微信内H5调起支付的示例代码:

JS代码如下:

//支付方法
function pay(){
        var url = ctx + '/wxpay/jsPay/wxPay';
        $.ajax({
            type:"post",
            url:url,
            dataType:"json",
            data:{gamePlayId:$("#gamePlayId").val(),userId:$("#userId").val()},
            success:function(data) {
                //调起微信支付
                WeixinJSBridge.invoke('getBrandWCPayRequest', {
                        appId: data.appId,
                        timeStamp: data.timeStamp,
                        nonceStr: data.nonceStr,
                        package: data.packageStr,
                        signType: 'MD5',
                        paySign: data.paySign,
                    },
                    //调起微信支付成功
                    function (res) {
                        WeixinJSBridge.log(res.err_msg);
                        if (res.err_msg == "get_brand_wcpay_request:ok") {
                            alert("充值成功!");
                            //更新支付状态
                            updatePayStatus();
                            location.href = "url";
                        } else {
                            alert("充值失败!");
                        }
                    });
            },
            error: function () {
                alert("data");
            }


        });
    }

package参数为返回的订单预支付id,统一下单接口返回的prepay_id参数值,提交格式如:prepay_id=***
 

第三步:用户在微信支付窗口中完成支付,支付完成后根据微信返回结果在前端判断是否成功

function(res){ if(res.err_msg == "get_brand_wcpay_request:ok" ){

// 使用以上方式判断前端返回,微信团队郑重提示: //res.err_msg将在用户支付成功后返回ok,但并不保证它绝对可靠。 }

在成功的回调函数中跳转到需要跳转的页面。

 

欢迎小伙伴们一起交流,如有错误还请指正。电话:同微信15809272351

展开阅读全文

没有更多推荐了,返回首页