Laravel 发送腾讯云SMS短信

安装easy-sms

$ composer require "overtrue/easy-sms"

新建一个配置文件config/easysms.php

<?php
/**
 * Created by PhpStorm.
 * User: Pasa吴
 * Date: 2019/4/1
 * Time: 18:16
 */
return [
    // HTTP 请求的超时时间(秒)
    'timeout'  => 5.0,

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

        // 默认可用的发送网关
        'gateways' => [
            'qcloud',
        ],
    ],
    // 可用的网关配置
    'gateways' => [
        'errorlog' => [
            'file' => __DIR__ . '/../storage/logs/easy-sms.log',
        ],
        'qcloud'   => [
            'sdk_app_id' => 'xx', // SDK APP ID
            'app_key'    => 'xx', // APP KEY
            'sign_name'  => '可以不填写', // 对应的是短信签名中的内容(非id)
        ],
    ],
];

在控制器或者逻辑层发送短信

<?php
/**
 * Created by PhpStorm.
 * User: Pasa吴
 * Date: 2019/3/30
 * Time: 15:58
 */

namespace App\Common\Logic;

use Overtrue\EasySms\EasySms;
use Illuminate\Support\Facades\Cache;


class Sms extends LogicBase
{
    /**
     * 发送短信
     * @param $mobile   手机号码
     * @param $code     验证码
     * @return array
     */
    public function sms($mobile, $code)
    {
        $config = config('easysms');
        $easySms = new EasySms($config);

        //判断60秒内是否发送过
        $_code = Cache::get($mobile . 'a');
        if (!empty($_code)) {
            return [FAILED,'60内不能频繁发送!',[]];
        }

        try{
            $easySms->send($mobile, [
                'template' => '271050',
                'data' => [$code,'1']//{1}{2}
                //【看车狗科技有限公司】{1}为您的验证码,请于{2}分钟内填写,如非本人操作,请忽略本短信。
                //data数组按顺序对应你设置的变量
            ]);
            Cache::add($mobile . 'a', $code, 60);
            return [SUCCESS, '发送成功', []];

        }catch (\Overtrue\EasySms\Exceptions\NoGatewayAvailableException $exception){
            $error = [
                'msg' => $exception->getException(),
                'phone' => $phoneNumbers,
                'time' => Carbon::now()
            ];
            \Log::error('发送失败' . json_encode($error));
        }
    }
}

easy-sms github地址
https://github.com/overtrue/easy-sms

Pasa吴技术博客
请先登录后发表评论
  • latest comments
  • 总共0条评论