• Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Payment application scenarios of wechat and Alipay

  1. APP (Android & IOS)
  2. The browser
    1. PC
    2. Wap side
      1. Application browsers: Chrome, Firefox, Opera…
      2. Wechat has a built-in browser

Here, we can divide it into PC terminal, mobile terminal and wechat terminal for convenient classification and explanation

Front-end Implementation Principles

  1. As for APP, it is necessary to deal with the compatibility of mobile phone system jump mode.

  2. In terms of browsers, when alipay and wechat pay are carried out on PC and WAP ends and non-wechat built-in browsers, the front-end only needs to jump according to the path returned by the back-end interface (GET URL jump) or form label string (POST Submit submission).

  3. And in the wechat built-in browser, the front end is required for special processing, because there are PC micro built-in browser and mobile micro built-in browser.

As is known to all, different platforms will block the links of “potentially dangerous WEBSITES” and do not allow the jump. For example, if you click the alipay payment link on wechat, it is impossible to jump, and vice versa. Therefore, we need to create a middle prompt page in the front page.

Recently, the Ministry of Industry and Information Technology (MIIT) proposed the action of “tearing down the wall” in response to the phenomenon of “Internet wall”. It is obvious that this beautiful “avalanche” is happening in the Internet world, and all of you present here are the snowflakes in it, big or small.

Alipay Payment

Alipay open platform document

  • Browser platform

    1. PC: alipay. Trade. Page. Pay

      • Effect: jump to the official website platform, display qr code scanning payment
      • Reference Documents:Payment API > Unified ordering and payment page interface
        • The sample URL
        https://openapi.alipay.com/gateway.do?method=alipay.trade.page.pay&app_id=202100210460...Copy the code
    2. Wap end: Alipay.trade.wap. Pay – Implementation effect: Evoke alipay App – reference API > mobile phone website payment interface 2.0 sample URL https://openapi.alipay.com/gateway.do?method=alipay.trade.wap.pay&app_id=2021002104604…

    3. WeChat side:

      When alipay is invoked in the built-in browser of wechat, wechat cannot directly wake up Alipay, and a guide page is required as the middle page to prompt the user to open it in the browser, and then wake up alipay for payment

      Note that the Method of alipay interface is different between the built-in wechat browser Alipay.trade.page.pay on PC and Alipay.trade.wap. Pay on mobile, so ensure that the parameters submitted in exchange for alipay payment path are correct

      Wechat public platform can not use alipay payment solution official documents

      • Steps to implement alipay payment scheme in wechat:
        1. New Boot pageAPGuide.vue
        2. Add bootpage routing/apGuideAnd set it to the whiteList without redirection to avoid the impact of login redirect
        3. When selecting the confirmation page to jump to the guide page of Alipay payment, the alipay jump path should be carried out firstencodeURIComponentDouble coding orescapeEncrypted, concatenated after the URL as a parameter, then usedlocation.hrefJump to the boot page
        4. The guide page determines whether it is on the wechat built-in browser or has jumped to the browser through the wechat menu
          • On wechat, the content of the guide page is displayed
          • On the PC or Wap browser, the URL parameters are processed, and the alipay jump path is taken outdecodeURIComponentDouble decryption orunescapeDecryption,location.hrefMeans jump pay treasure
        5. Vue sample core code:
        // RechargeInfo. Vue payment confirmation page window.location.href = '${location.origin}/apGuide? Url =${encodeURIComponent(encodeURIComponent((res.data.pay_url)))} '// apguide. vue <template> <div class="ap-guide-dialog"> <div class="ap-guide-dialog-content"> <div class="J-weixin-tip weixin-tip" ref="weixinTip"> <div class="weixin-tip-content"> Please select in the menu open in browser,<br/> to complete payment </div> <div class=" j-weixin-tip-img weixin-tip-img" ref="weixinTipImg"></div> </div> </div> </template> // script mounted(){ if (location.hash.indexOf('error') ! = 1) {alert(' parameter error, please check '); } else { var ua = navigator.userAgent.toLowerCase(); var tip = this.$refs.weixinTip; var tipImg = this.$refs.weixinTipImg; if (ua.indexOf('micromessenger') ! = -1) { tip.style.display = 'block'; tipImg.style.display = 'block'; if (ua.indexOf('iphone') ! = -1 || ua.indexOf('ipad') ! = -1 || ua.indexOf('ipod') ! = -1) { tipImg.className = 'J-weixin-tip-img weixin-tip-img iphone' } else { tipImg.className = 'J-weixin-tip-img weixin-tip-img android' } } else { let APurl = decodeURIComponent(decodeURIComponent((location.search.split('? ')[1].substr(location.search.split('? ')[1].indexOf('=')+1)))); window.location.href = APurl; }}},Copy the code

        DecodeURIComponent (decodeURIComponent()) two encoding reason: two encoding to the background, the server received parameters for the first time after decoding into a UTF-8 encoding string, so call again to decode once into Chinese. Therefore, Chinese parameters carrying Chinese need two encoding, one encoding cannot get the correct result

  • APP: alipay. Trade. APP. Pay

    • Implementation: APP embedded H5 page, using technology and browser end, mainly considering the normal jump back problem of APP
    • Effect: Evoke alipay AppPayment API > APP Payment Interface 2.0- the sample URLhttps://openapi.alipay.com/gateway.do?method=alipay.trade.app.pay&app_id=202100210460...
  • Escape, encodeURI, and encodeURIComponent

    1. Function:
      1. Escape () cannot be used directly for URL encoding; its real function is to return the Unicode encoding value of a character. For example, “Spring Festival” returns %u6625%u8282, escape() does not + code.

        It is mainly used for encoding Chinese characters and is now not recommended.

      2. EncodeURI () is the function in JS that actually encodes urls. Encode the entire URL address, but for special meaning symbols; /? : @ & = + $, #, also not encoded.

        The corresponding decoding function is decodeURI().

      3. EncodeURIComponent () can encode; /? : @ & = + $, # These special characters. The corresponding decoding function is decodeURIComponent().

        To pass ampersand urls, encodeURIComponent() is recommended.

    2. Application Scenarios:
      1. If it is just an encoding string that has nothing to do with the URL, useescape.
      2. If you need to encode the entire URL and then you need to use that URL, useencodeURI.
      3. When you need to encode parameters in the URL, thenencodeURIComponentIs the best way.

