早睡早起,方能养生
Sleep early rise early, way to keep healthy

阿里云短信服务 PHP最新版(Aliyun SMS)

super
2021-06-19 17:06
views 4750

composer require alibabacloud/dysmsapi-20170525

 

<?php
/**
 * Author: super
 * Date: 2021/6/19
 */

namespace app\base\logic;

use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;

use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;

class AliyunSMS
{
    const KEY = 'your_key';
    const SECRET = 'your_secret';
    const SIGN = 'your_sign';

    /**
     * 使用AK&SK初始化账号Client
     * @param mixed $accessKeyId
     * @param mixed $accessKeySecret
     * @return Dysmsapi Client
     */
    public static function createClient($accessKeyId = null, $accessKeySecret = null)
    {
        $config = new Config([
            "accessKeyId" => $accessKeyId ?? AliyunSMS::KEY,
            "accessKeySecret" => $accessKeySecret ?? AliyunSMS::SECRET
        ]);
        // 访问的域名
        $config->endpoint = "dysmsapi.aliyuncs.com";
        return new Dysmsapi($config);
    }

    /**
     * 短信验证码
     * @param int $phone 手机号码
     * @param int $code 验证码
     * @return array
     */
    public static function verify(int $phone, int $code)
    {
        $client = self::createClient(AliyunSMS::KEY, AliyunSMS::SECRET);
        $sendSmsRequest = new SendSmsRequest([
            "phoneNumbers" => $phone,
            "signName" => AliyunSMS::SIGN,
            "templateCode" => "SMS_21796xxxx",
            "templateParam" => json_encode([
                'code' => $code
            ])
        ]);
        $result = $client->sendSms($sendSmsRequest);
        if ($result->body->message == 'OK' && $result->body->code == 'OK') {
            return ['status' => 1];
        }
        if ($result->body->code == 'isv.MOBILE_NUMBER_ILLEGAL') {
            return ['status' => 0, 'msg' => '手机号码格式不正确'];
        }
        return ['status' => 0, 'msg' => '短信发送失败,网络繁忙'];
    }

    /**
     * @param string[] $args
     * @return void
     */
    public static function main($args)
    {
        $client = self::createClient("accessKeyId", "accessKeySecret");
        $sendSmsRequest = new SendSmsRequest([
            "phoneNumbers" => "1503871****",
            "signName" => "阿里大于测试专用",
            "templateCode" => "SMS_215180185",
            "templateParam" => "{\"code\":\"1111\",\"code1\":\"1111\",\"code3\":\"1111\"}"
        ]);
        // 复制代码运行请自行打印 API 的返回值
        $client->sendSms($sendSmsRequest);
    }
}

 

$phone = '';
$code = rand(100000, 999999);
$result = AliyunSMS::verify($phone, $code);
if ($result['status'] == 1) {
	Cache::set($this->userID . '_register_' . $phone, ['code' => $code, 'time' => time()], 86400);
	success('发送成功');
}
error($result['msg']);

 



分享
0 条讨论
top