ThinkPHP6 project basic operations (15. Actual combat part of Alibaba Cloud SMS redis)

1. Install Alibaba Cloud SMS SDK

Alibaba Cloud SMS debugging
Alibaba Cloud SMS SDK PHP document
Refer to the official Alibaba Cloud documentation to install Alibaba Cloud SMS SDK:

composer require alibabacloud/sdk

After the installation is complete, Alibaba Cloud's common functions will be generated in the vendor folder, not just the SMS module.
Insert picture description here

Two, package into the project lib

Because the SMS module may also be used in other applications, encapsulate it in the libmiddle, common\libcreate a folder under the sms\AliSmsfolder, and encapsulate the functions of Alibaba Cloud SMS in AliSmsit:
Insert picture description here
first test whether the SMS can be sent in the visual debugging page, and fill in PhoneNumbers to receive the SMS Mobile phone number, SignName is the name of the signature (SMS service-domestic message-signature management), TemplateCode fills in the name of the short message template (SMS service-domestic message-template management):
Insert picture description here
Click 发起调用to check if you have received a short message:
Insert picture description here
after successful sending, it will be on the right The code is pasted into the liblibrary, AliSms.phpand some of the parameters inside are written in the configuration file:

<?php
declare(strict_types=1);
namespace app\common\lib\sms\AliSms;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;

class AliSms
{
    
    
    /**
     * 阿里云发送短信
     * @param string $phone
     * @param int $code
     * @return bool
     * @throws ClientException
     */
    public static function sendCode(string $phone, int $code) : bool {
    
    
        if(empty($phone) || empty($code)){
    
    
            return false;
        }

        AlibabaCloud::accessKeyClient(config("aliyun.access_key_id"), config("aliyun.access_secret"))
            ->regionId(config("aliyun.region_id"))
            ->asDefaultClient();

        $templateParam = [
            "code" => $code
        ];

        try {
    
    
            $result = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                // ->scheme('https') // https | http
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->host(config("aliyun.host"))
                ->options([
                    'query' => [
                        'RegionId' => config("aliyun.region_id"),
                        'PhoneNumbers' => $phone,
                        'SignName' => config("aliyun.sign_name"),
                        'TemplateCode' => config("aliyun.template_code"),
                        'TemplateParam' => json_encode($templateParam),
                    ],
                ])
                ->request();
            print_r($result->toArray());
        } catch (ClientException $e) {
    
    
            return false;
            // echo $e->getErrorMessage() . PHP_EOL;
        } catch (ServerException $e) {
    
    
            return false;
            // echo $e->getErrorMessage() . PHP_EOL;
        }
        return true;
    }
}

BusinessFloor:

<?php

declare(strict_types=1);
namespace app\common\business;
use app\common\lib\sms\AliSms\AliSms;

class Sms
{
    
    
    public static function sendCode(string $phoneNumber) : bool {
    
    

        $code = rand(100000, 999999);
        $sms = AliSms::sendCode($phoneNumber, $code);
        if($sms){
    
    
            // 需要记录redis及失效时间1分钟
        }

        return true;
    }
}

ControllerFloor:

<?php
namespace app\api\controller;
use app\api\validate\User;
use app\BaseController;
use think\exception\ValidateException;
use app\common\business\Sms as SmsBus;

class Sms extends BaseController
{
    
    
    public function code(){
    
    
        $phoneNumber = input("param.phone_number","","trim");
        $data = [
            'phone_number' => $phoneNumber
        ];

        // 已采用自定义异常方法拦截,如果没有采用自定义拦截,需要try...catch
        validate(User::class)->scene("send_code")->check($data);

        /*try {
            validate(User::class)->scene("send_code")->check($data);
        }catch (ValidateException $e){
            return show(config("status.error"), $e->getError());
        }*/

        if(SmsBus::sendCode($phoneNumber)){
    
    
            return show(config("status.success"),"发送验证码成功");
        }
        return show(config("status.error"),"发送验证码失败");
    }
}

