search
HomeWeb Front-endH5 TutorialH5 WeChat payment solution to the failure of introducing WeChat's js-sdk package

The content shared with you in this article is about the solution to the failure of introducing WeChat’s js-sdk package in H5 WeChat payment. The content is of great reference value and I hope it can help friends in need.

Preface

In the development of WeChat public account activities, since I have not been exposed to WeChat-related development before, I fell into pits and climbed into pits. However, it also made me understand WeChat public and WeChat official Familiarity with documentation is greatly increased.

Climb the pit: There is a high probability that Android will fail to activate WeChat payment (failed to introduce WeChat's js-sdk package)

In the official document of WeChat: https://pay.weixin.qq. com/wik...
There is such a DEMO:
function onBridgeReady(){
   WeixinJSBridge.invoke(
      'getBrandWCPayRequest', {
         "appId":"wx2421b1c4370ec43b",     //公众号名称,由商户传入     
         "timeStamp":"1395712654",         //时间戳,自1970年以来的秒数     
         "nonceStr":"e61463f8efa94090b1f366cccfbbb444", //随机串     
         "package":"prepay_id=u802345jgfjsdfgsdg888",     
         "signType":"MD5",         //微信签名方式:     
         "paySign":"70EA570631E4BB79628FBCA90534C63FF7FADD89" //微信签名 
      },
      function(res){
      if(res.err_msg == "get_brand_wcpay_request:ok" ){
      // 使用以上方式判断前端返回,微信团队郑重提示:
            //res.err_msg将在用户支付成功后返回ok,但并不保证它绝对可靠。
      } 
   }); 
}
if (typeof WeixinJSBridge == "undefined"){
   if( document.addEventListener ){
       document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
   }else if (document.attachEvent){
       document.attachEvent('WeixinJSBridgeReady', onBridgeReady); 
       document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
   }
}else{
   onBridgeReady();
}
After the back-end colleague successfully authorizes it, introduce this code on the activity page, be happy, build and submit for testing. Apple is fine. , Android seems to be fine, but sometimes Goose Android cannot adjust the payment. I initially thought it was due to the WeChat version, etc. However, the probability of successful adjustment is too low. It can only be adjusted once every 10 times. , it must be the code reason. Change it.

Solution:

Open the WeChat developer tools, log, and finally find that at this step if (typeof WeixinJSBridge == "undefined")
1.ios can activate WeChat Browser's js-sdk
2. Most Androids go to undefined
Actually, I don't know the reason here. Personally, I feel it is a problem with the built-in browser version of WeChat Android and the WeixinJSBridge method. (I hope someone can answer it)
Since js-sdk cannot be adjusted, then introduce the configuration manually //So sometimes being lazy is more troublesome, learn lessons
if (typeof WeixinJSBridge == "undefined"){
    console.log( WeixinJSBridge);
   if( document.addEventListener ){
       document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
   }else if (document.attachEvent){
       document.attachEvent('WeixinJSBridgeReady', onBridgeReady); 
       document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
   }
}else{
   onBridgeReady();
}

Vue introduces WeChat js-sdk Package

npm i -S weixin-js-sdk

Introduce module

import wx from 'weixin-js-sdk'

configuration on the page that needs to be introduced (refer to WeChat official documentation: https://mp.weixin.qq.com/wiki...):

wx.config({
    debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
    appId: '', // 必填,公众号的唯一标识
    timestamp: , // 必填,生成签名的时间戳
    nonceStr: '', // 必填,生成签名的随机串
    signature: '',// 必填,签名
    jsApiList: [] // 必填,需要使用的JS接口列表 比如我要调用支付接口 那么就是 [chooseWXPay]
});

这里timestamp是小写 s 是小写,数据类型是 int 类型

Now that the configuration is successful, let’s continue reading the official documentation
The official documentation says that there is a ready method. After the config verification is successful, put the interface in it to ensure execution.

wx.ready(function(){
    // config信息验证后会执行ready方法,所有接口调用都必须在config接口获得结果之后,config是一个客户端的异步操作,所以如果需要在页面加载时就调用相关接口,则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口,则可以直接调用,不需要放在ready函数中。
});

Introduction parameters in ready (pay attention to the data type, and cooperate well with back-end colleagues - -)

wx.chooseWXPay({
timestamp: 0, // 支付签名时间戳,注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
nonceStr: '', // 支付签名随机串,不长于 32 位
package: '', // 统一支付接口返回的prepay_id参数值,提交格式如:prepay_id=\*\*\*)
signType: '', // 签名方式,默认为'SHA1',使用新版支付需传入'MD5'
paySign: '', // 支付签名
success: function (res) {
// 支付成功后的回调函数
}
});

Attached is my demo

Use Vue data in ready The data in WXPay accidentally fell into the pit pointed by this. If you do not add bind, the parameters in wx.chooseWXPay cannot get the data returned from the backend request. This here does not point to VueComponent, so naturally the request cannot be obtained. Finally, I assigned the data of this.wx_config array object.
getConfig(){
            wx.config({
                debug: this.wx_config.debug, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
                appId: this.wx_config.appId, // 必填,公众号的唯一标识
                timestamp: this.wx_config.timestamp, // 必填,生成签名的时间戳
                nonceStr: this.wx_config.nonceStr, // 必填,生成签名的随机串
                signature:this.wx_config.signature,// 必填,签名
                jsApiList: this.wx_config.jsApiList // 必填,需要使用的JS接口列表
            });
            //微信支付
            wx.ready(function() {
                // console.log(this.jsApiCall());
                wx.chooseWXPay({
                    timestamp: this.wechat_code.timestamp,
                    nonceStr:this.wechat_code.nonceStr,
                    package: this.wechat_code.package,
                    signType: this.wechat_code.signType,
                    paySign: this.wechat_code.paySign,
                    success: function () {
                        // 支付成功后的回调函数
                        alert("支付成功");
                        window.location.href = "/hd/becomevip";
                    },
                    cancel: function() {
                        alert("支付失败");
                    }
                });
            }.bind(this));
        },

Summary:

It is always inevitable to step into pitfalls. To summarize, don’t do the right thing because you are afraid of trouble~

Related recommendations:

About the solution to the 1px border in the mobile H5 page

About the sharing introduction of the html5 canvas WeChat poster

The above is the detailed content of H5 WeChat payment solution to the failure of introducing WeChat's js-sdk package. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
H5 Code: Best Practices for Web DevelopersH5 Code: Best Practices for Web DevelopersApr 16, 2025 am 12:14 AM

Best practices for H5 code include: 1. Use correct DOCTYPE declarations and character encoding; 2. Use semantic tags; 3. Reduce HTTP requests; 4. Use asynchronous loading; 5. Optimize images. These practices can improve the efficiency, maintainability and user experience of web pages.

H5: The Evolution of Web Standards and TechnologiesH5: The Evolution of Web Standards and TechnologiesApr 15, 2025 am 12:12 AM

Web standards and technologies have evolved from HTML4, CSS2 and simple JavaScript to date and have undergone significant developments. 1) HTML5 introduces APIs such as Canvas and WebStorage, which enhances the complexity and interactivity of web applications. 2) CSS3 adds animation and transition functions to make the page more effective. 3) JavaScript improves development efficiency and code readability through modern syntax of Node.js and ES6, such as arrow functions and classes. These changes have promoted the development of performance optimization and best practices of web applications.

