Uni-app wechat official account H5 shares trampling pits

In the recent project, I used uni-app to write the development of an H5 wechat official account, in which THERE was an experience of stomping on the function of sharing details of activities. When solving the problem, I also encountered some difficulties. Without further ado, I need to write the code.

I have front-end communication group: the group of sister, big guy, interested in private chat I enter the group

The first part is sharing, and the second part is the authorization process for wechat public account to jump to webpage

Let’s start with a waveOfficial wechat document

One: Our first step is to bind the domain name, which can be bound on the wechat public development platform

Two: the introduction of JS files, I am in the project directly into the file

var jweixin = require('jweixin-module')
Copy the code

3. Verify the permission injection of config. Directly access the background interface to obtain the corresponding parameters and write them in

compomentDidmount() {
    let url = `${location.origin}${location.pathname}${location.search}`;
    
    return this.$http.request({
        url: `/h5/mobile/WXShare`,
        method: 'post',
        data: {
            url: url
        }
    }).then(res => {
        if (res.code === 200) {
            jweixin.config({
                debug: false, appId: res.data.appId, timestamp: res.data.timestamp, nonceStr: res.data.nonceStr, signature: res.data.signature, jsApiList: res.data.jsApiList }); }})},Copy the code
The url that you’re sending to the background is usually just location.href, but we ran into some problems, and we’ll talk about that in a second, but let’s move on to the flow.

Iv. The verification of the ready processing is successful. Here is the jsApiList that I need to configure directly returned from the background, so there is no need to fill in manually.

let url =
    `${location.origin}${location.pathname}#/pages/look_activity/look_activity? activity_id=${this.activity_id}&invite_id=${invite_id}&spreader_id=${spreader_id}`;
