当前位置:网站首页>Use abp Zero builds a third-party login module (4): wechat applet development
Use abp Zero builds a third-party login module (4): wechat applet development
2022-07-24 12:22:00 【Lin Xiao LX】
Briefly review the process of wechat applet :
- The user enters the authentication page of the applet by scanning the code , Update status to ACCESSED Scanned code
- The user clicks confirm Authorization , Wechat through wx.login() Interface to obtain the necessary information of the third party login :Code Login credentials .
Wechat applet mainly provides interactive functions for user authorization , The user scans the code , Provide an interaction UI, as follows :

stay 《 Use Abp.Zero Build a third-party login module ( Two ): Server development 》 The interface that the server has built is introduced in , This time we will call Access and Authenticate, Call respectively to complete the update of scanned code and authorized status .
Project structures,
use first vue-cli Create a web project , Name it mp-weixin
vue create -p dcloudio/uni-preset-vue mp-weixinstay Pages Create login/index.vue page , As the login authorization page
The directory structure is as follows :

pages.json:
{
"pages": [ //pages The first item in the array represents the application startup page , Reference resources :https://uniapp.dcloud.io/collocation/pages
{
"path": "pages/index/index",
"style": {
"navigationBarTitleText": "uni-app"
}
},
{
"path": "pages/login/index",
"style": {
"navigationBarTitleText": " Authorization page "
}
}
],
"globalStyle": {
"navigationBarTextStyle": "black",
"navigationBarTitleText": "uni-app",
"navigationBarBackgroundColor": "#F8F8F8",
"backgroundColor": "#F8F8F8"
}
}
login New under the directory ajaxRequire.ts, establish request object , This object will utilize uni-axios-ts Library send ajax request
import axios from 'uni-axios-ts'
// Send network request
export const request = async (url: string, methods, data: any, onProgress?: (e) => void, cancelToken?) => {
let token = null
let timeout = 3000;
if (cancelToken) {
token = cancelToken.token
timeout = 0;
}
const service = axios.create()
service.interceptors.request.use(
(config) => {
config.header['Content-Type'] = "application/json"
return config
},
(error) => {
Promise.reject(error)
}
)
const re = await service.request({
headers: { 'Content-Type': 'multipart/form-data' },
url: url,
method: methods,
data: data,
cancelToken: token,
timeout: timeout,
onUploadProgress: function (progressEvent) { // The event that gets the upload progress
if (progressEvent.lengthComputable) {
if (onProgress) {
onProgress(progressEvent);
}
}
},
})
return re as any;
}
/// Get cancellation token
export const getCancelToken = () => {
const source = axios.CancelToken.source();
return source;
}
index.vue Created in loginExternalForms As a parameter transfer object
export default {
data() {
return {
loginExternalForms: {
WeChat: {
token: "",
providerAccessCode: "",
},
}
};
}
}onLoad Function ,option Stored in the scanning applet code scene Parameters , take scene The parameter is assigned to token Variable
onLoad(option) {
this.loginExternalForms.WeChat.token = option.scene;
this.start();
},start In, we call Access Interface , Change status to ACCESSED( Scanned code ) , If the return is successful , Then prompt the user to click confirm authorization , If the returned result is abnormal "WechatMiniProgramLoginInvalidToken" when , Indicates that the applet code has expired at this time , You need to update the applet code on the webpage .
async start() {
var currentForms = this.loginExternalForms["WeChat"];
this.loading = true;
await request(`${this.prefix}/MiniProgram/Access`, "post", currentForms)
.then((re) => {
this.successMessage(" You have scanned the QR code , Please click confirm login to complete ");
})
.catch((c) => {
var err = c.response?.data?.error?.message;
if (err != null) {
if (err == "WechatMiniProgramLoginInvalidToken") {
this.isInvalid = true;
} else {
this.errorMessage(c.err);
}
}
})
.finally(() => {
setTimeout(() => {
this.loading = false;
}, 1.5 * 1000);
});
},Prefix Is your service address prefix
prefix: "https://localhost:44311/api/services/app"stay Html in , We create authorized login and Cancel buttons , Only when the isInvalid by true You can click authorize
<button
@click="handleWxLogin"
:disabled="isInvalid || loading"
class="sub-btn"
>
Authorized login
</button>
<button @click="cancelWxLogin" :disabled="loading" class="sub-btn">
Cancel
</button>establish handleExternalLogin It is used to process the logic after the user clicks the authorization to log in , call Authenticate Interface , Update status to AUTHORIZED( Authorized ) You need to call before that uni.login Get applet login credentials code.
of uni.login function , Please refer to the official documentation uni.login(OBJECT) | uni-app Official website (dcloud.io)
uniapp Support a variety of applets , In order to retain certain expansion capability ,handleExternalLogin We keep parameters in the function authProvider, Wechat applet login has been implemented handleWxLogin Pass parameters when a function is called "WeChat",
async handleExternalLogin(authProvider) {
var currentForms = this.loginExternalForms[authProvider];
this.loading = true;
await request(
`${this.prefix}/MiniProgram/Authenticate`,
"post",
currentForms
)
.then((re) => {
uni.redirectTo({
url: "/pages/index/index",
});
})
.catch((c) => {
var err = c.response?.data?.error?.message;
if (err != null) {
if (err == "WechatMiniProgramLoginInvalidToken") {
this.isInvalid = true;
} else {
this.errorMessage(c.err);
}
}
setTimeout(() => {
this.loading = false;
}, 1.5 * 1000);
});
},
async handleWxLogin() {
const that = this;
uni.login({
provider: "weixin",
success: (loginRes) => {
that.loginExternalForms.WeChat.providerAccessCode = loginRes.code;
that.handleExternalLogin("WeChat");
},
});
},Create the unregister function
cancelWxLogin() {
uni.redirectTo({
url: "/pages/index/index",
});
},Execute the success notification function
successMessage(value = " Successful implementation ") {
uni.showToast({
title: value,
icon: "success",
duration: 1.5 * 1000,
});
},Next, simply write an interface ,
The interface will clearly reflect isInvalid And loading Corresponding to UI Interaction :
normal

Applet code is out of date

Overall test
Simulator test
When I open the page , Save image as

In wechat applet debugging tool ,“ Through two-dimensional code compilation ”

Wait for the mobile interface to display the authorization page and click “ Authorized login ”:

GetCurrentUser The interface returns the correct data , And displayed on web On the page

So far, the development of the applet side has been completed
Project address
jevonsflash/abp-mp-auth (github.com)
Conclusion
Applet login has certain scalability , Although wechat applet login is introduced throughout , But login authentication is an abstract function of applet ,uniapp Integrated with various platforms ( WeChat 、 Alipay 、 Baidu 、 Bytedance applet ) Login interface , adopt uni.login You can get the code
边栏推荐
- Chapter 1 Introduction
- Day5: construct program logic
- L1-043 reading room
- Anaconda environment migration
- STM32 - Fundamentals of C language
- Leetcode-81. search rotation sort array II (binary search returns true/false)
- A* and JPS
- Design of digital oscilloscope based on arm and FPGA -- QMJ
- Agile? DevOps ?
- 泰山OFFICE技术讲座:段落边框的布局难点
猜你喜欢

容错、熔断的使用与扩展

NFT digital collection system construction - app development

One of his birds sold for 60million -- the collection of eight mountain people in the Ming and Qing Dynasties

Equal principal increasing repayment / equal principal decreasing mortgage repayment calculator

【功能测试】项目的测试——登录和发布文章功能

Convergence rules for 4 * 4 image weights

基于ARM和FPGA的数字示波器设计——QMJ

Basic usage of GCC
![[function test] test of the project - login and post function](/img/64/c9bbf34964622f4f013b1184eeb1e0.jpg)
[function test] test of the project - login and post function

In kuborad graphical interface, operate kubernetes cluster to realize master-slave replication in MySQL
随机推荐
[function test] test of the project - login and post function
QT notes - realize form adaptation
[rust] Why do I suggest you learn rust | a preliminary study of rust
如何在IM系统中实现抢红包功能?
Counter attack dark horse: devdbops training, give you the best courses!
L2-011 play with binary tree
【功能测试】项目的测试——登录和发布文章功能
Top and bottom of stack
在kuborad图形化界面中,操作Kubernetes 集群,实现mysql中的主从复制
Buckle exercise - 32 divided into k equal subsets
Three small knowledge points about data product managers
Markdown mathematical formula syntax
leetcode-81. 搜索旋转排序数组 II(二分查找返回true/false)
[I also want to brush through leetcode] 468. Verify the IP address
STM32 - Fundamentals of C language
第0章 前言和环境配置
for mysql
MySQL advanced (XVII) cannot connect to database server problem analysis
L1-059 敲笨钟
【网络空间安全数学基础第9章】有限域