Laravel 公眾號網頁呼叫騰訊雲行駛證識別功能

夜遊人發表於2021-01-15

這兩天為公司做一個微信公眾號網頁呼叫騰訊雲“行駛證識別”的功能,在此寫一下過程,一是為了加深自己的理解,同時希望能給有需要的朋友做下借鑑,少走一些彎路。

準備工作

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;
        }
    }
}

這個程式碼比較簡單,直接呼叫就可以,涉及到業務邏輯的自行處理就可以

前端程式碼

遇到問題

Laravel 公眾號網頁呼叫騰訊雲駕駛證識別功能
報的是簽名錯誤,這個是換成正式號遇到的問題。測試號測試都通過了,但是上傳到伺服器後改成正式號就報錯。最後輸出錯誤提示:是因為伺服器 IP 沒有加入白名單。具體設定:開發 -> 基本配置:白名單

Laravel 公眾號網頁呼叫騰訊雲駕駛證識別功能

本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章