近期华为AppGallary Connect的认证服务SDK新增了支持微信小程序的功能。今天就来教大家如何在微信小程序中集成认证服务的手机号码认证方式
1、安装微信小程序环境
首先进入微信小程序官网根据自己需要下载微信开发者工具
https://developers.weixin.qq.com/miniprogram/dev/devtools/download.html
2、在AGC页面开通认证服务
具体创建与配置骤可以参考认证服务官方文档:https://developer.huawei.com/consumer/cn/doc/development/AppGallery-connect-Guides/agc-auth-android-getstarted-0000001053053922
3、创建微信小程序工程
点击“+”号添加新的工程
输入项目信息即可,这里我们不需要用到微信的云服务,所以选择不使用云服务
4、集成认证服务SDK
输入指令将认证服务sdk下载到项目中
当界面出现 run 'npm fund' for details,输入以下命令
npm install @agconnect/auth
5、添加配置文件
在应用启动的时候添加agconnect.instance().configInstance(),将配置文件的json代码块加入到入参中。
下面就进入功能接入步骤了:
5.1 获取验证码
function getPhoneVerifyCode(account: string, sendInterval = 30) {
return agconnect.auth.PhoneAuthProvider.requestVerifyCode('86', account, agconnect.auth.Action.ACTION_REGISTER_LOGIN, 'zh_CN', sendInterval,)
.then((res: any) => {
console.log('getPhoneVerifyCode res:', res);
return Promise.resolve(res);
}).catch((err: any) => {
console.log('getPhoneVerifyCode err:', err);
return Promise.reject(err);
});
}
5.2 注册新用户
function createPhoneUser(account: string, password: string, verifyCode: string) {
return agconnect.auth().createPhoneUser(new agconnect.auth.PhoneUser('86', account, password, verifyCode))
.then((res: any) => {
console.log('createPhoneUser res:', res);
return Promise.resolve(res);
}).catch((err: any) => {
console.log('createPhoneUser err:', err);
return Promise.reject(err);
});
}
5.3 登录
function loginWithPhone(account: string, password: string, verifyCode?: string) {
let credential;
if (verifyCode) {
credential = agconnect.auth.PhoneAuthProvider.credentialWithVerifyCode('86', account, password, verifyCode);
} else {
credential = agconnect.auth.PhoneAuthProvider.credentialWithPassword('86', account, password);
}
if (!credential) {
return Promise.reject('credential is undefined');
}
return agconnect
.auth()
.signIn(credential)
.then((res: any) => {
console.log('login res:', res);
return Promise.resolve(res);
})
.catch((err: any) => {
console.log('login err:', err);
return Promise.reject(err);
});
}
以上我们就成功接入了微信小程序版本认证服务中的手机账号认证。如果觉得简单那就赶快行动起来试试吧。
{{o.name}}
{{m.name}}