Wechat JSAPI Payment, Wechat Browser Payment, Solve the problem that Wechat H5 Payment can only be paid in Wechat Browser

Setting up Payment Catalogue

Make sure that the actual payment request directory is the same as the background configuration directory (now supports the configuration root directory, which has a certain effective time after configuration, usually within 5 minutes), otherwise it will not be able to successfully wake up Wechat payment.

Set up your JSAPI payment directory on the Wechat Business Platform (pay.weixin.qq.com) and set the path: Business Platform -> Product Center -> Development Configuration, as shown in Figure 7.7. JSAPI payment checks whether the source of the request has been configured on the customer platform when requesting payment, so it is necessary to ensure that the payment directory is properly configured, otherwise the verification will fail and the request payment will not succeed.

2. Setting up Authorized Domain Names

When developing JSAPI payment, the user openid is required to be transmitted in the unified single interface, while acquiring openid requires you to set up the domain name to acquire openid on the public platform. Only the domain name that has been set up is an effective domain name to acquire openid, otherwise the acquisition will fail. The specific interface is shown in Figure 7.8.

3. Replace the redirect-url parameter in the connection after encoding the connection of the payment page to get the code

Reference link (please open this link experience in the Wechat client)
Scope is snsapi_base, which is connected to silently obtain user authorization

https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx520c15f417810387&redirect_uri=http%3A%2F%2Fchong.qq.com%2Fphp%2Findex.php%3Fd%3D%26c%3DwxAdapter%26m%3DmobileDeal%26showwxpaytitle%3D1%26vb2ctag%3D4_2030_5_1194_60&response_type=code&scope=snsapi_base&state=123#wechat_redirect

4. Obtain openid through code, and then call the unified single interface after having openid. At this time, secret can not be ignored. Obtain it on the Wechat public platform.

https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code