WeChat pay

Wechat Pay developer documentation

  • Browser platform
    1. PC:
      • Implementation effect: from the back end to return the TWO-DIMENSIONAL code or front-end path to two-dimensional code, so as to display two-dimensional code picture scan code payment – Reference document: Native order API
      • The sample URL
      weixin://wxpay/bizpayurl? Pr = OaEfZ...Copy the code
    2. Wap side:
      • Effect: withwindow.location.hrefJump directly to the back end return path, thus arousing wechat App for payment
      • Reference document: H5 wechat Pay
      • The sample URL
      https://wx.tenpay.com/cgi-bin/mmpayweb-bin/checkmweb?prepay_id=wx081520... & package = 31101...Copy the code
    3. WeChat side:
      • Implementation effect: Wechat authorized login to adjust the payment
      • JSAPI invokes wechat Payment
      • Vue sample code
      If (isWx() &&! This. Params ('is_success_auth')) {this.$confirm(' is_success_auth'); ', 'confirmButtonText ', {confirmButtonText:' confirm ', cancelButtonText: 'cancel ', type: 'warning',}). Then (() => { }) .catch(() => {}); return; }}, methods: {openId wxLogin: function () {let callbackUrl = location.href; Let url = getreqinfo.getreqinfo(). Apiurl + '/user/wechat/oauth' + '? callback=' + escape(callbackUrl) + '&token=' + window.tools.cache.get('token') + '&service=user'; window.location.href = url; }, // confirm confirmPay() {let _this = this; let ajaxData = { pay_type: Number(this.payType), money: this.rechragePrice, method: 'api.pay.userRecharge', API_trade_type: ', // API transaction type}; // API_trade_type string No API transaction type H5 alipay or wechat mobile browser jsAPI wechat browser, Default web side if (isWx()) {// wechat side if (this.payType == 2) {// Alipay // mobile side wechat built-in browser & PC side wechat built-in browser ajaxData. Api_trade_type = isWapWx() ? 'h5' : ''; } else if (this.payType == 3) {// wx // ajaxData. Api_trade_type = isWapWx()? 'jsapi' : ''; } else { ajaxData.api_trade_type = ''; }} else {/ / mobile end & PC end ajaxData api_trade_type = isAndroid () | | isIOS ()? 'h5' : ''; } this.$myAjax({ ajaxData: params, type: 'POST', successFun: res => { this.payRelated.out_trade_no = res.data.out_trade_no; if (isWx() && this.params('is_success_auth')) { WeixinJSBridge.invoke( 'getBrandWCPayRequest', { appId: Res.data.js_params. appId, // public id, passed in by merchant timeStamp: res.data.js_params.timeStamp, // timeStamp, number of seconds since 1970 nonceStr: Res.data.js_params. nonceStr, // random string package: res.data.js_params.package, signType: Res.data.js_params. signType, // wechat signature: paySign: Res.data.js_params. paySign, // wechat signature}, Function (res) {if (res.err_msg == 'get_brand_wcpay_request: OK ') {// h. $toast(' paid successfully '); // Poll the payment result //...... } else if (res) err_msg = = 'get_brand_wcpay_request: cancel') {window. The tools. Alert. The message (' cancel '); } else {window.tools.alert.error(' payment failed '); }}); return; } // Other payment type processing //...... }}); }},Copy the code

      Pay attention to the payment process, polling order payment status to avoid mistakes

Js redirect mode of the page

  1. Form Submission (POST)
    • If the background interface returns a form tag string, the jump is committed this way
    • The sample demo
    Let _str =' <form id=' alipaySubmit 'name=' alipaySubmit' Action = 'https://openapi.alipay.com/gateway.do' method = 'POST' > < input type = "hidden" name = 'app_id' value = '201805106... '/> <input type='hidden' name='method' value='alipay.trade.page.pay'/> <input type='hidden' name='format' value='JSON'/> / /... <input type='submit' value='ok' style='display:none; ''> </form> <script>document.forms['alipaysubmit'].submit(); </script> `; _str = _str.replace(/form/, 'form target="_blank"'); div.innerHTML = _str; document.body.appendChild(div); document.forms.alipaysubmit.submit();Copy the code
  2. window.location.href
  3. window.open
  4. The a tag triggers the click event

    Note: This method can be used on both Android and PC, but it cannot be used on iOS. Therefore, it is not recommended to use this method