Vue WeChat public account development pit record
WeChat JS-SDK is a web development toolkit based on WeChat provided by WeChat public platform for web developers.
By using WeChat JS-SDK, web developers can use WeChat to efficiently use the capabilities of mobile phone systems such as taking pictures, selecting pictures, voice, and location. At the same time, they can directly use WeChat to share, scan, coupon, pay, etc. Unique ability to provide WeChat users with a better web experience
If we want to implement WeChat sharing, payment and other functions in the embedded h5 of the official account, we have to introduce js- sdk.
There is a key link in using js-sdk, which is to inject permission verification configuration through the config interface, and there is a signature parameter in the configuration that needs to be obtained with the help of the server. I won’t go into too much detail here. You can learn more about it through the official documentation.
Hash or History?
In the previous article, I recommended that you configure vue-router to use hash mode in vue. So what is the difference between hash mode and history mode? Let me give you an example, assuming that we all enter through http://domain.com
, and then jump to the page with the route /jssdk
, which requires jssdk, then the actual js-sdk The current page URL obtained during signature verification is different between ios and andrioid. Here I show it through a table:
The truth is in the table, I'm not good at expressing myself. Please forgive me for being lazy. 23333333.
If you do not have the need to access and share the specified page, the hash mode is very convenient, but unfortunately I need to share it through WeChat. If you use the hash mode, WeChat will automatically process the part after # of the shared address. , then I will not be able to share the specified page to Moments or to friends.
What should I do? I can only solve the history problem hard. In fact, it is easy to solve, that is, iOS needs to use the URL of the first entry page to obtain the signature, and Android needs to reconfigure the signature every time the route is switched.. I will list two solutions here:
Record the page URL in the entry file. After the page component is created, ios gets the recorded url for signature, and android gets the current route (
window .location.href.split('#')[0]
), please go to my previous blogentry file to directly perform signature and injection configuration. Only for android, re-sign and configure every time you switch routes. This solution is suitable for all pages that need to use js-sdk
Problem record
Now list the bugs I encountered during the tinkering process:
Android devices can share and ios devices cannot;
The reason for this problem is that the history mode is used and the ios calibration is not considered The URL obtained by the verification signature is the URL visited for the first time and the URL after switching is used.
You cannot share when ios devices enter the page. You can only share after manually refreshing the page;
This bug is very strange, and the author did not understand the details. If you know what happened, be sure to share it with me.
You can share normally by clicking on the link, but you cannot share after clicking on the graphic message shared by others;
Conjecture 1: When clicking on the graphic message, the url used by WeChat for signature verification removes the parameters added by WeChat, so we also need to remove the parameters added by WeChat when signing? So I put the WeChat parameters as
` After removing the ?from=singlemessage&isappinstalled=0' part, the result is that the sharing still fails. But if I add a parameter at will, the sharing will be normal. When I add two parameters at will, the sharing will be abnormal again.
Conjecture 2: Only one parameter is allowed in the URL shared by WeChat for signature verification? So I wrote like this: url = location.href.split('&')[0]
. After verification, I found it was wrong. When I thought about it more carefully, I actually had such a terrible idea. I don’t even believe the official documents.
Conjecture 3: Does the URL need to be encoded? That is url = encodeURIComponent(window.location.href.split('#')[0])
After many times of debugging, I finally found the problem, which is that the signed url needs to be encoded, word Brother, it’s not easy.
Only the signed url needs to be encoded. The url in the sharing configuration does not need to be encoded.
Only the signed url needs to be encoded and shared. The URL in the configuration does not need to be encoded
Only the signed URL needs to be encoded, the URL in the shared configuration does not need to be encoded
This is another pitfall, be careful .
After debugging and trying N times, I coded dozens of lines of code and solved all the above problems. Looking back, I am really young. It is such a simple logic. Maybe someone else can do it in one step. It's in place, but I have fought with various bugs many times (who can understand the sadness of having to go to the production environment to debug after changing a little code), alas. . .
Coding
Share how I configure WeChat sharing according to the second plan
Since the requirement in my project is that basically all pages need to be able to be shared, so I obtain it in each page component Signing is not practical, so I want to use vue-router's after hook to complete the sharing configuration operation. For android, I need to re-sign.
// main.js ... import wx from 'weixin-js-sdk' import request from 'axios' ... router.afterEach((to, from) => { let _url = window.location.origin + to.fullPath // 非ios设备,切换路由时候进行重新签名 if (window.__wxjs_is_wkwebview !== true) { request.get('/api/jssdk?url=' + encodeURIComponent(_url)).then(function (_lists) { // 注入配置 wx.config({ ... }) }) } // 微信分享配置 wx.ready(function () { wx.onMenuShareTimeline({ ... }) wx.onMenuShareAppMessage({ ... }) }) }) ... // ios 设备进入页面则进行js-sdk签名 if (window.__wxjs_is_wkwebview === true) { let _url = window.location.href.split('#')[0] request.get('/api/jssdk?url=' + encodeURIComponent(_url)).then(function (res) { let _lists = res wx.config({ debug: false, appId: _lists.appId, timestamp: _lists.timestamp, nonceStr: _lists.nonceStr, signature: _lists.signature, jsApiList: ['chooseImage', 'uploadImage', 'previewImage', 'onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareTimeline', 'chooseWXPay'] }) }) }
Calling WeChat payment
Where will the two plans go?
h5 When using WeChat payment, careful people will find that WeChat has two plans. I have a rough understanding of one. , one is the open capability in js-sdk, and the other is the interface provided by the WeChat payment open platform
js-sdk version:
WeChat payment version:
If you only need to call payment in the official account, both methods are fine. Since the author has used js-sdk to access other functions, here I chose the chooseWXPay method.
Access steps
On the premise that all other functions are successfully accessed, receiving payment will be quick and convenient. The author lists the main steps:
Configure the js security interface domain name (such as www.imwty.com) in the WeChat public platform. This is the prerequisite for calling js-sdk. Public account payment is also based on js-sdk;
-
To set up the payment directory in the WeChat payment platform, please refer to the WeChat payment development documentation. What needs to be explained here is the page route you need to pay for, what you need to configure, and you need to add / at the end (for example www.imwty .com/pay/)
Call js-sdk signature configuration (wechat.config), which has been mentioned above.
In the logic of clicking the payment button, the wechat.chooseWXPay() method is called. This method also involves the payment signature and needs to obtain the signature information from the server
Note: Be sure not to miss /
when accessing the payment page. WeChat will strictly compare whether the route of the page you are on when calling step 4 is consistent with the route set in the payment platform.
Coding
Here we mainly show the author’s writing method in step 4, for reference only
... methods () { handlerPay () {**粗体文本** let self = this // 进行支付签名 apiUtil.get('/api/jssdk/pay', {amount: this.amount}).then(function (wxmsg) { self.$wechat.chooseWXPay({ // 支付签名时间戳,注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符 appId: wxmsg.appId, timestamp: wxmsg.timeStamp, nonceStr: wxmsg.nonceStr, // 支付签名随机串,不长于 32 位 package: wxmsg.package, // 统一支付接口返回的prepay_id参数值,提交格式如:prepay_id=***) signType: wxmsg.signType, // 签名方式,默认为'SHA1',使用新版支付需传入'MD5' paySign: wxmsg.paySign, // 支付签名 success: function (res) { // 支付成功的回调函数 }, cancel: function (res) { // 支付取消的回调函数 }, error: function (res) { // 支付失败的回调函数 } }).catch(function () { ... }) } }
Related recommendations:
WeChat public account development Summary of common configuration error messages
Detailed introduction to WeChat public account development
The above is the detailed content of Vue WeChat public account development pit record. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Pinduoduo software provides a lot of good products, you can buy them anytime and anywhere, and the quality of each product is strictly controlled, every product is genuine, and there are many preferential shopping discounts, allowing everyone to shop online Simply can not stop. Enter your mobile phone number to log in online, add multiple delivery addresses and contact information online, and check the latest logistics trends at any time. Product sections of different categories are open, search and swipe up and down to purchase and place orders, and experience convenience without leaving home. With the online shopping service, you can also view all purchase records, including the goods you have purchased, and receive dozens of shopping red envelopes and coupons for free. Now the editor has provided Pinduoduo users with a detailed online way to view purchased product records. method. 1. Open your phone and click on the Pinduoduo icon.

This AI-assisted programming tool has unearthed a large number of useful AI-assisted programming tools in this stage of rapid AI development. AI-assisted programming tools can improve development efficiency, improve code quality, and reduce bug rates. They are important assistants in the modern software development process. Today Dayao will share with you 4 AI-assisted programming tools (and all support C# language). I hope it will be helpful to everyone. https://github.com/YSGStudyHards/DotNetGuide1.GitHubCopilotGitHubCopilot is an AI coding assistant that helps you write code faster and with less effort, so you can focus more on problem solving and collaboration. Git

On March 3, 2022, less than a month after the birth of the world's first AI programmer Devin, the NLP team of Princeton University developed an open source AI programmer SWE-agent. It leverages the GPT-4 model to automatically resolve issues in GitHub repositories. SWE-agent's performance on the SWE-bench test set is similar to Devin, taking an average of 93 seconds and solving 12.29% of the problems. By interacting with a dedicated terminal, SWE-agent can open and search file contents, use automatic syntax checking, edit specific lines, and write and execute tests. (Note: The above content is a slight adjustment of the original content, but the key information in the original text is retained and does not exceed the specified word limit.) SWE-A

Go language development mobile application tutorial As the mobile application market continues to boom, more and more developers are beginning to explore how to use Go language to develop mobile applications. As a simple and efficient programming language, Go language has also shown strong potential in mobile application development. This article will introduce in detail how to use Go language to develop mobile applications, and attach specific code examples to help readers get started quickly and start developing their own mobile applications. 1. Preparation Before starting, we need to prepare the development environment and tools. head

Summary of the five most popular Go language libraries: essential tools for development, requiring specific code examples. Since its birth, the Go language has received widespread attention and application. As an emerging efficient and concise programming language, Go's rapid development is inseparable from the support of rich open source libraries. This article will introduce the five most popular Go language libraries. These libraries play a vital role in Go development and provide developers with powerful functions and a convenient development experience. At the same time, in order to better understand the uses and functions of these libraries, we will explain them with specific code examples.

Android development is a busy and exciting job, and choosing a suitable Linux distribution for development is particularly important. Among the many Linux distributions, which one is most suitable for Android development? This article will explore this issue from several aspects and give specific code examples. First, let’s take a look at several currently popular Linux distributions: Ubuntu, Fedora, Debian, CentOS, etc. They all have their own advantages and characteristics.

"Understanding VSCode: What is this tool used for?" 》As a programmer, whether you are a beginner or an experienced developer, you cannot do without the use of code editing tools. Among many editing tools, Visual Studio Code (VSCode for short) is very popular among developers as an open source, lightweight, and powerful code editor. So, what exactly is VSCode used for? This article will delve into the functions and uses of VSCode and provide specific code examples to help readers

As a fast and efficient programming language, Go language is widely popular in the field of back-end development. However, few people associate Go language with front-end development. In fact, using Go language for front-end development can not only improve efficiency, but also bring new horizons to developers. This article will explore the possibility of using the Go language for front-end development and provide specific code examples to help readers better understand this area. In traditional front-end development, JavaScript, HTML, and CSS are often used to build user interfaces
