Laravel中使用阿里云短信服务发送验证码

作者: 温新

分类: 【Laravel】

阅读: 2949

时间: 2021-02-21 08:46:10

Laravel版本大于6.x可以使用,不过在Laravel8.x中需要将protected $namespace = 'App\\Http\\Controllers';注释打开。Laravel版本小于6未进行测试。

关于购买短信资源的步骤省略,下面直接进行测试。在测试之前需要说明的是,要使用短信服务就必须申请模板,审核通过之后才可以进行正常的短信业务。

第一步:引入官方SDK

composer require alibabacloud/sdk

官方文档:

第二步:创建短信配置文件

文件位置:config/sms.php

// config/sms.php

<?php
/**
 * 短信相关配置
 */
return [
    // 阿里云秘钥ID
    'access_key_id'     =>  '',
    // 阿里云秘钥secret
    'access_secret'     =>  '',
    // 短信模板签名
    'sign_name'         =>  '',
    // 短信模板代码
    'template_code'     =>  ''
];

第三步:创建路由与控制器

路由

// 发送短信界面
Route::get('reg','RegisterController@reg');
// 获取短信
Route::post('get_code','RegisterController@getMobileCode');

控制器

php artisan make:controller RegisterController

控制器方法

// 获取短信界面
public function reg()
{
 	return view('reg.reg');
}

// 获取短信
public function getMobileCode(Request $request)
{
}

视图

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">>
    <title>Document</title>
</head>
<body>
    <form method="post" action="{{url('/get_code')}}">
        @csrf
        <input type="text" name="mobile" value="">
        <input type="submit" value="获取验证码">
    </form>
</body>
</html>

第四步:使用短信SDK发送短信

为了方便,我将发送短信的代码写到RegisterController中,实际开发业务中最好分离出来。

<?php

namespace App\Http\Controllers;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use Illuminate\Http\Request;

class RegisterController extends Controller
{
    // 获取短信界面
    public function reg()
    {
        return view('reg.reg');
    }

    // 获取短信
    public function getMobileCode(Request $request)
    {
        $mobile   = $request->get('mobile');
        $authCode = json_encode(['code'=>mt_rand(100000,999999)]);
        $successCode = $this->sendMobileCode($mobile, $authCode);
        // 验证码发送成功后进行相关业务操作,
        // 如在这里将验证码写入数据
    }

    public function sendMobileCode($mobile, $authCode)
    {
        AlibabaCloud::accessKeyClient(config('sms.access_key_id'),config('sms.access_secret'))->regionId('cn-hangzhou')->asDefaultClient();
        try {
            $result = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->host('dysmsapi.aliyuncs.com')
                ->options([
                    'query' => [
                        'RegionId' => "cn-hangzhou",
                        'PhoneNumbers' => $mobile,
                        'SignName' => config('sms.sign_name'),
                        'TemplateCode' => config('sms.template_code'),
                        'TemplateParam' => $authCode,
                    ],
                ])
                ->request();
            // 成功发送后的结果集
            //print_r($result->toArray());
            // 短信发送成功可以这里进行相关业务逻辑处理
            if ($result['Code'] == 'OK') {
                return true;
            } else {
                return false;
            }
        } catch (ClientException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        } catch (ServerException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        }
    }
}

到这里短信发送就完成了。

附带$result->toArray()返回值

Array ( [RequestId] => 8D3EA330-56B7-458A-9B9B-5F96A407316A [Message] => OK [BizId] => 601516013896268408^0 [Code] => OK )

2021-02-21

请登录后再评论