騰訊雲 圖形驗證碼接入

php_yt發表於2020-10-16

新建圖形驗證應用

首先進入控制檯 console.cloud.tencent.com/captcha

騰訊雲 圖形驗證碼接入

「新建驗證」後,可獲得 APPIDApp Secret Key

開發文件

騰訊雲 圖形驗證碼接入

雲 API 金鑰

騰訊雲 圖形驗證碼接入
新建金鑰

騰訊雲 圖形驗證碼接入

前端接入

略過
騰訊雲 圖形驗證碼接入

伺服器接入

騰訊雲 圖形驗證碼接入

騰訊雲 圖形驗證碼接入

騰訊雲 圖形驗證碼接入

  1. 點選右上方 PHP SDK 使用說明 ,下載 sdk
  2. 填入引數除錯,複製自動生成的程式碼。

實踐

比如我將 sdk 下載到了 laravel/sdk 目錄

騰訊雲 圖形驗證碼接入

DEMO

<?php
namespace App\Library\Other;
require_once '../sdk/cvm/vendor/autoload.php';
use TencentCloud\Common\Credential;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Captcha\V20190722\CaptchaClient;
use TencentCloud\Captcha\V20190722\Models\DescribeCaptchaResultRequest;
use Illuminate\Support\Facades\Log;
class TCaptcha {
    private $tencent_secret_id;
    private $tencent_secret_key;
    private $captcha_appid;
    private $captcha_key;
    public function __construct()
    {
        $this->tencent_secret_id = env('TSECRET_ID');
        $this->tencent_secret_key = env('TSECRET_KEY');
        $this->captcha_appid = env('CAPCHA_APPID');
        $this->captcha_key = env('CAPCHA_KEY');
    }

    public function captchaResult($ticket, $randstr)
    {
        try {
            $cred = new Credential($this->tencent_secret_id, $this->tencent_secret_key);
            $httpProfile = new HttpProfile();
            $httpProfile->setEndpoint("captcha.tencentcloudapi.com");

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

            $req = new DescribeCaptchaResultRequest();

            $params = array(
                "CaptchaType" => 9,
                "Ticket" => $ticket,
                "UserIp" => get_client_ip(), 
                "BusinessId" => 1, 
                "SceneId" => 1,
                "Randstr" => $randstr,
                "CaptchaAppId" => intval($this->captcha_appid),
                "AppSecretKey" => $this->captcha_key, 
                // "NeedGetCaptchaTime" => 1
            );
            $req->fromJsonString(json_encode($params));

            $resp = $client->DescribeCaptchaResult($req);    //{"CaptchaCode":1,"CaptchaMsg":"OK","EvilLevel":0,"GetCaptchaTime":0,"RequestId":"bb271767-159f-4d86-bd35-56f6812116b8"}

            $resp_json = $resp->toJsonString();
            $resp_array = json_decode($resp_json, true);

            if($resp_array['CaptchaCode'] == 1){
                return true;
            }else{
                Log::error($resp_json);
                return false;
            }

        }
        catch(TencentCloudSDKException $e) {
            Log::error($e);
            return false;
        }
    }
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結
focus

相關文章