一、功能分析
功能概述
- 检查设备是否支持面容/指纹识别
- 检查用户是否已录入相关生物特征
- 显示可用的识别方式(如"指纹识别"、"面容识别")
- 点击后调起系统级生物识别弹窗
需要用到的Uniapp的Api
uni.checkIsSupportSoterAuthentication()
:检测支持的认证方式uni.checkIsSoterEnrolledInDevice()
:检查是否已录入生物特征uni.startSoterAuthentication()
:启动生物识别
二、完整代码
html
<template>
<view class="content">
<view class="title-box">生物识别demo</view>
<view class="mode-box">
<block v-for="(item,index) in authMode.mode" :key="index">
<view class="mode" @click="startAuth(item)">{{item.text}}</view>
</block>
</view>
</view>
</template>
<script setup lang="ts">
import { onShow } from "@dcloudio/uni-app";
import { ref } from "vue";
interface ModeInfo {
mode : 'fingerPrint' | 'facial' | string;
text : string;
support : boolean;
}
onShow(()=>{
checkAuthModeSupport();
});
/**
* 检查设备支持的生物识别方式
*/
let authMode = ref({
mode: [] as Array<ModeInfo>,
support: false
})
const modeDes = {
'facial': '面容识别',
'fingerPrint': '指纹识别'
}
async function checkAuthModeSupport() {
let authModeRes = await uni.checkIsSupportSoterAuthentication();
if(authModeRes.supportMode) {
authModeRes.supportMode.forEach( async (mode) => {
let creatureInfo = await uni.checkIsSoterEnrolledInDevice({
checkAuthMode: mode
});
authMode.value.mode.push({
mode,
text: modeDes[mode],
support: creatureInfo.isEnrolled
});
});
}else {
authMode.value.support = false;
console.log('该设备不支持生物识别认证!')
}
}
/**
* 启动生物识别认证
* @param modeInfo 选择的认证方式
*/
async function startAuth(modeInfo : ModeInfo) {
let authRes = await uni.startSoterAuthentication({
requestAuthModes: [modeInfo.mode] as any,
challenge: '实际项目中 challenge 应为动态生成的唯一标识(如订单ID)',
// 挑战因子为调用者为此次生物鉴权准备的用于签名的字符串关键识别信息,场景为请求用户对某订单进行授权确认,则可以将订单号填入此参数。
authContent: `请进行${modeInfo.text}`,
});
if(authRes.errCode == 0) {
console.log('识别成功');
// TODO: 处理业务逻辑(如登录、支付确认等)
}else {
/*
其它错误码说明
90001 本设备不支持生物认证
90002 用户未授权使用该生物认证接口
90003 请求使用的生物认证方式不支持
90004 未传入challenge或challenge长度过长(最长512字符)
90005 auth_content长度超过限制(最长42个字符)
90007 内部错误
90008 用户取消授权
90009 识别失败
90010 重试次数过多被冻结
90011 用户未录入所选识别方式
*/
}
}
</script>
<style scoped lang="scss">
.content {
padding: 20px 0;
.mode-box {
display: flex;
align-items: center;
justify-content: center;
gap: 16px;
.mode {
opacity: 0.9;
font-size: 12px;
font-weight: bolder;
}
}
.title-box {
display: flex;
font-size: 14px;
font-weight: bolder;
margin: 22px auto;
justify-content: center;
}
}
</style>
三、运行测试
