关于对接阿里云短信的坑

最近项目中有使用到阿里云短信,所以对接了一下。

在对接过程中出现一个问题,使用官方的demo并不能成功发送短信。

官方定义给的模型是:

$sms = new SendSmsRequest([]);
$runtime = new RuntimeOptions([]);
$result = $client->sendSmsWithOptions($sms,$runtime);

在sendsmsrequest中加入要发送的参数就可以发送了,实际使用时会出现报错: missing PhoneNumbers。

如果我们进入到SendSmsRequest中可以看到,里面只有一个tomap和一个frommap的方法。要能正常使用,需要如下操作:

$sms->phoneNumbers = 'the phone number need send message';
$sms->templateCode = 'your template code';
$sms->signName ='your sign name';
$sms->templateParam = json_encode($data);

完整代码如下:

public function sendSms($data)
    {  
        $client = $this->getInstance('your appid', 'your app secret');
        $sms = new SendSmsRequest([]);
        $sms->phoneNumbers = 'your phone numbers';
        $sms->templateCode = 'your template code';
        $sms->signName = 'your sign name';

        $sms->templateParam = json_encode($data);//需要发送的变量数据
        $runtime = new RuntimeOptions([]);
        $result = $client->sendSmsWithOptions($sms,$runtime);
        return $result;
}

 public function getInstance($appId,$appKey)
    {
        $config = new Config([
            'accessKeyId' => $appId,
            'accessKeySecret' => $appKey
        ]);

        $config->endpoint = 'dysmsapi.aliyuncs.com';
        return new Dysmsapi($config);
    }

 

posted @ 2023-11-23 11:58  秋江月  阅读(162)  评论(0)    收藏  举报