thinkphp6阿里云短信新版sdk对接

1、composer 加载sdk
2、配置sdk

<?php

namespace app\api\common;

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

class AliSms
{

    /**
     * 使用AK&SK初始化账号Client
     * @param string $accessKeyId
     * @param string $accessKeySecret
     * @return Dysmsapi Client
     */
    public static function createClient(string $accessKeyId, string $accessKeySecret): Dysmsapi
    {
        $config = new Config([
            // 您的AccessKey ID
            "accessKeyId" => config('sms.ali.accessKeyId'),
            // 您的AccessKey Secret
            "accessKeySecret" => config('sms.ali.accessKeySecret')
        ]);
        // 访问的域名
        $config->endpoint = "dysmsapi.aliyuncs.com";
        return new Dysmsapi($config);
    }

    /**
     * @param string[] $args
     * @return void
     */
    public static function main(array $args)
    {
        $client = self::createClient("accessKeyId", "accessKeySecret");
        //SMS_157225731
        $sendSmsRequest = new SendSmsRequest([
            "phoneNumbers" => $args['phone'],
            "signName" => config(sms.ali.sign_name),
            "templateCode" => config(sms.ali.template_code),
            "templateParam" => json_encode(['code'=>$args['code']])
        ]);
        $result = $client->sendSms($sendSmsRequest);
        if ($result->body->message == 'OK' && $result->body->code == 'OK') {
            return ['code' => 200,'msg'=>'success'];
        }
        if ($result->body->code == 'isv.MOBILE_NUMBER_ILLEGAL') {
            return ['code' => 0, 'msg' => '手机号码格式不正确'];
        }
        return ['code' => 0, 'msg' => '短信发送失败,网络繁忙'];
    }
}


3、调用sdk

<?php

namespace app\api\controller;
use app\api\common\AliSms as ali;
class AliSms
{
    public function sendSms($phone){
        if(!request()->isPost()){
            return json(['code'=>0,'msg'=>'methods is error']);
        }
        $phone = trim($phone);
        $code = mt_rand(1000,9999);
        $data = [
            'phone'=>$phone,
            'code'=>$code
        ];
        //判断运营商
        //调用阿里云短信发送方法
        $send = new ali();
        $result = $send::main($data);
        dump($result);die;
    }
}
————————————————
版权声明:本文为CSDN博主「victor of Python」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_44213550/article/details/124288084

 

posted @ 2022-06-03 17:11  画画520  阅读(289)  评论(0编辑  收藏  举报