Define the routing file:
api.php

<?php

use think\facade\Route;

Route::rule('smscode', 'sms/code','POST');

Define exception method interception reference: ThinkPHP6 project basic operation (13. Custom exception handling summary in actual combat projects, error page & API error)

Three, radis record verification code

1. Install redis service

Download from the official website: https://redis.io/download
Install the redisservice according to your own system , and then turn on the service.
Double-click on the windows and the redis-server.exefollowing interface appears to start the service:
Insert picture description here

Tips: 这个窗口不要关闭哦,否则服务就关掉了!

2. Visual redis management software

Beginners can view the data managed by redis through visualization tools, just like navcatviewing the database.
RDM official website: https://rdm.dev/
(The official website is chargeable, but we Chinese students should know what to do, so I won’t say more...)
Insert picture description here

3. PHP install redis extension

Enter in the console to php -mview the phpinstalled extensions. If you find the redis extension, you don't need to install it.
Enter the php -iview PHP Extension Buildinformation in the console , and then download the corresponding redisextended version.
redis download official website

Zend Extension Build => API320190902,NTS,VC15
PHP Extension Build => API20190902,NTS,VC15

Then put it in the php extension directory: the D:\phpstudy_pro\Extensions\php\php7.4.3nts\extgeneral integrated environment will have this file, and then check the php.iniconfiguration in the file redis:

extension=php_redis.dll

Open the php extension redis:
Insert picture description here

4. Configure cache redis

ThinkPHPThe default is to use the file cache. The interface for sending the verification code is written in the apiapplication, so I copied a cacheconfiguration file to the apiapplication configdirectory and modified the configuration:

<?php

// +----------------------------------------------------------------------
// | 缓存设置
// +----------------------------------------------------------------------

return [
    // 默认缓存驱动
    'default' => env('cache.driver', 'redis'),

    // 缓存连接方式配置
    'stores'  => [
        'file' => [
            // 驱动方式
            'type'       => 'File',
            // 缓存保存目录
            'path'       => '',
            // 缓存前缀
            'prefix'     => '',
            // 缓存有效期 0表示永久缓存
            'expire'     => 0,
            // 缓存标签前缀
            'tag_prefix' => 'tag:',
            // 序列化机制 例如 ['serialize', 'unserialize']
            'serialize'  => [],
        ],
        // 更多的缓存连接
        'redis' => [
            'host' => '127.0.0.1',
            'port' => 6379,
            'type' => 'redis',
        ]
    ],
];

5. Redis saves the SMS verification code and sets the expiration time

  1. Configure redis prefix and expiration time
    <?php
    
    return [
        "code_pre" => "sms_code_pre_", // key 前缀
        "code_expire" => 60, // 失效时间 60 秒
    ];
    
  2. Modify Businesslayer code
    public static function sendCode(string $phoneNumber) : bool {
          
          
        $code = rand(100000, 999999);
        $sms = AliSms::sendCode($phoneNumber, $code);
        if($sms){
          
          
            // 需要记录redis及失效时间1分钟
            cache(config("redis.code_pre").$phoneNumber, $code, config("redis.code_expire"));
        }
    
        return $sms;
    }
    
  3. Re-test the SMS sending interface to see redisif the record is successful.
    Send a POST request with Postman http://tp6.com/api/smscode, and it shows that the sending is successful: the
    Insert picture description here
    mobile phone receives the SMS verification code 403777, refresh the RDM, there is already a record, and the verification code and expiration time are displayed, the time 60decreases from the beginning If it is reduced, 0it will no longer be accessible. Refresh this key and it will disappear.
    Insert picture description here

6. Verify SMS verification code

Here you only need to use cache("key")it to get radisthe value of the record. If it is not found, it is expired. If it is not expired, then judge whether it is equal.

Insert picture description here

Guess you like

Origin blog.csdn.net/zy1281539626/article/details/110913448