This article briefly introduces the operation of uni-App to do wechat login on the app side, and gives a practical example

  1. How to conduct wechat authorized login?
  2. How do I log in without exposing AppSecret in my code

Uni-app’s wechat authorized login is implemented in h5+ mode. The front-end code does not need to display the key, and the login is completed by the background. The front-end only checks the service provider, obtains relevant information and transfers it to the back-end to complete the login process

start

Follow the following steps to apply for an account, create a new APP, open login permission, and obtain an APPID

1. Account registration guidelines

open.weixin.qq.com/

2. Create an application (details are omitted)

Enter the wechat public to create an application, and save the appID and key after passing

3. Configuration (the following are the key codes and operations)

As shown below, simply fill in the appID,Private information, such as keys, is not required in the application

Due to the security upgrade of Apple’S iOS 13 system, wechat SDK1.8.6 requires the support of Universal Links to jump, so as to verify the validity and improve security.

Ios general link configuration guide ask.dcloud.net.cn/article/364…

4. Analyze APP wechat authorized login

  1. Obtaining an authorized service provider The following operations are used to detect the service provider and return the wechat authorized object
// Get the service
getServices() {
    let weixinService = null; // Available login authorization services
    // #ifdef APP-PLUS
    return new Promise((resolve, reject) = > {
        plus.oauth.getServices((services) = > {
            if (services && services.length) {
                // Iterate through the array of authorization services
                for (let i = 0, len = services.length; i < len; i++) {
                    if (services[i].id === 'weixin') {
                        weixinService = services[i]; // wechat authorized object
                        break; }}if(! weixinService) {this.showToast('No wechat login authorization service')
                    reject()
                }
                resolve(weixinService)
            } else {
                this.showToast('Currently unavailable Login Authorization Service')
                reject()
            }
        },(error) = > {
            this.showToast('Authorization failed')
            reject()
        })
    })
    // #endif
},
Copy the code
  1. Access code
// APP gets the code
doLogin() {
    // #ifdef APP-PLUS
    if (this.isLogin) return
    this.isLogin = true
    // Returns the wechat authorization object
    this.getServices().then(weixinService= > {
        weixinService.authorize((event) = > {  // Get the key to code here
            this.loginApi(event.code) // Invoke background login
        }, (error) = > {
            this.showToast('Authorization failed')
            this.isLogin = false}, {scope:'snsapi_userinfo'.state:'authorize'.appid: this.appId
        });
    }).catch(err= > {
        this.isLogin = false
    })
    // #endif
},
Copy the code
  1. The background login
loginApi(code) {
    uni.showLoading({
            title: "Logging in..."
    })
    uni.request({
        url: 'Background request address'.data: {
            code: code,
            appid: this.appId,
        },
        success: res= > {
            this.isLogin = false
            uni.hideLoading();
            // Return failure status according to background
            if(res && res.data.code ! = =0) {
                this.showToast('Login failed')
                return;
            }
            // The login succeeded
            this.success(res.data.data)
        },
        fail: (err) = > {
            this.isLogin = false
            console.log('Login failed error', err)
        }
    })
}
Copy the code

Complete example (functional, code run error to solve their own)

<template> <view style="padding-top: 1px;" > <! -- #ifdef APP-PLUS --> <view v-if="isCanUse"> <view> <view class="header"><image :src="avatarUrl"></image></view> <view Class ="content"> <view> Apply for the following permissions </view> <text> to get your public information (nickname, </text> </view> <button class=" @click="doLogin"> </button> </view> <! -- #endif --> </view> </template> <script> const appId = 'create app appId '; Export default {data() {return {appId: appId, avatarUrl: null, isCanUse: true, isLogin: False, // Login status to prevent repeated click}; }, methods: {getServices() {let weixinService = null; // #ifdef app-plus return new Promise((resolve, Reject) => {plus.oauth.getServices((services) => {if (services &&services.length) { len = services.length; i < len; i++) { if (services[i].id === 'weixin') { weixinService = services[i]; // wechat authorization object break; } } if (! {this. ShowToast (' no weixinService ') {this. ShowToast (' no weixinService ') {this. Reject ()}},(error) => {this.showtoast (' reject ')}}) // #endif}, showToast(message) {uni. 'none', title: message || '' }) }, #ifdef app-plus if (this.islogin) return this.islogin = true This.getservices ().then(weixinService => {weixinService.authorize((event) => {this.loginAPI (event.code)) }, (error) => {this.isLogin = false},{scope:'snsapi_userinfo', state:'authorize', appid: this.appId }); }). Catch (err => {this.isLogin = false}) // #endif}, success(data) {uni. '/pages/index/index' }); }, loginApi(code) {uni.showloading ({title: "logging in... }) uni. Request ({url: 'background ', data: {code: code, appid: this. appid,}, success: res => { this.isLogin = false uni.hideLoading(); If (res && res.data.code! == 0) {this.showToast(' login failed ') return; This.success (res.data.data)}, fail: (err) => {this.isLogin = false console.log(' login failed error', err)}})}}; </script> <style> .header { margin: 90rpx 0 90rpx 50rpx; border-bottom: 1px solid #ccc; text-align: center; width: 650rpx; height: 300rpx; line-height: 450rpx; } .header image { width: 200rpx; height: 200rpx; } .content { margin-left: 50rpx; margin-bottom: 90rpx; } .content text { display: block; color: #9d9d9d; margin-top: 40rpx; } .bottom { border-radius: 80rpx; margin: 70rpx 50rpx; font-size: 35rpx; } </style>Copy the code

If the operation is not successful, you can comment below