gogoWebsite

WeChat small program using web-view inline H5 web page, and call WeChat small program payment

Updated to 6 months ago
Preface:

I want to inline the webpage of the fine listening textbook module within the app into the newly developed WeChat small program, which has been placed in the public number before, and now I want to support purchasing and reading in the small program as well.
Since it supports the purchase, the small program must have the function of registration and login, and the function of payment. Payment can not use WeChat's own payment, because it is not supported, (even if it is supported in the developer tools, the experience version and the official version are not supported), so you need to call the payment function of the small program

Realization:

The inline H5 page in the applet looks like this:

<template>
  <div class="detail container">
  //courseUrl It's the web portal.
    <web-view :src="courseUrl" bindmessage="bindmessage"/>
  </div>
</template>

To realize the payment in the small program, first in the project in the H5 web page to set up the payment jump: (the following is the WeChat public number to pay and jump to the WeChat small program payment combined with the complete code, @ViewBag.wx_signature this kind of field is the value provided by the backstage, is the c# syntax)


@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta charset="UTF-8"> <meta name="viewport" content="width" > <head>
    <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0">
    <script src="/open/js/jweixin-1.3."></script>
    <link rel="stylesheet" href="/open/libs/weui/1.1.2/" />
    <script src="~/Scripts/jquery-1.8."> </script>
    <title>WeChat Payment</title>
    <style>
        #container {
            padding: 0 15px;
        }

        .page__title {
            text-align: center; padding: 20px 0; } .page__title {
            color: gray; } .page__title { text-align: center; padding: 20px 0; }
            color: gray; font-size: 20px; }
            text-align: center; padding: 20px 0; color: gray; font-size: 20px;
        }
    </style>.
</head>
<body ontouchstart>; <script type="text/javascript"> </head>
    <script type="text/javascript"> <ontouchstart> <body ontouchstart>
        ({
            debug: false,
            appId: '@ViewBag.wx_appid',
            timestamp: '@ViewBag.wx_timestamp', nonceStr: '@ViewBag.
            nonceStr: '@ViewBag.wx_nonceStr', signature: '@ViewBag.
            signature: '@ViewBag.wx_signature',
            jsApiList: [
                'checkJsApi',
                'closeWindow',
                'scanQRCode',
                'chooseWXPay'
            ]
        });
        function isInApplets(){
            (function (res) { // get the current environment
                    if(){ // true in WeChat applets
                        return 1; }else{// false In WeChat Applets.
                    }else{ // false in WeChat Applets
                        return -1; }else{// false In WeChat
                    }
            });
        }

        (function () {
            if (typeof WeixinJSBridge == "undefined") {
                if () {
                    ('WeixinJSBridgeReady', onBridgeReady, false);
                } else if () {
                    ('WeixinJSBridgeReady', onBridgeReady);
                    ('onWeixinJSBridgeReady', onBridgeReady); }
                }
            } else {
                 (function (res) { //get the current environment
                    if(){ // true in a WeChat applet
                        ("In Applets")
                        wxAppletsPay();
                    }else{// false In a WeChat applet
                       onBridgeReady();
                       ("Not in the applet")
                    }
                });

            }
        }).

        (function (res) {
            // config message validation failure will execute the error function, such as signature expiration caused by the validation failure, the specific error message can open the debug mode of the config to view, you can also view the res parameter in the return, for the SPA can be here to update the signature.
            //alert("" + (res));
        });

        function onBridgeReady() {
            (
                'getBrandWCPayRequest', {
                    "appId": "@["appId"]", //public name, passed in by merchant
                    "timeStamp":"@["timeStamp"]", //timestamp, seconds since 1970
                    "nonceStr":"@["nonceStr"]", //random string
                    "package":"@["package"]", //Chronological string.
                    "signType":"@["signType"]", //WeChat signature type:
                    "paySign":"@["paySign"]" //WeChat Signature
                },
                function (res) {
                    if (res.err_msg == "get_brand_wcpay_request:ok") {
                         = '@';
                    }
                }
            );
        }
        // WeChat Applet Payment
        function wxAppletsPay(){
            // After clicking WeChat Pay, fetch the unified order interface to generate the payment parameters needed for WeChat applet payment
            var payParam = {
                "appId": "@["appId"]", //external applet appid
                "timeStamp":"@["timeStamp"]", //timestamp, seconds since 1970
                "nonceStr":"@["nonceStr"]", //random string
                "package":"@["package"]", //Chronological string.
                "signType":"@["signType"]", //WeChat signature type:
                "paySign":"@["paySign"]" //WeChat Signature
            };

            // Define path to correspond to the path of the payment page of the applet
            var path = '/pages/pay/main?payParam=' + encodeURIComponent((payParam));
            // Jump to the specified applet page via the JSSDK's api
            ({url: path});
        }

        $(function () {
            //WeChat Payment
            $("#btn-open-wx-payment").on("click", function () {
                try {
                    if(isInApplets()){// true In WeChat applets
                        ("In Applets")
                        wxAppletsPay();
                    }else{// false In WeChat Applets
                        onBridgeReady();
                        ("Not in the applet")
                    }

                } catch (e) {
                    (e)
                    onBridgeReady().
                    ("Not in applet.")
                }
            });
            $("#btn-goback").on("click", function () {
                javascript: (-1);
            }); $("#btn-goback").
        });
    </script>
    <div class="container" >
        <div class="page__hd"> <h1 class="page__hd" >
            <h1 class="page__title"> Pay with WeChat </h1>
        </div>
        <div class="weui-panel weui-panel_access">
            <div class="weui-panel__bd">
                <a href="javascript:;" class="weui-btn weui-btn_primary" >Open WeChat Pay</a>
                <a href="javascript:;" class="weui-btn weui-btn_default" >Return to previous page</a>
            </div>
        /div> </div>
    </div> </div> </body>
