LSP 用户端API 一 SMS

本文详细介绍了如何在Laravel项目中使用EasySms包实现短信验证码的发送功能,包括配置阿里云短信服务、生成随机验证码、发送短信、缓存验证码以及实现节流处理等关键步骤。

安装 easy-sms

.env

# aliyun sms
ALI_ACCESS_KEY_ID=LTAIOJfkWhaYYtWD
ALI_ACCESS_KEY_SECRET=W6ytWrlgmx4xCDuBN2jbusD1ji3QaJ
ALI_SIGN_NAME=洪荒社
composer require "overtrue/easy-sms"
touch config/easysms.php
<?php
return [
    // HTTP 请求的超时时间(秒)
    'timeout' => 5.0,

    // 默认发送配置
    'default' => [
        // 网关调用策略,默认:顺序调用
        'strategy' => \Overtrue\EasySms\Strategies\OrderStrategy::class,

        // 默认可用的发送网关
        'gateways' => [
            'aliyun',
        ],
    ],
    // 可用的网关配置
    'gateways' => [
        'errorlog' => [
            'file' => '/tmp/easy-sms.log',
        ],
        'aliyun' => [
            'access_key_id' => env('ALI_ACCESS_KEY_ID'),
            'access_key_secret' => env('ALI_ACCESS_KEY_SECRET'),
            'sign_name' => env('ALI_SIGN_NAME'),
        ],
    ],
];
php artisan make:provider EasySmsServiceProvider
public function register()
{
    $this->app->singleton(EasySms::class, function ($app) {
        return new EasySms(config('easysms'));
    });

    $this->app->alias(EasySms::class, 'easysms');
}

config/app.php 在 providers 中增加 App\Providers\EasySmsServiceProvider::class

\App\Providers\EasySmsServiceProvider::class,

tinker测试

php artisan tinker
$sms = app('easysms');
try {
    $sms->send(18665182079, [
        'content'  => '您的验证码为: 6666',
        'template' => 'SMS_105440011',
        'data' => [
            'code' => 6666
        ],
    ]);
} catch (\GuzzleHttp\Exception\ClientException $exception) {
    $response = $exception->getResponse();
    $result = json_decode($response->getBody()->getContents(), true);
    dd($result);
}

路由

routes/api.php

$api = app('Dingo\Api\Routing\Router');

$api->version('v1', [
    'namespace' => 'App\Http\Controllers\Api\V1'
], function($api) {
    // 短信验证码
    $api->post('sms', 'SmsController@store')
        ->name('api.sms.store');
});

请求验证类

php artisan make:request Api/SmsRequest
public function rules()
{
    return [
        'cellphone' => 'required|regex:/^1[3456789]\d{9}$/|unique:users',
        'type' => 'required',
    ];
}

控制器

php artisan make:controller Api/V1/SmsController
  • 生成6位随机码
  • 用 easySms 发送短信到用户手机
  • 发送成功后,生成一个 key,在缓存中存储这个 key 对应的手机以及验证码,10分钟过期
  • 将 key 以及 过期时间 返回给客户端
  • 除了正式环境外,默认不真实发送短信
<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Requests\Api\SmsRequest;
use GuzzleHttp\Exception\ClientException;
use Illuminate\Support\Facades\Cache;
use Overtrue\EasySms\EasySms;

/**
 * 短信服务控制器
 *
 * Class SmsController
 * @package App\Http\Controllers\Api\V1
 */
class SmsController extends Controller
{
    public function store(SmsRequest $request, EasySms $easySms)
    {
        $cellphone = $request->cellphone;

        if(!app()->environment('production')) {
            $code = '666666';
        } else {
            // 生成6位随机数,左侧补0
            $code = str_pad(random_int(1, 999999), 6, 0, STR_PAD_LEFT);

            try {
                $result = $easySms->send($cellphone, [
                    'content'  => '您的验证码为: '. $code,
                    'template' => 'SMS_105440011',
                    'data' => [
                        'code' => $code
                    ],
                ]);
            } catch (ClientException $exception) {
                $response = $exception->getResponse();
                $result = json_decode($response->getBody()->getContents(), true);
                return $this->response->errorInternal($result['msg'] ?? '短信发送异常');
            }
        }

        // 缓存验证码 10分钟过期
        $key = 'verificationCode_'. str_random(15);
        $expiredAt = now()->addMinutes(10);
        Cache::put($key, ['phone' => $cellphone, 'code' => $code], $expiredAt);

        return $this->response->array([
            'key' => $key,
            'expired_at' => $expiredAt->toDateTimeString(),
        ])->setStatusCode(201);
    }
}

节流处理

.env

# api.throttle 中间件
RATE_LIMITS_EXPIRES=1
RATE_LIMITS=60
SIGN_RATE_LIMITS_EXPIRES=1
SIGN_RATE_LIMITS=10

config/api.php

/*
 * 接口频率限制
 */
'rate_limits' => [
    // 访问频率限制,次数/分钟
    'access' => [
        'expires' => env('RATE_LIMITS_EXPIRES', 1),
        'limit'  => env('RATE_LIMITS', 60),
    ],
    // 登录相关,次数/分钟
    'sign' => [
        'expires' => env('SIGN_RATE_LIMITS_EXPIRES', 1),
        'limit'  => env('SIGN_RATE_LIMITS', 10),
    ],
],

routes/api.php

$api = app('Dingo\Api\Routing\Router');

$api->version('v1', [
    'namespace' => 'App\Http\Controllers\Api\V1'
], function($api) {
    // 短信验证码
    $api->post('sms', 'SmsController@store')
        ->name('api.sms.store');
});

转载于:https://my.oschina.net/beanho/blog/2874914

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值