编程 PHP中集成腾讯云人脸识别服务,并将结果写入数据库

2024-11-18 23:24:17 +0800 CST views 604

本文展示了如何在PHP中集成腾讯云人脸识别服务,并将结果写入数据库。通过调用腾讯云的API,获取人脸识别Token,处理返回结果,并更新用户信息到本地数据库。文章还包括错误处理和数据库操作的最佳实践,确保身份验证的安全性和有效性。

<?php

require "./vendor/autoload.php";

use TencentCloud\Common\Credential;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Faceid\V20180301\FaceidClient;
use TencentCloud\Faceid\V20180301\Models\DetectAuthRequest;
use TencentCloud\Faceid\V20180301\Models\GetDetectInfoEnhancedRequest;

// 获取配置项
function C($name){
    $config = [ 
        "TX_ID"  => "AKIDNbdZKEyXxBByd7OSM3WourPo11Cdt4A",
        "TX_KEY" => "5KWcebP2a4QegcP1XyOgqwu3JPTN6gO3"
    ];
    return $config[$name] ?? null;
}

// 获取人脸识别结果
function getResult($BizToken = "") {
    if (empty($BizToken)) {
        return [
            'ErrCode' => -1,
            'ErrMsg'  => 'BizToken 参数无效',
        ];
    }

    $params = [
        'Action'   => 'GetDetectInfoEnhanced',
        'Version'  => '2018-03-01',
        'BizToken' => $BizToken,
        'RuleId'   => '1',
    ];

    try {
        $cred = new Credential(C("TX_ID"), C("TX_KEY"));
        $httpProfile = new HttpProfile();
        $httpProfile->setEndpoint("faceid.tencentcloudapi.com");

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

        $req = new GetDetectInfoEnhancedRequest();
        $req->fromJsonString(json_encode($params));

        $resp = $client->GetDetectInfoEnhanced($req);
        $result = json_decode($resp->toJsonString(), true);

        return $result['Text'] ?? [
            'ErrCode' => -1,
            'ErrMsg'  => '未能获取有效值',
        ];

    } catch (TencentCloudSDKException $e) {
        return [
            'ErrCode' => -1,
            'ErrMsg'  => $e->getMessage(),
        ];
    }
}

// 处理数据库更新逻辑
function updateMemberInfo($id, $real_name, $idc) {
    $db = include("./Application/Common/Conf/db.php");

    $mysqli = new mysqli("127.0.0.1", $db["DB_USER"], $db["DB_PWD"], $db["DB_NAME"], 3306);
    
    if ($mysqli->connect_error) {
        die("数据库连接失败: " . $mysqli->connect_error);
    }

    $sql = "UPDATE dt_member SET real_name = ?, idc = ? WHERE id = ?";
    
    $stmt = $mysqli->prepare($sql);
    if ($stmt === false) {
        die("SQL 语句准备失败: " . $mysqli->error);
    }

    $stmt->bind_param("ssi", $real_name, $idc, $id);
    if ($stmt->execute()) {
        echo "更新成功!";
        header('Location: /index.php/Home/Member/info.html');
    } else {
        echo "更新失败: " . $stmt->error;
    }

    $stmt->close();
    $mysqli->close();
}

// 执行人脸认证结果处理
$bizToken = $_GET["BizToken"] ?? null;
$result = getResult($bizToken);

if ($result["ErrCode"] == 0) {
    $id = $_GET["Extra"];
    $real_name = $result["Name"];
    $idc = $result["OcrIdCard"];

    updateMemberInfo($id, $real_name, $idc);
} else {
    exit("人脸认证失败: " . $result["ErrMsg"]);
}


