Laravel 公众号网页调用腾讯云行驶证识别功能
这两天为公司做一个微信公众号网页调用腾讯云 “行驶证识别” 的功能,在此写一下过程,一是为了加深自己的理解,同时希望能给有需要的朋友做下借鉴,少走一些弯路。
准备工作#
1、需要腾讯云账号,开通 “文字识别” 功能,这个就不细说了。
2、需要注册公众号(要验证),如果没有验证的话,也可以采用测试号,测试号入口点此》》
依赖环境#
1、PHP 5.6.33 版本及以上。
2、获取安全凭证。安全凭证包含 SecretId 及 SecretKey 两部分。SecretId 用于标识 API 调用者的身份,SecretKey 用于加密签名字符串和服务器端验证签名字符串的密钥。前往 API 密钥管理 页面,即可进行获取
安装 PHP SDK 3.0#
composer require tencentcloud/tencentcloud-sdk-php
后端代码#
use TencentCloud\Common\Credential;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Ocr\V20181119\OcrClient;
use TencentCloud\Ocr\V20181119\Models\VehicleLicenseOCRRequest;
class PicRecognitionController extends Controller
{
public function xsz(Request $request)
{
$ImageBase64 = $request->ImageBase64;
try {
$cred = new Credential(env('TENANCY_SECRETID'), env('TENANCY_SECRETKEY'));
$httpProfile = new HttpProfile();
$httpProfile->setEndpoint("ocr.tencentcloudapi.com");
$clientProfile = new ClientProfile();
$clientProfile->setHttpProfile($httpProfile);
$client = new OcrClient($cred, "ap-guangzhou", $clientProfile);
$req = new VehicleLicenseOCRRequest();
// 可以通过图片URL 或者 图片Base64 进行识别,我选择了 Base64 的方式
$params = array(
"ImageBase64" => $ImageBase64
);
$req->fromJsonString(json_encode($params));
$resp = $client->VehicleLicenseOCR($req);
// 识别出的信息都在 FrontInfo
$data = isset($resp->FrontInfo) ? $resp->FrontInfo : [];
return response()->json($data);
}
catch(TencentCloudSDKException $e) {
echo $e;
}
}
}
这个代码比较简单,直接调用就可以,涉及到业务逻辑的自行处理就可以
前端代码#
遇到问题#
报的是签名错误,这个是换成正式号遇到的问题。测试号测试都通过了,但是上传到服务器后改成正式号就报错。最后输出错误提示:是因为服务器 IP 没有加入白名单。具体设置:开发 -> 基本配置:白名单
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: