LSP 用戶端API 一 SMS 原

安裝 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');
});
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章