5. Call Unified Single Interface, AppID and other sensitive information I encapsulated in the entity class

 /**
     * Wechat Payment by Browser
     *
     * @return
     */
    @PostMapping("/createJSAPI")
    @ApiOperation("Wechat Payment,orderId Order ID,openId User Unique Identification ID")
    public DzResult createJSAPI(String orderId, String openId) throws Exception {
        if (StringUtils.isBlank(orderId) || StringUtils.isBlank(openId)) {
            System.out.println("Payment of Empty Order Number in Wechat-------------------->");
            return new DzResult().error(OrderCode.ERROR_PARAMS, "Parameter error");
        }
        // Get the current user
        Claims claims = (Claims) request.getAttribute("authInfo");
        if (claims == null) {
            return new DzResult().error(OrderCode.NOT_LEGAL, "Illegal operation");
        }
        // Invoke business layer to query order information
        CyOrder order = weixinPayService.findOrderByOrderId(orderId);
        if (order == null) {
            return new DzResult().error(OrderCode.ORDER_NOT_EXIST, "Order does not exist");
        }
        if (!claims.getId().equals(order.getFrontUserId())) {
            return new DzResult().error(OrderCode.NOT_BELONG, "The order does not belong to the current user");
        }
        // Merchant Order Number (Mark 1: Payment Deposit 2: Payment End) with the number after the underline
        BigDecimal totalAmount;
        // Divide the database price
        BigDecimal mun = BigDecimal.valueOf(100);
        // Name
        String subject;
        //Setting Details of Goods
        HashMap<String, String> attach = new HashMap<>(16);
        // Order number
        String outTradeNo = orderId;
        //Order number
        attach.put("outTradeNo", outTradeNo);
        //Custom parameters
        String attachStr;
        //Whole paragraph
        //Wechat is divided into units, where * 100 points:
        totalAmount = order.getPayMoney().multiply(mun);
        subject = "Payment in full";
        attach.put("subject", subject);
        //Zero after the decimal point is removed
        attach.put("totalAmount", totalAmount.stripTrailingZeros().toPlainString());
        attachStr = JSONUtils.toJSONString(attach);
        Map map = weixinPayService.createJSAPI(outTradeNo, totalAmount.stripTrailingZeros().toPlainString(), attachStr, openId);
        if (map == null) {
            return new DzResult().error(OrderCode.ORDER_WECAT_ERROR, "Wechat Payment Abnormality");
        }
        if ("FAIL".equals(map.get("return_code"))) {
            System.out.println("Abnormal communication");
            Object errorMsg = map.get("return_msg");
            return new DzResult().error(OrderCode.ORDER_WECAT_ERROR, errorMsg + "");
        }
        if ("FAIL".equals(map.get("result_code"))) {
            System.out.println("Payment error");
            Object errCode = map.get("err_code");
            Object errCodeDes = map.get("err_code_des");
            String errorMsg = errCode + "  :  " + errCodeDes;
            return new DzResult().error(OrderCode.ORDER_WECAT_ERROR, errorMsg + "");
        }
        System.out.println("The results returned by a single interface under harmonization are all OK...............");
        boolean haveMwebUrl = map.containsKey("mweb_url");
        System.out.println("Did you pull up the Wechat? APP Path:" + haveMwebUrl);
        boolean havePrepay_id = map.containsKey("prepay_id");
        System.out.println("Are there any,Prepaid transaction session identification:" + havePrepay_id);
        //Create a new map collection
        Map<String, String> resMap = new HashMap<>(16);
        //appID
        resMap.put("appId", WeChatPayConfig.app_id);
        System.out.println("appId:-->" + resMap.get("appId").toString());
        //time stamp
        resMap.put("timeStamp", String.valueOf(System.currentTimeMillis() / 1000));
        System.out.println("timeStamp:-->" + resMap.get("timeStamp").toString());
        //Random string
        resMap.put("nonceStr", WXPayUtil.generateNonceStr());
        System.out.println("nonceStr:-->" + resMap.get("nonceStr").toString());
        //Order Details Extension Field
        resMap.put("package", "prepay_id="+map.get("prepay_id").toString());
        System.out.println("package:-->" + map.get("prepay_id").toString());
        //Signature method
        resMap.put("signType", "MD5");
        String paySign = WXPayUtil.generateSignature(resMap, WeChatPayConfig.partner_key);
        //autograph
        resMap.put("paySign", paySign);
        System.out.println("paySign:-->" + resMap.get("paySign").toString());
        //Back to the front end
        map.put("WCPayRequest", resMap);
        return new DzResult().success(map);

Implementation Layer Code

/**
     * Calling JSAPI Payment in Wechat Browser
     *
     * @param outTradeNo
     * @param totalFee
     * @param attachStr
     * @param openID
     * @return
     */
    @Override
    public Map createJSAPI(String outTradeNo, String totalFee, String attachStr, String openID) {
        System.out.println("Payment Method for Browsers Entering Wechat");
        System.out.println("Order Number Passed Over:"+outTradeNo);
        System.out.println("The amount passed on:"+totalFee);
        System.out.println("Custom parameters passed in:"+attachStr);
        System.out.println("From here on openid:"+openID);
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        //Set failure time for 5 minutes
        String expireTime = getOrderExpireTime(300 * 1000L);
        //1. Create parameters
        HashMap<String, String> param = new HashMap<>(16);
        //Public Account
        param.put("appid", WeChatPayConfig.app_id);
        //Custom parameters (attach)
        param.put("attach", attachStr);
        //Commodity Description: Commodity Name
        param.put("body", "Customization of clothes");
        //Business name
        param.put("mch_id", WeChatPayConfig.partner);
        //Random string
        param.put("nonce_str", WXPayUtil.generateNonceStr());
        //token url
        param.put("notify_url", WeChatPayConfig.notify_url);
        //User's openID,JSAPI Payment Required
        param.put("openid", openID);
        //Order number
        param.put("out_trade_no", outTradeNo);
        //ip,
        param.put("spbill_create_ip", getIpAddr(request));
        //Set failure time for 5 minutes
        param.put("time_expire", expireTime);
        //Total amount (points)
        param.put("total_fee", totalFee);
        //Type of transaction
        param.put("trade_type", "JSAPI");

        System.out.println("appid"+param.get("appid").toString());
        System.out.println("attach"+param.get("attach").toString());
        System.out.println("body"+param.get("body").toString());
        System.out.println("mch_id"+param.get("mch_id").toString());
        System.out.println("nonce_str"+param.get("nonce_str").toString());
        System.out.println("notify_url"+param.get("notify_url").toString());
        System.out.println("openid"+param.get("openid").toString());
        System.out.println("out_trade_no"+param.get("out_trade_no").toString());
        System.out.println("spbill_create_ip"+param.get("spbill_create_ip").toString());
        System.out.println("time_expire"+param.get("time_expire").toString());
        System.out.println("total_fee"+param.get("total_fee").toString());
        System.out.println("trade_type"+param.get("trade_type").toString());
        System.out.println("partner_key"+WeChatPayConfig.partner_key);
        try {
            //2. Generate the xml to be sent, and pass in the signature in the method
            String xmlParam = WXPayUtil.generateSignedXml(param, WeChatPayConfig.partner_key);
            System.out.println("Calling the Unified Single Interface of Wechat,Request parameters" + xmlParam);
            //url address of request
            HttpClient httpclient = new HttpClient(WeChatPayConfig.request_url);
            //Is it an https protocol?
            httpclient.setHttps(true);
            //xml data sent
            httpclient.setXmlParam(xmlParam);
            //Request method for execution
            httpclient.post();
            Map<String, String> returnMap = WXPayUtil.xmlToMap(httpclient.getContent());
            //Order number
            returnMap.put("out_trade_no", outTradeNo);
            //Custom parameters, transaction information
            returnMap.put("attach", attachStr);
            System.out.println("Normal single interface under unified invocation");
            return returnMap;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

Keywords: xml encoding PHP Database

Added by dave_biscuits on Thu, 22 Aug 2019 15:25:31 +0300