Is H5 a Shorthand for HTML5? Exploring the DetailsIs H5 a Shorthand for HTML5? Exploring the DetailsApr 14, 2025 am 12:05 AM

H5 is not just the abbreviation of HTML5, it represents a wider modern web development technology ecosystem: 1. H5 includes HTML5, CSS3, JavaScript and related APIs and technologies; 2. It provides a richer, interactive and smooth user experience, and can run seamlessly on multiple devices; 3. Using the H5 technology stack, you can create responsive web pages and complex interactive functions.

H5 and HTML5: Commonly Used Terms in Web DevelopmentH5 and HTML5: Commonly Used Terms in Web DevelopmentApr 13, 2025 am 12:01 AM

H5 and HTML5 refer to the same thing, namely HTML5. HTML5 is the fifth version of HTML, bringing new features such as semantic tags, multimedia support, canvas and graphics, offline storage and local storage, improving the expressiveness and interactivity of web pages.

What Does H5 Refer To? Exploring the ContextWhat Does H5 Refer To? Exploring the ContextApr 12, 2025 am 12:03 AM

H5referstoHTML5,apivotaltechnologyinwebdevelopment.1)HTML5introducesnewelementsandAPIsforrich,dynamicwebapplications.2)Itsupportsmultimediawithoutplugins,enhancinguserexperienceacrossdevices.3)SemanticelementsimprovecontentstructureandSEO.4)H5'srespo

H5: Tools, Frameworks, and Best PracticesH5: Tools, Frameworks, and Best PracticesApr 11, 2025 am 12:11 AM

The tools and frameworks that need to be mastered in H5 development include Vue.js, React and Webpack. 1.Vue.js is suitable for building user interfaces and supports component development. 2.React optimizes page rendering through virtual DOM, suitable for complex applications. 3.Webpack is used for module packaging and optimize resource loading.

The Legacy of HTML5: Understanding H5 in the PresentThe Legacy of HTML5: Understanding H5 in the PresentApr 10, 2025 am 09:28 AM

HTML5hassignificantlytransformedwebdevelopmentbyintroducingsemanticelements,enhancingmultimediasupport,andimprovingperformance.1)ItmadewebsitesmoreaccessibleandSEO-friendlywithsemanticelementslike,,and.2)HTML5introducednativeandtags,eliminatingthenee

H5 Code: Accessibility and Semantic HTMLH5 Code: Accessibility and Semantic HTMLApr 09, 2025 am 12:05 AM

H5 improves web page accessibility and SEO effects through semantic elements and ARIA attributes. 1. Use, etc. to organize the content structure and improve SEO. 2. ARIA attributes such as aria-label enhance accessibility, and assistive technology users can use web pages smoothly.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor