一、前言
最近在开发过程中积累了一些踩坑经验,希望能对类似的开发者提供一些参考方法。
网上有太多的文章都写到了相关教程,我的并不是最全面的,但直接上干货,合适的直接提走就行。
二、问题描述
相信开发到这一步的攻城狮们Vue页面也基本写得差不多了,想要接着开发整个需求第一步就是实现用户的登录功能,上半篇先写微信小程序官方的登录样式,下半篇使用第三方服务来管理小程序用户的文章(我写使用Authing组件的登录),这一篇就相当于基础知识了。
官方文档的登录方法其实就是一个调用微信小程序官方接口的功能,一句话概括就是:
引导用户点击授权获取用户信息,实现一进入微信小程序就弹出授权窗口
以下是实现的功能截图:
三、解决思路
1、先附上官方文档的解释
PS:查阅官方文档是很有必要的。微信小程序官方文档链接如下:
看完官方文档还不理解的接着往下看
2、原理简单解释一下
微信小程序登录流程时序图是这样的:
大白话解释就是:
(1)、准备工作得有
1、你,在开发人员名单内
2、在HBuilder X开发工具里,项目的manifest.json中先配置好APPID
配置APPID步骤:点击项目目录里的manifest.json→微信小程序配置→微信小程序APPID
(2)、使用流程
(背后不可见的原理,也可以用来解释console.log出来的code):
四、实现代码
1、概述:
使用 button 组件,并将 open-type 指定为 getPhoneNumber 类型,以获取用户手机号码。
注意:不管是getUserInfo还是getPhoneNumber都只能通过 button 去触发!!!
2、先跑以下代码
跑一下代码是为了让你更好理解上边我画的图,以便你最终能完全理解最后的代码
<template>
<view class="login">
<button class="wxq-btn loginWx" open-type="getUserInfo" @getuserinfo="getUserInfo">一键登录</button>
<button class="wxq-btn goback">取消登录</button>
<button open-type=""></button>
</view>
</template>
<script>
import {
// mapState,
mapMutations
} from 'vuex';
export default{
// computed: {
// ...mapState(['userInfo'])
// },
data(){
return{
code:'',//微信临时登录凭证
}
},
onLoad:function(){
uni.login({
success: (res) => {
if (res.errMsg == "login:ok") {
this.code = res.code;
} else {
uni.showToast({
title: '系统异常,请联系管理员!'
})
}
}
})
},
methods:{
...mapMutations(['login']),
//微信授权登录
getUserInfo(e){
let that = this;
var p = this.getSetting();
p.then(function(isAuth) {
console.log('是否已经授权', isAuth);
if (isAuth) {
console.log('用户信息,加密数据', e);
//eData 包括//微信头像//微信名称 还有加密的数据.
let eData = JSON.parse(e.detail.rawData);
//接下来就是访问接口.
uni.request({
header: {
'content-type': 'application/x-www-form-urlencoded'
},
url: '', //你的接口地址
method: 'POST',//接口类型
data: '', //接口需要的数据
success: function(res) {
console.log(res);
if (res.data.Success) {
that.login(res.data); //将接口返回的数据保存在全局变量中.
//登录成功跳转首页或者你想跳转的地方...
//注意:如果时导航页 请用uni.switchTab
// 其他页面建议使用uni.reLaunch
} else {
uni.showToast({
title: '授权登录失败!',
mask: true,
icon: 'none'
})
}
}
})
} else {
uni.showToast({
title: '授权失败,请确认授权已开启',
mask: true,
icon: 'none'
})
}
});
},
//获取用户的当前设置
getSetting() {
return new Promise(function(resolve, reject) {
uni.getSetting({
success: function(res) {
if (res.authSetting['scope.userInfo']) {
console.log('存在');
resolve(true);
} else {
console.log('不存在');
resolve(false);
}
}
})
}).catch((e) => {
console.log(e)
});;
},
},
}
</script>
<style>
.login{
width: 750rpx;
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.goback{
width: 90%;
background:#eee;
color: #333;
margin-bottom: 24rpx;
}
.loginWx{
width: 90%;
background: #04BE02;
margin-bottom: 24rpx;
}
</style>
3、如何实现跟我开头截图一样的代码
1、authing的使用
先打开
2、完成authing的下载后,正确配置(全网首个教程)
项目根目录下创建一个common文件夹,里边创建一个authing.js文件
authing.js代码为:
import { Authing } from "@authing/miniapp-uniapp";
// 以下两种密码加密方式可以按需使用,选其一即可
// rsa 加密
import { encryptFunction } from "@authing/miniapp-jsencrypt";
export const authing = new Authing({
appId: "6*************6c",//你的APPID
// 公有云部署:Authing 控制台 -> 选择已创建的小程序应用 -> 应用配置 -> -> 认证配置 -> 认证地址
// 私有化部署:填写你的私有服务地址
host: "https://***********.cn",
// 用户池 ID
userPoolId: "6*************8",
platform: 'wx',
// 非必传,密码默认将以明文传输
encryptFunction
});
以上是截图 ,完成后到下一步
3、代码里import authing:
<script>
import {
authing
} from '@/common/authing.js'
</script>
4、完整代码
<template>
<view class="content">
<image class="logo" src="../../static/logo.png"></image>
<text class="title">****系统</text>
<text class="text-area">**** **** ****</text>
<view class="sqcontainer">
<button open-type="getPhoneNumber" @getphonenumber="loginByPhone" class="login-button"
hover-class="check-login-button">
<image src='../../static/icon.png' class="wechat-icon" mode="aspectFill"></image>
微信授权一键登录
</button>
</view>
</view>
</template>
<script>
import {
authing
} from '@/common/authing.js'
export default {
methods: {
/**
* 需要在真机上测试,微信开发者工具不会返回 code
* @param {*} e
*/
async loginByPhone(e) {
const {
code,
iv,
encryptedData
} = e.detail;
try {
const res = await authing.loginByPhone({
extIdpConnidentifier: '**-*****',//注意这里不是APPID,是识别码,是一小串字符串
miniProgramCodeAndPhonePayload: {
phoneParams: {
encryptedData,
iv,
},
wxPhoneInfo: {
code
}
},
options: {
scope: 'openid profile offline_access'
}
});
console.log('wxPhoneInfo code',code);
console.log('authing.loginByPhone res: ', res);
const phone = e.detail.phoneNumber; // 获取被授权的手机号
console.log('手机号已更新为: ', phone);
wx.switchTab({
url: '/pages/***/***' // 直接转首页
});
// 检查用户信息
} catch (err) {
console.error('登录失败: ', err);
}
}
}
}
</script>
<style>
.content {
height: 100vh;
background-color: #ffffff;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.logo {
position: relative;
height: 400rpx;
width: 400rpx;
top: -20vh;
margin-left: auto;
margin-right: auto;
margin-bottom: 50rpx;
}
.title {
position: relative;
top: -300rpx;
font-size: 46rpx;
color: #000000;
font-weight: bold;
margin-bottom: 50rpx;
}
.text-area {
position: relative;
top: -300rpx;
font-size: 40rpx;
color: #000000;
}
.sqcontainer {
justify-content: center;
align-items: center;
}
.login-button {
position: relative;
top: -150rpx;
display: flex;
align-items: center;
background-color: #00ba0c;
/* 按钮背景色 */
color: #fff;
/* 按钮文字颜色 */
padding: 5px 80px;
/* 按钮内边距 */
border-radius: 5px;
/* 按钮圆角 */
border: none;
/* 去掉边框 */
cursor: pointer;
/* 鼠标悬停时显示为可点击 */
}
.check-login-button {
background-color: #00ff00;
}
.wechat-icon {
width: 30px;
/* 微信图标宽度 */
height: 30px;
/* 微信图标高度 */
margin-right: 10px;
/* 文字和图标之间的间距 */
}
</style>
五、结束语
在实际开发过程中,认真查阅文档是第一步,要是遇到文档不详细或者教程不理解的情况,则需要我们综合自身需要进行选择性的参考。
以上方式在每次做开发都会给客户说明并让其选择,目前主流方式就是通过微信的手机号直接一键注册到小程序的用户管理信息中,authing会帮我们创建好用户,通过wx手机号的话不仅能够识别出用户注册方式(wx or 其他)、自动填充用户手机号码。
最后以上内容如果有大佬能留言指教一二,不胜感激!