let data = {
    title: ' '// Share caption desc:' '// Share description link: url, // Share link. The domain name or path of the link must be the same as the security domain name of the current page. ImgUrl:' '// Share icon success:function() {// the user clicked the share callback function}}; Jweixin. UpdateAppMessageShareData (data) / / share to friends jweixin. UpdateTimelineShareData (data)Copy the code
Note: the path here must be the same as the configuration of the public number, of course, I here is the path to share out later to take parameters, so the path behind? You don’t have to be consistent. Only the key code is posted here.

There’s a problem here

${location.origin}${location.pathname}# /// If I write it directly in the top urllet url = ${location.href}// Then I found the problem and added it before the path of the original code${location.origin}${location.pathname}?# /// At this point my share will work properlyCopy the code

Just yesterday, when users directly accessed the home page to share, the previous problem appeared. At that time, I took the mobile phone to test it was normal, I thought it was the problem of the customer’s iPhone, and then I started to find the problem, and finally I found the problem with the help of my colleague.

The rules for generating signatures are as follows: fields in a signature include noncestr (random string), valid jsapi_ticket, timestamp (timestamp), and url (url of the current web page, not included# and the rest)
Copy the code

The URL of the current page does not contain the # or the following part

// This is why I have to add? So I decided to change the url rules as soon as I entered the APP, so that sharing could work anywhere. The first thought was to change the URL when I entered app.vueif (location.href.indexOf('? ') == -1) {
	location.href = '? ' + location.hash
	return} This method, if the editor is running correctly, will fail to change the machine, so when entering the shared page, directly changelet url = `${location.origin}${location.pathname}${location.search}`;
Copy the code

Here it can be used normally, and when sharing wechat will have its own parameters, which need to be analyzed. I did not use this requirement in my project, so I did not deal with it, but I will give you the method to post it.

EncodeURLComponent (window. The location. Href) done!Copy the code

Authorized login process of wechat official website

At that time in writing this part of the time, should be the first time to write not too familiar so take a lot of detours, now to send out the code, just as a review of the code.

No more words, first on the document ha ha haWechat web page authorization document

The documentation is very clear, just follow the documentation step by step
1 Step 1: The user agrees to authorize and obtain code 2 Step 2: Exchange for web page authorization access_token 3 Step 3: refresh the access_token (if necessary) 4 Step 4: Pull user information (scope is snSAPi_userinfo) 5 Attach: Verify that the access_token is validCopy the code

Without more words to code!!


Store->user.js Vuex

State: {// user code value code:' 'UserInfo: {}, // return to backUrl:' 'Mutations :{// obtain code (state) {state.code =' '// The url to jump tolet url = `${location.origin}${location.pathname}?#/pages/login/login`;// This is done according to the official documentlet local= encodeURIComponent(url) // This part of the document requirementslet params = '&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';
        let loginUrl = `${baseConfig.baseUrl}? appid=${baseConfig.APPID}&redirect_uri=${local}${params}`;
    
        uni.setStorageSync('backUrl', location.hash); window.location.href = loginUrl; // Jump! }}, actions: {// Check whether the user token is valid checkToken(context) {// Get user information api.getUserInfo(). Then (res => {if (res.code == 200) {
                this.userInfo = res.data;
                uni.setStorageSync('userInfo', res.data);
            } else {
                context.commit('getCode'); }}); }, // check whether the user is logged in checkAuth(context, path) {let token = uni.getStorageSync('userToken');
        if(! token && path ! = ='pages/login/login') {// Token does not exist'getCode');
        } else {
            if(path ! = ='pages/login/login') {// Token exists to verify token validity context.dispatch('checkToken'); }}}},Copy the code

This is what vuex needs to do, so below, we make a login transition page to transition, without further ado, programmers communicate with code

login.vue

<template>
	<view class="wrap">
		<image class="loading" src="http://pjserver.huasukeji.net/uploads/loading.gif"></image> <text> Logging in Please wait... </text> <view> If no jump for a long time, <text class="doLogin" @click="goIndex"</view> </view> </template> methods:{getParam(path, name) {var reg = new RegExp();"(^ | \ \? | &)" + name + "=([^&]*)(\\s|&|$)"."i");
        if (reg.test(path))
        return unescape(RegExp.$2.replace(/\+/g, ""));
        return "";
    },
    
    init() {
        let code = this.getParam(location.href, 'code') // Get the code returned after successful authorizationif(code) {// This. DoLogin (code); }},doLogin(code) {
        let params = {
            code: code
        }
        this.$api.login(params).then(res => {
            if (res.code && res.code === 200) {
                uni.setStorageSync('userToken', res.data.token);
                history.replaceState({}, null, `${location.origin}${location.pathname}`);
                let backUrl = uni.getStorageSync('backUrl');
                if (backUrl) {
                    backUrl = backUrl.replace(The '#'.' ')}else {
                    backUrl = '/';
                }
                this.$api.getUserInfo().then(res => {
                    if (res.code == 200) {
                        this.userInfo = res.data
                        uni.setStorageSync('userInfo', res.data)
    
                        uni.reLaunch({
                            url: backUrl
                        })
                    } else {
                        uni.showToast({
                            icon: 'none',
                            title: res.msg
                        })
                    }
                })
    
            } else {
                uni.showToast({
                    icon: 'none',
                    title: 'Login failed'})})}, // The user is concerned about the login page for a long time, so the route is redirectedgoIndex() {
        history.replaceState({}, null, `${location.origin}${location.pathname}`);
        uni.reLaunch({
            url: '/pages/index/index'}); }, // intercept codegetUrlCode() {
        var url = location.search
        this.winUrl = url
        var theRequest = new Object()
        if (url.indexOf("?") != -1) {
            var str = url.substr(1)
            var strs = str.split("&")
            for (var i = 0; i < strs.length; i++) {
                theRequest[strs[i].split("=")[0]] = (strs[i].split("=") [1])}}returnTheRequest}, // can be used directly}Copy the code

ReplaceState () changes the current history entry rather than creating a new one, so no matter how many times the user clicks on a different child page on the current page, it will return to the https:// fixed page when clicking back.

Should be taken into account when sharing out certainly can not let the user login success after the jump to the home page, so do the demand is the user comes in directly judge whether there is login, no login click login or remain unchanged on this page!!

Finally, call the method in app.vue

onLaunch: function(e) {
    this.$store.dispatch('checkAuth', e.path);
},

Copy the code

That’s it!

Two of my backstage colleagues helped me a lot on this project

I just share some experience from stranger to pit in the project, to provide a reference for those who have never done this. If you can, please give me a thumbs up. I am tired of writing the article, so I work overtime during the day and share it at night.

If you have any questions or shortcomings, please leave a message and let me know. Thank you!