SoFunction
Updated on 2025-04-13

Code examples for implementing WeChat payment in webpages in mini program webview

Implementing WeChat payment function in the webview of the applet requires interaction between the applet and the webview. Here is a simple code implementation example:

  • In the applet, create a webview component and specify the URL address to load:
<web-view src="/payment"></web-view>
  • In the webview page, introduce the SDK code of WeChat Pay and implement the payment function:
&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;

&lt;head&gt;
  &lt;meta charset="UTF-8"&gt;
  &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;
  &lt;script src="/open/js/jweixin-1.6."&gt;&lt;/script&gt;
  &lt;title&gt;WeChat Payment&lt;/title&gt;
&lt;/head&gt;

&lt;body&gt;
  &lt;button &gt;Pay&lt;/button&gt;

  &lt;script&gt;
    // Implement WeChat payment function here    ('payButton').addEventListener('click', function() {
      // Call the WeChat payment interface      ('getBrandWCPayRequest', {
        appId: 'xxxxxx', // WeChat Pay AppID        timeStamp: 'xxxxxx', // Time stamp        nonceStr: 'xxxxxx', // Random string        package: 'xxxxxx', // Payment package        signType: 'xxxxxx', // Signature type        paySign: 'xxxxxx' // sign      }, function(res) {
        if (res.err_msg == 'get_brand_wcpay_request:ok') {
          // Successful payment operation        } else {
          // Payment failed operation        }
      });
    });
  &lt;/script&gt;
&lt;/body&gt;

&lt;/html&gt;
  • In the script code of the applet, listen for events in the webview and perform corresponding processing:
Page({
  onMessage: function(e) {
    // Listen to messages sent by webview    if ( === 'paymentSuccess') {
      // Successful payment operation    } else if ( === 'paymentFailed') {
      // Payment failed operation    }
  }
});
  • In the JS code of the webview page,Method to send a message to the applet:
// Call at a location where payment is successful or payment failed({ data: 'paymentSuccess' }, '*');
// or({ data: 'paymentFailed' }, '*');

Through the above code, messages can be passed between the applet and the webview, thereby realizing the function of using webview to make WeChat payment in the applet.

Summarize

This is the article about the implementation of WeChat payment in the webview of the mini program webview. For more related webview content in the webview of the mini program webview, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!