一、官方资料
https://help.aliyun.com/document_detail/55501.html?spm=5176.doc55451.6.539.r5rP1D
二、下载SDK(选择合适的语言)
https://help.aliyun.com/document_detail/55359.html?spm=5176.doc55501.6.569.aCqx8E
三、使用
1,将下载的文件放入需要使用的项目中。
2,自定义类使用SDK
<?php
/**
* 阿里云短信
*/
class Dg_Helper_AliyunSms
{
//此处需要替换成自己的AK信息
private $_accessKeyId = 'xxx';
private $_accessKeySecret = 'xxx';
//短信API产品名
private $_product = 'Dysmsapi';
//短信API产品域名
private $_domain = 'dysmsapi.aliyuncs.com';
//暂时不支持多Region
private $_region = 'cn-hangzhou';
public function __construct()
{
$path = dirname(dirname(__FILE__));
include $path.'/Message/aliyun/api_sdk/aliyun-php-sdk-core/Config.php';
include_once $path.'/Message/aliyun/api_sdk/Dysmsapi/Request/V20170525/SendSmsRequest.php';
include_once $path.'/Message/aliyun/api_sdk/Dysmsapi/Request/V20170525/QuerySendDetailsRequest.php';
}
/**
* 发送短信
* @param integer $phone 电话号码
* @param string $templateCode 模板编号
* @param array $templateParam 选填,模板参数
* @param string $signName 短信签名
* @param integer $outId 短信流水号
*/
public function sendMessage($phone, $templateCode, $templateParam = array(), $signName = '短信签名', $outId = false)
{
//初始化访问的acsCleint
$profile = DefaultProfile::getProfile($this->_region, $this->_accessKeyId, $this->_accessKeySecret);
DefaultProfile::addEndpoint("cn-hangzhou", "cn-hangzhou", $this->_product, $this->_domain);
$acsClient= new DefaultAcsClient($profile);
$request = new Dysmsapi\Request\V20170525\SendSmsRequest;
//必填-短信接收号码
$request->setPhoneNumbers($phone);
//必填-短信签名
$request->setSignName($signName);
//必填-短信模板Code
$request->setTemplateCode($templateCode);
//选填-假如模板中存在变量需要替换则为必填(JSON格式)
if ( !empty($templateParam) ) {
$request->setTemplateParam(json_encode($templateParam));
}
//选填-发送短信流水号
if ( $outId ) {
$request->setOutId($outId);
}
//发起访问请求
$acsResponse = $acsClient->getAcsResponse($request);
return json_decode(json_encode($acsResponse), true);
}
/**
* 发送验证码短信
* @param integer $phone 电话号码
* @param integer $code 激活码
* @param integer $expire_time 失效时间,该有效时间为redis缓存有效时间
*/
public function sendVcodeMessage($phone, $code = false, $expire_time = false)
{
$templateCode = 'SMS_12345678';
$templateParam = array(
'code' => $code,
'expire_time' => $expire_time ? $expire_time : '',
);
return $this->sendMessage($phone, $templateCode, $templateParam);
}
}
3,调用
四、注意
短信平台一般有各种限制,比如单一IP限制等,最好多个短信平台一起使用(一个平台发送失败,可以用其他平台继续发送)