TP6 腾讯云发送短信验证码配置详解

一、发送注册验证码代码实现

参考腾讯云文档
https://cloud.tencent.com/document/product/382/56058

1.通过composer安装

	composer require tencentcloud/tencentcloud-sdk-php

2.TP6框架相关代码
2.1添加相关接口方法

use app\common\controller\SmsController; // todo 这个引用千万别忘记

public function sendCode(){

        $phone = request()->post('phone');
        if (!isMobile($phone)){	//检测手机号方法 自己去写吧
            return SendError("手机号码不正常");
        }
        $sms = new SmsController($this->app);
        $sms->sendcode($phone);
        if ($sms->getError()){
            return SendError($sms->getError());
        }
        return SendSuccess("发送成功");
    }

2.2 在app/common文件夹下新建smscontroler类

/**
 * 发送验证码类
 */
namespace app\common\controller;

use TencentCloud\Sms\V20190711\SmsClient;
// 导入要请求接口对应的 Request 类
use TencentCloud\Sms\V20190711\Models\SendSmsRequest;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Common\Credential;
// 导入可选配置类
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;

class SmsController extends BaseController{

    protected $SecretId;  // 腾讯云账户秘密ID,注意不是短信中的id
    protected $SecretKey; // 腾讯云账户中的秘钥key
    protected $AppID;     // 腾讯云短信应用appid。应用管理 > 应用列表中的应用id
    protected $smsSign;   // 模板签名内容。一定是要 国内短信 > 签名管理 > 中的签名内容
    protected $templateId;// 正文模板中的模板id。   国内短信 > 正文模板管理 > 模板ID
    public $error ='';
    private $expire_time = 600;      //失效时间
    private $wait_time = 120;      //发送间隔秒数

    public function initialize()
    {
        parent::initialize(); // TODO: 相关配置放到了.env文件内
        $this->SecretId = env('SMS.sid', '');
        $this->SecretKey = env('SMS.skey', '');
        $this->AppID = env('SMS.appid', '');
        $this->smsSign = env('SMS.sign', '');
        $this->templateId = "493349";
    }

    /**
     * 发送验证码
     * @param string $phone 手机号码
     * @param int $t_type 模板类型 1 注册 2登录 3 忘记密码
     */
    public function sendcode($phone='',$t_type=1){
        $phone ="+86".$phone;

        //设置请求模板
        switch ($t_type){
            case 2:
                $this->templateId = "493349";	// 这个可随意改
                break;
            default:
                $this->templateId = "493349";	//默认注册模板id
        }
        // 随机验证码
        $TemplateParamSet = $this->setVcode($phone);
        if ($this->error){
            return  false;
        }

        try {
            // 实例化认证对象
            $cred = new Credential($this->SecretId, $this->SecretKey);
            $httpProfile = new HttpProfile();
            $httpProfile->setEndpoint("sms.tencentcloudapi.com");

            // 实例化一个 http 选项
            $clientProfile = new ClientProfile();
            $clientProfile->setHttpProfile($httpProfile);

            // 实例化一个 client 选项
            $client = new SmsClient($cred, "", $clientProfile);

            // 实例化一个 sms 发送短信请求对象,每个接口都会对应一个 request 对象。
            $req = new SendSmsRequest();
            // 发送短信验证码配置参数
            $params = '{"PhoneNumberSet":["'.$phone.'"],"TemplateID":"'.$this->templateId.'",
            "Sign":"'.$this->smsSign.'","TemplateParamSet":["'.$TemplateParamSet.'"],"SmsSdkAppid":"'.$this->AppID.'"}';

            $req->fromJsonString($params);

            // 通过 client 对象调用 SendSms 方法发起请求
            $resp = $client->SendSms($req);
            if ($resp->SendStatusSet[0]->Code !='Ok'){
                $this->error ='发送失败';
                return false;
            }
            return true;
        }
        catch(TencentCloudSDKException $e) {
            echo $e;
        }
    }

    /**
     * 生成验证码
     * @param $account
     */
    public function setVcode($account){

        $key = get_vcode_key($account);
        $vcodeData = cache($key);
        if (is_array($vcodeData) && !empty($vcodeData['when_send'])){
            if( time() - $vcodeData['when_send'] < $this->wait_time ){
                $this->error = '操作过于频繁,请稍后重试';
                return false;
            }
        }else{
            $vcodeData = array();
            $vcode = rand(100000,999999);
            $vcodeData['mobile'] = $account;
            $vcodeData['vcode'] = $vcode;
            $vcodeData['when_send'] = time();
            cache($key,$vcodeData,$this->expire_time);
            return $vcode;
        }
    }

    /**
     * 校验验证码
     * @param $account
     * @param $vcode
     * @author: liuhui
     * @Date: 2021/7/13 14:59
     */
    public function checkVcode($account, $vcode){
        $key = get_vcode_key($account);
        $vcodeData = cache($key);
        if ($vcodeData) {
            if($vcodeData['mobile']==$account && $vcodeData['vcode']==$vcode){
                if(time()-$vcodeData['when_send'] > $this->expire_time){
                    $this->error = '验证码已过期';
                    //删除过期缓存
                    cache($key,NULL);
                    return false;
                }else{
                    return true;
                }
            }else{
                $this->error = '验证码不正确';
                return false;
            }
        }else{
            $this->error = '验证失败';
            return false;
        }
    }

    public function getError(){
        return $this->error;
    }
}

补充 代码中用到的自定义方法

if (!function_exists("get_vcode_key")){
    /**
     * 生成缓存key
     * @param string $account
     * @return \think\response\Json
     * @author: liuhui
     * @Date: 2021/7/13 14:47
     */
    function get_vcode_key($account='')
    {
        return md5($account);
    }
}

二、错误解决

安装SDK之后,如果您的 PHP 环境证书有问题,可能会遇到报错,类似于
cURL error 60: See http://curl.haxx.se/libcurl/c/libcurl-errors.html,
请尝试按以下步骤解决:

1.到 https://curl.haxx.se/ca/cacert.pem 下载证书文件cacert.pem。
 将 cacert.pem文件复制到php安装目录中,如下,我的路经
E:\phpstudy_pro\Extensions\php\php7.4.3nts\extras\ssl\cacert.pem
2.编辑php.ini文件。
删除curl.cainfo配置项前的分号注释符(;)

配置curl.cainfo绝对路经,如下

curl.cainfo =E:\phpstudy_pro\Extensions\php\php7.4.3nts\extras\ssl\cacert.pem
3.重启依赖 PHP 的服务。
评论 15
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

懒惰的胖猪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值