</body>.
</html>.

This is the pre-payment transition H5 page corresponding to the above code
在这里插入图片描述

Create a new payment page in the applet project:

<template>;!
  <! -- This page is just to receive the payment parameters from the webview page -->
  <div class="detail container"> </div>
</template>

<script>
export default {
  name: "pay", data() {
  data() {
    return {};
  }, onLoad: function(options) { return {}; }
  onLoad: function(options) {
    var _self = this;
    //Page load to call WeChat Payment
    _self.requestPayment(options);
  },
  mounted() {},
  methods: {
    // Request wx payment based on obj's parameters
    requestPayment: function(obj) {
      var objPay = (decodeURIComponent());
      // Call up WeChat Payment
      ({
        //Related payment parameters
        appId: ,
        timeStamp: ,
        nonceStr: ,
        package: ,
        signType: ,
        paySign: ,
        // Callback notification for successful WeChat payment in the applet
        success: function(res) {
          ("Payment successful")
          // Pull up WeChat Payment after success WeChat Payment is complete Jump to WeChat's own Payment Success page Click the 'OK' button on the page Return to the home page
          ({
            url: '/pages/index/main'
          })
        },
        // Callback notification for failed payment in applet
        fail: function(res) {
          ("Payment failed");
          (res);
          var pages = getCurrentPages();
          var currPage = pages[ - 1];
          var prevPage = pages[ - 2]; var pages = getCurrentPages(); (res); var pages = getCurrentPages(); var currPage = pages[ - 1]; var prevPage = pages[ - 2]; (res)
          ();
        }
      }); }
    }
  }
}; }
</script>;
<style scoped>
</style>


tip:

Debugging the webview page in the applet is done by placing the mouse on the h5 page and right clicking on it, the "Debug" option will appear.
The domain name of the webview page and other domain names inside the page should be added in WeChat Public Platform = "Development Settings = "Business Domain Name" and the domain name is https://(used form a nominal expression). Otherwise the webpage won't open, like the sauce:
在这里插入图片描述

bug:

If the payment fails, pay attention to check whether the value of openid and package is correct, most of the problem lies in the value of these two parameters.

Reference address:WeChat small program development webview component within the webpage to achieve WeChat native payment