preface

If you have completed wechat H5 payment, it may be easier to continue the payment of the public account.

scenario

Application payment in wechat browser must rely on public account payment. The following is a detailed analysis of some technical points in public account payment.

The preparatory work

Basic Configuration Application

Reference: Wechat public account to open the payment function – Baidu experience tutorial

The basic information

  • Service number: Administrator number bound to the service number
  • Open a payment account, and remember the payment account and the wechat signal bound to the payment account
  • Appid and secret key
  • Payment account opening Payment directory (the directory above the direct payment address)
  • Set the page authorization domain name, and is your site domain name address
  • Basic interface permissions, especially JSSDK part of the permissions, to ensure that as far as possible open

Business process diagrams and sequence diagrams

Basically the same as wechat H5, the only difference is that this time wechat returns a list of parameters that need to evoke wechat SDK payment.

Technical problems

To obtain the openid

Website application wechat login is a wechat OAuth2.0 authorized login system based on OAuth2.0 protocol standard. There are two steps to obtain OpenID: obtain code, and then obtain OpenID according to code. It is recommended that these two parts of requests be initiated by the back-end. Direct front-end requests may involve cross-domain problems. The backend defines these two methods as tool methods, which are easy to use and reuse in other scenarios.

One: request to get the code, if you don’t want to waste time please directly copy and paste use

  • Standard format stitching code:

    letencodeUrl=encodeURIComponent(`http://xxx/xhxwxpay? productId=${productId}&orderNo=${orderNo}`)
    let tempUrl=`https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx6f5de09c8ef178a7&redirect_uri=${encodeUrl}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`
    Copy the code
  • Request Parameters

    parameter Whether must instructions
    appid is Application unique identifier
    redirect_uri is Please use urlEncode to process the link
    response_type is Fill in the code
    scope is Use commas (,) to separate multiple authorization scopes. For web applications, only snsapi_login is required. Snsapi_userinfo is used here
    state no It is used to preserve the status of requests and callbacks, and to authorize requests to be returned to third parties as is. This parameter is used to prevent CSRF attacks (cross-site request forgery attacks). You are advised to set this parameter to a simple random number plus session for verification
  • The user will be redirected to the redirect_URI url with the code and state parameters redirect_uri? Code =CODE&state=STATE If the user disables authorization, the redirection will not carry the code parameter but the STATE parameter redirect_uri? state=STATE

  • Reference Document: Obtain the code reference document from the wechat Web site

Obtain the OpenID according to code

  • A user has a fixed openID for a public number, so there is no doubt that the same access involves the secret keys of some sensitive public numbers, etc. It is suggested that the back-end process initiates the request, which can also avoid the front-end cross-domain problem.

    // Gateway or backend Settings (koA framework as an example) *post_getOpenId() {let reqData = this.request.body;
            let param = {
                appid:'wxxxx',
                secret:'affsdcsdvdsvfv6',
                code:reqData.code,
                grant_type:'authorization_code'
            }
            letresult = yield this.api.getOpenId(param); this.body = result; } // Get the form of the object passed in by openId and modify the general API method getOpenId:function* (apiParam, json = true) {// Get the token addresslet apiUrl='https://api.weixin.qq.com/sns/oauth2/access_token'
        let response = yield request.get(apiUrl, { qs: apiParam, json: json });
        returnresponseHandle(response, apiUrl, apiParam); }.bind(this), //$api.post("order/getOpenId", {code: this.code}). Then (res => {// If openID is correctly obtained, only openID is requiredif(res.openid) { this.openId = res.openid; // This. Topay ()}else{// Request failed or there is no corresponding field}Copy the code
  • Request parameter description: Obtain access_token by code

    https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
    
    Copy the code
    parameter Whether must instructions
    appid is The unique identifier of the application will be obtained after the application is approved on wechat open platform
    secret is The application key AppSecret is obtained after the application is submitted and approved on wechat open platform
    code is Fill in the code parameter obtained in the first step
    grant_type is Fill authorization_code
  • Return Result

    // Correct return {"access_token":"ACCESS_TOKEN"."expires_in": 7200,"refresh_token":"REFRESH_TOKEN"."openid":"OPENID"."scope":"SCOPE"."unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"} // Error return {"errcode": 40029,"errmsg":"invalid code"}
    Copy the code
  • Refresh the fresh-Token validity period If the token is invalid, you can use the refresh_token to obtain another token.

Wechat Pay SDK

Method 1: the official website

The invoke method, simple and effective, returns a parameter invocation directly from the interface. The following code examples are vUE environment, other environment please match, for reference only.

// Prepare the wechat SDK partjsSdk(){// determine the WeixinJSBridge of wechatif (typeof WeixinJSBridge == "undefined") {if( document.addEventListener ){
            document.addEventListener('WeixinJSBridgeReady', this.onBridgeReady, false);
        }else if (document.attachEvent){
            document.attachEvent('WeixinJSBridgeReady', this.onBridgeReady); 
            document.attachEvent('onWeixinJSBridgeReady', this.onBridgeReady); }}else{ this.onBridgeReady(); }}, // The payment SDK is readyonBridgeReady() {// invoke weixinjsbridge.invoke ()'getBrandWCPayRequest', {appId: enclosing payOption appId, / / the public name, by the merchants to timeStamp: enclosing payOption. The timeStamp, / / timeStamp, since 1970 the number of seconds nonceStr: This.payoption. nonceStr, // random string package: this.payoption. package, //prepay_id This.payoption. signType, // wechat signature: this.payoption. paySign, // wechat signature},function(res){     
           if(res.err_msg == "get_brand_wcpay_request:ok") {// Successful payment returns a success pagelet tempUrl="//paysucc"
            location.href=tempUr
           } else{// Cancel the payment or other cases get_BRAND_wcpay_REQUEST :cancel get_brand_wcpay_request:faillet tempUrl='//topay'
            location.href=tempUrl
           }    
       }
   ); 
    },
Copy the code

Method 2: JS-Weixin module needs to be introduced, and the flow is as follows:

Introduce modules –ready– get access-token– get ticket– generate signature (required by wx.config) — return parameters with interface — invoke WxPay. (More trouble, not recommended)

Reference documentation

  • Set the payment directory and callback domain name