Home  >  Article  >  WeChat Applet  >  Vue WeChat public account development pit record

Vue WeChat public account development pit record

小云云
小云云Original
2017-12-08 14:11:254390browse

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:
Vue WeChat public account development pit record

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:

  1. 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 blog

  2. entry 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:

  1. 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.

  1. 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.

  1. 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:
Vue WeChat public account development pit record
WeChat payment version:
Vue WeChat public account development pit record

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:

  1. 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;

  2. 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/)

  3. Call js-sdk signature configuration (wechat.config), which has been mentioned above.

  4. 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

php Chinese website WeChat public account uses the correct posture! Get resources you never thought possible!

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!

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