1.开通短信服务后,进入控制器->短信服务
2.点击国内消息,配置签名,模板(这里不作详细介绍)
3.点击进入左侧帮助文档里面,找到PHP sdk,Composer命令直接安装
4.获取accessKeyId和accessSecret(如图,不做详细介绍)
5.上代码:
<?phpnamespace 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;
}