[vue3+webman+微信小程序]利用第三方接口实现人脸登录

2022-06-06 23:09 6196 次阅读 PHP成长
使用的接口首先需要创建人员库并且创建人员信息并且上传人脸,这个也有相关接口,创建的人和自己应用的用户表相互关联就行了。
![](https://skapi-1253927675.cos.ap-guangzhou.myqcloud.com/blog/202206/7c3b7a31a46ec5311690d4137ea327f4.png)
我这里目前是登录pc端后台,但是电脑没有摄像头,所以是利用小程序,大概逻辑就是首先选择人脸登录的时候,后台创建一个没有状态的登录记录,把这个登录记录的唯一标识请求微信后台生成带参数的小程序码
```php
$url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$wx_token;
$params = [
'scene' => $order_number,
'check_path'=>false,
'page' => 'pages/facelogin/index',
'width' => 300,
'env_version'=>'trial'
];
$rst = curlPost($url,json_encode($params));
```
微信小程序获取小程序码文档地址在这[https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.getUnlimited.html](https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.getUnlimited.html "https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.getUnlimited.html")
这个结果返回的是小程序码的文件信息,需要自行保存或者直接输出给前端。用微信扫码后,会携带这个登录记录的参数到小程序,然后小程序那边接收这个参数
```javascript
Page({
onLoad (query) {
// scene 需要使用 decodeURIComponent 才能获取到生成二维码时传入的 scene
const scene = decodeURIComponent(query.scene)
}
})
```
然后还需要微信小程序的调取摄像头组件[https://developers.weixin.qq.com/miniprogram/dev/component/camera.html](https://developers.weixin.qq.com/miniprogram/dev/component/camera.html "https://developers.weixin.qq.com/miniprogram/dev/component/camera.html")
```
<!-- camera.wxml -->
<camera device-position="back" flash="off" binderror="error" style="width: 100%; height: 300px;"></camera>
<button type="primary" bindtap="takePhoto">拍照</button>
<view>预览</view>
<image mode="widthFix" src="{{src}}"></image>
```
```
// camera.js
Page({
takePhoto() {
const ctx = wx.createCameraContext()
ctx.takePhoto({
quality: 'high',
success: (res) => {
this.setData({
src: res.tempImagePath
})
}
})
},
error(e) {
console.log(e.detail)
}
})
```
这里我是拍照成功后上传照片至服务器,然后服务器那边调用腾讯云的人脸搜索接口sdk
````
<?php
require_once 'vendor/autoload.php';
use TencentCloud\Common\Credential;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Iai\V20200303\IaiClient;
use TencentCloud\Iai\V20200303\Models\SearchFacesRequest;
try {

$cred = new Credential("SecretId", "SecretKey");
$httpProfile = new HttpProfile();
$httpProfile->setEndpoint("iai.tencentcloudapi.com");

$clientProfile = new ClientProfile();
$clientProfile->setHttpProfile($httpProfile);
$client = new IaiClient($cred, "", $clientProfile);

$req = new SearchFacesRequest();

$params = array(
"GroupIds" => array( "face_login" ),
"Image" => "图片base64编码",
"MaxPersonNum" => 1
);
$req->fromJsonString(json_encode($params));

$resp = $client->SearchFaces($req);

print_r($resp->toJsonString());
}
catch(TencentCloudSDKException $e) {
echo $e;
}
```
成功识别后修改登录记录的状态为成功并且写入token缓存,登录页面轮询记录的时候把token写入到前端缓存里。然后九成功登录进去了。