ThinkPHP 接入谷歌验证

本文详细介绍了如何在PHP项目中使用GoogleAuthenticator类库生成安全秘钥,创建QR码并验证2FA验证码。包括创建随机秘钥、计算时间戳哈希值以及生成谷歌验证器的二维码链接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、使用github 上的类库(https://github.com/PHPGangsta/GoogleAuthenticator/blob/master/PHPGangsta/GoogleAuthenticator.php

<?php
namespace app\user\controller;
/**
 * PHP Class for handling Google Authenticator 2-factor authentication.
 *
 * @author Michael Kliewe
 * @copyright 2012 Michael Kliewe
 * @license http://www.opensource.org/licenses/bsd-license.php BSD License
 *
 * @link http://www.phpgangsta.de/
 */
class QrcodeController
{
    protected $_codeLength = 6;

    /**
     * Create new secret.
     * 16 characters, randomly chosen from the allowed base32 characters.
     *
     * @param int $secretLength
     *
     * @return string
     */
    public function createSecret($secretLength = 16)
    {
        $validChars = $this->_getBase32LookupTable();

        // Valid secret lengths are 80 to 640 bits
        if ($secretLength < 16 || $secretLength > 128) {
            throw new Exception('Bad secret length');
        }
        $secret = '';
        $rnd = false;
        if (function_exists('random_bytes')) {
            $rnd = random_bytes($secretLength);
        } elseif (function_exists('mcrypt_create_iv')) {
            $rnd = mcrypt_create_iv($secretLength, MCRYPT_DEV_URANDOM);
        } elseif (function_exists('openssl_random_pseudo_bytes')) {
            $rnd = openssl_random_pseudo_bytes($secretLength, $cryptoStrong);
            if (!$cryptoStrong) {
                $rnd = false;
            }
        }
        if ($rnd !== false) {
            for ($i = 0; $i < $secretLength; ++$i) {
                $secret .= $validChars[ord($rnd[$i]) & 31];
            }
        } else {
            throw new Exception('No source of secure random');
        }

        return $secret;
    }

    /**
     * Calculate the code, with given secret and point in time.
     *
     * @param string   $secret
     * @param int|null $timeSlice
     *
     * @return string
     */
    public function getCode($secret, $timeSlice = null)
    {
        if ($timeSlice === null) {
            $timeSlice = floor(time() / 30);
        }

        $secretkey = $this->_base32Decode($secret);

        // Pack time into binary string
        $time = chr(0).chr(0).chr(0).chr(0).pack('N*', $timeSlice);
        // Hash it with users secret key
        $hm = hash_hmac('SHA1', $time, $secretkey, true);
        // Use last nipple of result as index/offset
        $offset = ord(substr($hm, -1)) & 0x0F;
        // grab 4 bytes of the result
        $hashpart = substr($hm, $offset, 4);

        // Unpak binary value
        $value = unpack('N', $hashpart);
        $value = $value[1];
        // Only 32 bits
        $value = $value & 0x7FFFFFFF;

        $modulo = pow(10, $this->_codeLength);

        return str_pad($value % $modulo, $this->_codeLength, '0', STR_PAD_LEFT);
    }

    /**
     * Get QR-Code URL for image, from google charts.
     *
     * @param string $name
     * @param string $secret
     * @param string $title
     * @param array  $params
     *
     * @return string
     */
    public function getQRCodeGoogleUrl($name, $secret, $title = null, $params = array())
    {
        $width = !empty($params['width']) && (int) $params['width'] > 0 ? (int) $params['width'] : 200;
        $height = !empty($params['height']) && (int) $params['height'] > 0 ? (int) $params['height'] : 200;
        $level = !empty($params['level']) && array_search($params['level'], array('L', 'M', 'Q', 'H')) !== false ? $params['level'] : 'M';

        $urlencoded = urlencode('otpauth://totp/'.$name.'?secret='.$secret.'');
        if (isset($title)) {
            $urlencoded .= urlencode('&issuer='.urlencode($title));
        }

        return "https://api.qrserver.com/v1/create-qr-code/?data=$urlencoded&size=${width}x${height}&ecc=$level";
    }

    /**
     * Check if the code is correct. This will accept codes starting from $discrepancy*30sec ago to $discrepancy*30sec from now.
     *
     * @param string   $secret
     * @param string   $code
     * @param int      $discrepancy      This is the allowed time drift in 30 second units (8 means 4 minutes before or after)
     * @param int|null $currentTimeSlice time slice if we want use other that time()
     *
     * @return bool
     */
    public function verifyCode($secret, $code, $discrepancy = 1, $currentTimeSlice = null)
    {
        if ($currentTimeSlice === null) {
            $currentTimeSlice = floor(time() / 30);
        }

        if (strlen($code) != 6) {
            return false;
        }

        for ($i = -$discrepancy; $i <= $discrepancy; ++$i) {
            $calculatedCode = $this->getCode($secret, $currentTimeSlice + $i);
            if ($this->timingSafeEquals($calculatedCode, $code)) {
                return true;
            }
        }

        return false;
    }

    /**
     * Set the code length, should be >=6.
     *
     * @param int $length
     *
     * @return PHPGangsta_GoogleAuthenticator
     */
    public function setCodeLength($length)
    {
        $this->_codeLength = $length;

        return $this;
    }

    /**
     * Helper class to decode base32.
     *
     * @param $secret
     *
     * @return bool|string
     */
    protected function _base32Decode($secret)
    {
        if (empty($secret)) {
            return '';
        }

        $base32chars = $this->_getBase32LookupTable();
        $base32charsFlipped = array_flip($base32chars);

        $paddingCharCount = substr_count($secret, $base32chars[32]);
        $allowedValues = array(6, 4, 3, 1, 0);
        if (!in_array($paddingCharCount, $allowedValues)) {
            return false;
        }
        for ($i = 0; $i < 4; ++$i) {
            if ($paddingCharCount == $allowedValues[$i] &&
                substr($secret, -($allowedValues[$i])) != str_repeat($base32chars[32], $allowedValues[$i])) {
                return false;
            }
        }
        $secret = str_replace('=', '', $secret);
        $secret = str_split($secret);
        $binaryString = '';
        for ($i = 0; $i < count($secret); $i = $i + 8) {
            $x = '';
            if (!in_array($secret[$i], $base32chars)) {
                return false;
            }
            for ($j = 0; $j < 8; ++$j) {
                $x .= str_pad(base_convert(@$base32charsFlipped[@$secret[$i + $j]], 10, 2), 5, '0', STR_PAD_LEFT);
            }
            $eightBits = str_split($x, 8);
            for ($z = 0; $z < count($eightBits); ++$z) {
                $binaryString .= (($y = chr(base_convert($eightBits[$z], 2, 10))) || ord($y) == 48) ? $y : '';
            }
        }

        return $binaryString;
    }

    /**
     * Get array with all 32 characters for decoding from/encoding to base32.
     *
     * @return array
     */
    protected function _getBase32LookupTable()
    {
        return array(
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', //  7
            'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', // 15
            'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', // 23
            'Y', 'Z', '2', '3', '4', '5', '6', '7', // 31
            '=',  // padding char
        );
    }

    /**
     * A timing safe equals comparison
     * more info here: http://blog.ircmaxell.com/2014/11/its-all-about-time.html.
     *
     * @param string $safeString The internal (safe) value to be checked
     * @param string $userString The user submitted (unsafe) value
     *
     * @return bool True if the two strings are identical
     */
    private function timingSafeEquals($safeString, $userString)
    {
        if (function_exists('hash_equals')) {
            return hash_equals($safeString, $userString);
        }
        $safeLen = strlen($safeString);
        $userLen = strlen($userString);

        if ($userLen != $safeLen) {
            return false;
        }

        $result = 0;

        for ($i = 0; $i < $userLen; ++$i) {
            $result |= (ord($safeString[$i]) ^ ord($userString[$i]));
        }

        // They are only identical strings if $result is exactly 0...
        return $result === 0;
    }
}

2、代码中引用

        $ga = new qrcode();

        //秘钥
        $secret = $ga->createSecret();
        
        dump($secret);
        /**
         * 生成二维码地址
         */
        $qrCodeUrl = $ga->getQRCodeGoogleUrl('验证码名称', $secret);
          
        //谷歌验证器扫码绑定此连接显示的二维码            
        dump($qrCodeUrl);

      

3、验证验证码


//验证用户提交的验证码是否正确
//$secret 为上一步生成的秘钥
//$code 为获取的输入验证码
$checkResult = $ga->verifyCode($secret, $code, 1);
 
if ($checkResult) {
    echo 'SUCCESS';
} else {
    echo 'FAILED';
}

转载于:PHP 为项目设置谷歌身份验证器_php 谷歌验证器-CSDN博客

<think>好的,我需要帮助用户解决在ThinkPHP框架中集成DeepSeek大模型服务的问题。首先,我得确认用户的需求,他们想要一个接入教程和示例代码。接下来,我应该考虑ThinkPHP的版本,目前最新的稳定版本是6.x,所以我会基于这个版本进行说明。 首先,用户需要安装HTTP客户端来发送API请求。ThinkPHP通常推荐使用Guzzle,所以安装Guzzle是第一步。然后,用户需要在DeepSeek平台上获取API密钥,这一步需要注册账号并创建应用,获取API Key。 接下来,配置API密钥到ThinkPHP的环境文件中,比如.env,这样可以方便管理敏感信息。然后,创建一个服务类来处理API请求,这个类应该包含构造请求头、发送请求和处理响应的方法。这里需要注意异常处理,确保网络问题或API错误能够被捕获并记录。 在控制器中调用这个服务类,用户需要传递必要的参数,比如模型名称、提示内容和其他参数。返回结果后,控制器处理响应并返回给前端。此外,编写一个路由来映射控制器的入口方法,使得可以通过URL访问该功能。 测试时,用户可以使用Postman或直接访问路由来验证接口是否正常工作。同时,优化建议也很重要,比如使用异步请求、参数校验和缓存机制,这些都能提升性能和安全性。 最后,生成相关问题,帮助用户进一步了解API集成中的其他方面,比如异常处理、性能优化、参数调整和安全性措施。确保每个步骤都清晰,代码示例正确,并且符合ThinkPHP的最佳实践。</think>### ThinkPHP框架集成DeepSeek API教程 #### 一、环境准备 1. 安装ThinkPHP 6.x框架 ```bash composer create-project topthink/think project_name ``` 2. 安装HTTP客户端(推荐Guzzle) ```bash composer require guzzlehttp/guzzle ``` #### 二、配置API密钥 在`.env`文件中添加: ```env DEEPSEEK_API_KEY=your_api_key DEEPSEEK_API_HOST=https://api.deepseek.com/v1 ``` #### 三、创建API服务类 新建`app/service/DeepSeekService.php`: ```php <?php declare(strict_types=1); namespace app\service; use GuzzleHttp\Client; use GuzzleHttp\Exception\GuzzleException; class DeepSeekService { private string $apiKey; private string $apiHost; public function __construct() { $this->apiKey = env('deepseek.api_key'); $this->apiHost = env('deepseek.api_host'); } public function createCompletion(array $params): array { $client = new Client([ 'base_uri' => $this->apiHost, 'timeout' => 30.0, ]); try { $response = $client->post('/chat/completions', [ 'headers' => $this->buildHeaders(), 'json' => $params ]); return json_decode($response->getBody()->getContents(), true); } catch (GuzzleException $e) { // 记录日志 \think\facade\Log::error('API请求异常:'.$e->getMessage()); return ['error' => $e->getMessage()]; } } private function buildHeaders(): array { return [ 'Content-Type' => 'application/json', 'Authorization' => 'Bearer '.$this->apiKey, 'Accept' => 'application/json' ]; } } ``` #### 四、控制器调用示例 创建`app/controller/AiController.php`: ```php <?php declare(strict_types=1); namespace app\controller; use app\service\DeepSeekService; use think\Response; class AiController { public function chat(): Response { $service = new DeepSeekService(); $params = [ 'model' => 'deepseek-chat', 'messages' => [ ['role' => 'user', 'content' => request()->param('prompt')] ], 'temperature' => 0.7, 'max_tokens' => 1000 ]; $response = $service->createCompletion($params); if (isset($response['error'])) { return json(['code' => 500, 'message' => $response['error']]); } return json([ 'code' => 200, 'data' => $response['choices'][0]['message']['content'] ]); } } ``` #### 五、路由配置 修改`route/app.php`: ```php use think\facade\Route; Route::post('ai/chat', 'AiController/chat'); ``` #### 六、测试接口 使用Postman发送POST请求: ```http POST /ai/chat Content-Type: application/json { "prompt": "请解释量子计算的基本原理" } ``` #### 七、最佳实践建议 1. **异步处理**:耗时请求建议使用消息队列 ```php // 安装think-queue composer require topthink/think-queue ``` 2. **参数校验**:添加中间件验证请求参数 ```php // 创建验证php think make:validate AiValidate ``` 3. **缓存机制**:对常见问题结果进行缓存 ```php use think\facade\Cache; $response = Cache::remember("ai_response_{$hash}", function() use ($service, $params) { return $service->createCompletion($params); }, 3600); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值