// 获取腾讯云人脸认证 Token
function getToken($IdCard = '', $Name = "", $notify = "", $uid = 0) {
    if (empty($IdCard) || empty($Name) || empty($uid)) {
        exit("参数错误");
    }

    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https://" : "http://";
    $url = $protocol . $_SERVER['HTTP_HOST'] . "/idc2.php";

    $params = [
        'Action'      => 'DetectAuth',
        'Version'     => '2018-03-01',
        'RuleId'      => "1",
        'IdCard'      => $IdCard,
        'Name'        => $Name,
        'RedirectUrl' => $url,
        'Extra'       => $notify,
    ];

    try {
        $cred = new Credential(C("TX_ID"), C("TX_KEY"));
        $httpProfile = new HttpProfile();
        $httpProfile->setEndpoint("faceid.tencentcloudapi.com");

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

        $req = new DetectAuthRequest();
        $req->fromJsonString(json_encode($params));

        $resp = $client->DetectAuth($req);
        return json_decode($resp->toJsonString(), true);

    } catch (TencentCloudSDKException $e) {
        return [
            'ErrCode' => -1,
            'ErrMsg'  => $e->getMessage(),
        ];
    }
}

// 获取 UID 并发起认证
$uid = $_GET["uid"] ?? null;
if ($uid) {
    $data = ['idc' => 'your_idc_value', 'real_name' => 'your_real_name'];
    $res = getToken($data['idc'], $data['real_name'], $uid);

    if (isset($res["Url"])) {
        header('Location: ' . $res["Url"]);
    } else {
        var_dump($res);
    }
} else {
    exit("UID 参数无效");
}

优化要点:

  1. 减少重复代码:移除了重复的 requireuse 语句,组织结构更简洁。
  2. 错误处理改进:通过检查参数和返回结果,优化了错误处理,确保每次出错时有明确的提示。
  3. 数据库操作改进:增加了数据库操作的错误处理机制,确保数据库连接和 SQL 操作的安全性和可读性。
  4. 变量安全性:使用了三元运算符或 isset 来确保获取参数时的安全性。

文章:PHP 集成腾讯云人脸识别与数据库操作的实现

在现代 Web 应用开发中,身份验证的需求逐渐从传统的密码验证转向更先进的生物识别技术,比如人脸识别。本文将展示如何在 PHP 中集成腾讯云人脸识别服务,并将结果写入数据库。这个过程包括与腾讯云 API 的交互、处理返回数据,并将身份验证结果存储到本地数据库中。

步骤 1:准备环境

首先,确保你已经安装了 PHP 和 Composer,并通过 Composer 安装了腾讯云的 SDK。运行以下命令:

composer require tencentcloud/tencentcloud-sdk-php

接下来,确保你已经在腾讯云中开通了相关的 API 服务,并获得了相应的 TX_IDTX_KEY

步骤 2:集成腾讯云人脸识别

在 PHP 中,我们需要通过腾讯云的 SDK 与 API 交互。这里展示了如何生成人脸识别 Token 并发起认证:

function getToken($IdCard = '', $Name = "", $notify = "", $uid = 0) {
    if (empty($IdCard) || empty($Name) || empty($uid)) {
        exit("参数错误");
    }

    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https://" : "http://";
    $url = $protocol . $_SERVER['HTTP_HOST'] . "/idc2.php";

    $params = [
        'Action'      => 'DetectAuth',
        'Version'     => '2018-03-01',
        'RuleId'      => "1",
        'IdCard'      => $IdCard,
        'Name'        => $Name,
        'RedirectUrl' => $url,
        'Extra'       => $notify,
    ];

    try {
        $cred = new Credential(C("TX_ID"), C("TX_KEY"));
        $httpProfile = new HttpProfile();
        $httpProfile->setEndpoint("faceid.tencentcloudapi.com");

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

        $req = new DetectAuthRequest();
        $req->fromJsonString(json_encode($params));

        $resp = $client->DetectAuth($req);
        return json_decode($resp->toJsonString(), true);

    } catch (TencentCloudSDKException $e) {
        return [
            'ErrCode' => -1,
            'ErrMsg'  => $e->getMessage(),
        ];
    }
}

通过上面的代码,我们可以生成 BizToken,并将用户重定向到腾讯云的验证页面。

步骤 3:处理验证结果

在用户完成验证后,腾讯云将返回结果。我们需要解析返回数据并存储到数据库中:

function getResult($BizToken = "") {
    if (empty($BizToken)) {
        return [
            'ErrCode' => -1,
            'ErrMsg'  => 'BizToken 参数无效',
        ];
    }

    $params = [
        'Action'   => 'GetDetectInfoEnhanced',
        'Version'  => '2018-03-01',
        'BizToken' => $BizToken,
        'RuleId'   => '1',
    ];

    try {
        $cred = new Credential(C("TX_ID"), C("TX_KEY"));
        $httpProfile = new HttpProfile();
        $httpProfile->setEndpoint("faceid.tencentcloudapi.com");

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

        $req = new GetDetectInfoEnhancedRequest();
        $req->fromJsonString(json_encode($params));

        $resp = $client->GetDetectInfoEnhanced($req);
        $result = json_decode($resp->toJsonString(), true);

        return $result['Text'] ?? [
            'ErrCode' => -1,
            'ErrMsg'  => '未能获取有效值',
        ];

    } catch (TencentCloudSDKException $e) {
        return [
            'ErrCode' => -1,
            'ErrMsg'  => $e->getMessage(),
        ];
    }
}

步骤 4:更新数据库

我们将识别到的身份信息(如真实姓名和身份证号)存储到本地数据库中:

function updateMemberInfo($id, $real_name, $idc) {
    $db = include("./Application/Common/Conf/db.php");

    $mysqli = new mysqli("127.0.0.1", $db["DB_USER"], $db["DB_PWD"], $db["DB_NAME"], 3306);
    
    if ($mysqli->connect_error) {
        die("数据库连接失败: " . $mysqli->connect_error);
    }

    $sql = "UPDATE dt_member SET real_name = ?, idc = ? WHERE id = ?";
    
    $stmt = $mysqli->prepare($sql);
    if ($stmt === false) {
        die("SQL 语句准备失败: " . $mysqli->error);
    }

    $stmt->bind_param("ssi", $real_name, $idc, $id);
    if ($stmt->execute()) {
        echo "更新成功!";
        header('Location: /index.php/Home/Member/info.html');
    } else {
        echo "更新失败: " . $stmt->error;
    }

    $stmt->close();
    $mysqli->close();
}

结论

通过使用腾讯云的 SDK 与 PHP 结合,我们可以实现简单的人脸识别与身份验证流程,确保用户的身份信息在验证后能够被安全地写入数据库。这种集成方式不仅可以提升应用的安全性,还能大大简化用户的认证流程。

这种方法可以广泛应用于登录验证、身份核实等场景,为企业和开发者提供更先进的身份管理工具。
images

推荐文章

Vue3中的v-for指令有什么新特性?
2024-11-18 12:34:09 +0800 CST
在 Rust 生产项目中存储数据
2024-11-19 02:35:11 +0800 CST
如何实现生产环境代码加密
2024-11-18 14:19:35 +0800 CST
Flet 构建跨平台应用的 Python 框架
2025-03-21 08:40:53 +0800 CST
一个简单的打字机效果的实现
2024-11-19 04:47:27 +0800 CST
php微信文章推广管理系统
2024-11-19 00:50:36 +0800 CST
Golang 几种使用 Channel 的错误姿势
2024-11-19 01:42:18 +0800 CST
liunx服务器监控workerman进程守护
2024-11-18 13:28:44 +0800 CST
Vue3中的v-bind指令有什么新特性?
2024-11-18 14:58:47 +0800 CST
Web浏览器的定时器问题思考
2024-11-18 22:19:55 +0800 CST
Golang 中你应该知道的 noCopy 策略
2024-11-19 05:40:53 +0800 CST
JavaScript 策略模式
2024-11-19 07:34:29 +0800 CST
程序员出海搞钱工具库
2024-11-18 22:16:19 +0800 CST
Vue3中如何扩展VNode?
2024-11-17 19:33:18 +0800 CST
windon安装beego框架记录
2024-11-19 09:55:33 +0800 CST
PHP 唯一卡号生成
2024-11-18 21:24:12 +0800 CST
一个有趣的进度条
2024-11-19 09:56:04 +0800 CST
html一个全屏背景视频
2024-11-18 00:48:20 +0800 CST
程序员茄子在线接单