1.開通短信服務后,進入控制器->短信服務
2.點擊國內消息,配置簽名,模板(這里不作詳細介紹)
3.點擊進入左側幫助文檔里面,找到PHP sdk,Composer命令直接安裝
4.獲取accessKeyId和accessSecret(如圖,不做詳細介紹)
5.上代碼:
<?php
namespace app\common\controller;
use think\Controller;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
class SendSms extends Controller {
static private $accessKeyId = "你的accessKeyId";
static private $accessSecret = "你的accessSecret";
static private $signName = "阿里雲里面設置的簽名";
// 優先加載
public function _initialize() {
}
static function send_sms($mobile,$code,$template){
$accessKeyId = self::$accessKeyId;
$accessSecret = self::$accessSecret;
$signName = self::$signName;
AlibabaCloud::accessKeyClient($accessKeyId, $accessSecret)
->regionId('cn-hangzhou')
->asDefaultClient();
try {
$result = AlibabaCloud::rpc()
->product('Dysmsapi')
// ->scheme('https') // https | http
->version('2017-05-25')
->action('SendSms')
->method('POST')
->host('dysmsapi.aliyuncs.com')
->options([
'query' => [
'RegionId' => "cn-hangzhou",
'PhoneNumbers' => $mobile,
'SignName' => $signName,
'TemplateCode' => $template,
'TemplateParam' => $code,
],
])
->request();
print_r($result->toArray());
} catch (ClientException $e) {
echo $e->getErrorMessage() . PHP_EOL;
} catch (ServerException $e) {
echo $e->getErrorMessage() . PHP_EOL;
}
}
}
6.控制器里面調用:
use app\common\controller\SendSms;
public function sendTest(){
$mobile = "需要接收短信的手機號";
$template = "阿里雲短信服務里面配置的模板";
$code['code'] = "短信驗證碼";
$return = SendSms::send_sms($mobile,json_encode($code),$template);
return $return;
}