/**
* 阿里云 短信驗(yàn)證
* @param $phone 手機(jī)號(hào)碼
* @param null $mobile_code 驗(yàn)證碼
* @param null $template_code 短信模版
*/
public function phoneCode($phone,$mobile_code=null,$template_code=null){
if (!$mobile_code){$mobile_code = $this->random(6,1);}
if(!$template_code){$template_code='SMS_37650042';}
$target = "https://sms.aliyuncs.com/?";
// 注意使用GMT時(shí)間
date_default_timezone_set("GMT");
$dateTimeFormat = 'Y-m-d\TH:i:s\Z'; // ISO8601規(guī)范
$accessKeyId = 'LTAIGsgBVt8MDTyf'; // 這里填寫(xiě)您的Access Key ID
$accessKeySecret = '5koNqwSpKi0SfjfyHUWqF0lCLIwuoS'; // 這里填寫(xiě)您的Access Key Secret
$ParamString="{\"code\":\"".strval($mobile_code)."\",\"time\":\"15\"}";
$data = array(
// 公共參數(shù)
'SignName'=>'代碼派',
'Format' => 'XML',
'Version' => '2016-09-27',
'AccessKeyId' => $accessKeyId,
'SignatureVersion' => '1.0',
'SignatureMethod' => 'HMAC-SHA1',
'SignatureNonce'=> uniqid(),
'Timestamp' => date($dateTimeFormat),
// 接口參數(shù)
'Action' => 'SingleSendSms',
'TemplateCode' => $template_code,
'RecNum' => $phone,
'ParamString' => $ParamString
);
// 計(jì)算簽名并把簽名結(jié)果加入請(qǐng)求參數(shù)
//echo $data['Version']."<br>";
//echo $data['Timestamp']."<br>";
$data['Signature'] = $this->computeSignature($data, $accessKeySecret);
// 發(fā)送請(qǐng)求
$result = $this->xml_to_array($this->https_request($target.http_build_query($data)));
print_r($result);
}
public function https_request($url)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($curl);
if (curl_errno($curl)) {return 'ERROR '.curl_error($curl);}
curl_close($curl);
return $data;
}
public function xml_to_array($xml){
$reg = "/<(\w+)[^>]*>([\\x00-\\xFF]*)<\\/\\1>/";
if(preg_match_all($reg, $xml, $matches)){
$count = count($matches[0]);
for($i = 0; $i < $count; $i++){
$subxml= $matches[2][$i];
$key = $matches[1][$i];
if(preg_match( $reg, $subxml )){
$arr[$key] = $this->xml_to_array( $subxml );
}else{
$arr[$key] = $subxml;
}
}
}
return @$arr;
}
public function random($length = 6 , $numeric = 0) {
PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
if($numeric) {
$hash = sprintf('%0'.$length.'d', mt_rand(0, pow(10, $length) - 1));
} else {
$hash = '';
/* $chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789abcdefghjkmnpqrstuvwxyz';*/
$chars = '0123456789';
$max = strlen($chars) - 1;
for($i = 0; $i < $length; $i++) {
$hash .= $chars[mt_rand(0, $max)];
}
}
return $hash;
}
public function percentEncode($str)
{
// 使用urlencode編碼后,將"+","*","%7E"做替換即滿(mǎn)足ECS API規(guī)定的編碼規(guī)范
$res = urlencode($str);
$res = preg_replace('/\+/', '%20', $res);
$res = preg_replace('/\*/', '%2A', $res);
$res = preg_replace('/%7E/', '~', $res);
return $res;
}
public function computeSignature($parameters, $accessKeySecret)
{
// 將參數(shù)Key按字典順序排序
ksort($parameters);
// 生成規(guī)范化請(qǐng)求字符串
$canonicalizedQueryString = '';
foreach($parameters as $key => $value)
{
$canonicalizedQueryString .= '&' . $this->percentEncode($key)
. '=' . $this->percentEncode($value);
}
// 生成用于計(jì)算簽名的字符串 stringToSign
$stringToSign = 'GET&%2F&' . $this->percentencode(substr($canonicalizedQueryString, 1));
//echo "<br>".$stringToSign."<br>";
// 計(jì)算簽名,注意accessKeySecret后面要加上字符'&'
$signature = base64_encode(hash_hmac('sha1', $stringToSign, $accessKeySecret . '&', true));
return $signature;
}
第二種方式:
導(dǎo)入項(xiàng)目中 如圖
源碼如下
<?php
ini_set("display_errors", "on");
require_once dirname(__DIR__) . '/sms/vendor/autoload.php';
use Aliyun\Core\Config;
use Aliyun\Core\Profile\DefaultProfile;
use Aliyun\Core\DefaultAcsClient;
use Aliyun\Api\Sms\Request\V20170525\SendSmsRequest;
use Aliyun\Api\Sms\Request\V20170525\QuerySendDetailsRequest;
// 加載區(qū)域結(jié)點(diǎn)配置
Config::load();
/**
* Class SmsDemo
*
* Created on 17/10/17.
* 短信服務(wù)API產(chǎn)品的DEMO程序,工程中包含了一個(gè)SmsDemo類(lèi),直接通過(guò)
* 執(zhí)行此文件即可體驗(yàn)語(yǔ)音服務(wù)產(chǎn)品API功能(只需要將AK替換成開(kāi)通了云通信-短信服務(wù)產(chǎn)品功能的AK即可)
* 備注:Demo工程編碼采用UTF-8
*/
class Sms
{
static $acsClient = null;
/**
* 取得AcsClient
*
* @return DefaultAcsClient
*/
public static function getAcsClient() {
//產(chǎn)品名稱(chēng):云通信流量服務(wù)API產(chǎn)品,開(kāi)發(fā)者無(wú)需替換
$product = "Dysmsapi";
//產(chǎn)品域名,開(kāi)發(fā)者無(wú)需替換
$domain = "dysmsapi.aliyuncs.com";
// TODO 此處需要替換成開(kāi)發(fā)者自己的AK (https://ak-console.aliyun.com/)
$accessKeyId = "LTAISVqnlWld4er1"; // AccessKeyId
$accessKeySecret = "MEuXuWz3kN5uN5J0qi7OEk4DFDEPWO"; // AccessKeySecret
// 暫時(shí)不支持多Region
$region = "cn-hangzhou";
// 服務(wù)結(jié)點(diǎn)
$endPointName = "cn-hangzhou";
if(static::$acsClient == null) {
//初始化acsClient,暫不支持region化
$profile = DefaultProfile::getProfile($region, $accessKeyId, $accessKeySecret);
// 增加服務(wù)結(jié)點(diǎn)
DefaultProfile::addEndpoint($endPointName, $region, $product, $domain);
// 初始化AcsClient用于發(fā)起請(qǐng)求
static::$acsClient = new DefaultAcsClient($profile);
}
return static::$acsClient;
}
/**
* 發(fā)送短信
*
* @param string $signName <p>
* 必填, 短信簽名,應(yīng)嚴(yán)格"簽名名稱(chēng)"填寫(xiě),參考:<a >短信簽名頁(yè)</a>
* </p>
* @param string $templateCode <p>
* 必填, 短信模板Code,應(yīng)嚴(yán)格按"模板CODE"填寫(xiě), 參考:<a >短信模板頁(yè)</a>
* (e.g. SMS_0001)
* </p>
* @param string $phoneNumbers 必填, 短信接收號(hào)碼 (e.g. 12345678901)
* @param array|null $templateParam <p>
* 選填, 假如模板中存在變量需要替換則為必填項(xiàng) (e.g. Array("code"=>"12345", "product"=>"阿里通信"))
* </p>
* @param string|null $outId [optional] 選填, 發(fā)送短信流水號(hào) (e.g. 1234)
* @param string|null $smsUpExtendCode [optional] 選填,上行短信擴(kuò)展碼(擴(kuò)展碼字段控制在7位或以下,無(wú)特殊需求用戶(hù)請(qǐng)忽略此字段)
* @return stdClass
*/
public static function sendSms($signName,$templateCode, $phoneNumbers, $templateParam = null, $outId = null, $smsUpExtendCode = null) {
// 初始化SendSmsRequest實(shí)例用于設(shè)置發(fā)送短信的參數(shù)
$request = new SendSmsRequest();
// 必填,設(shè)置雉短信接收號(hào)碼
$request->setPhoneNumbers($phoneNumbers);
// 必填,設(shè)置簽名名稱(chēng)
$request->setSignName($signName);
// 必填,設(shè)置模板CODE
$request->setTemplateCode($templateCode);
// 可選,設(shè)置模板參數(shù)
if($templateParam) {
$request->setTemplateParam(json_encode($templateParam));
}
// 可選,設(shè)置流水號(hào)
if($outId) {
$request->setOutId($outId);
}
// 選填,上行短信擴(kuò)展碼
if($smsUpExtendCode) {
$request->setSmsUpExtendCode($smsUpExtendCode);
}
// 發(fā)起訪(fǎng)問(wèn)請(qǐng)求
$acsResponse = static::getAcsClient()->getAcsResponse($request);
// 打印請(qǐng)求結(jié)果
var_dump($acsResponse);
return $acsResponse;
}
}
// header('Content-Type: text/plain; charset=utf-8');
// $response = Sms::sendSms(
// "阿里云短信測(cè)試專(zhuān)用", //簽名
// "SMS_104910077", // 短信模板編號(hào)
// "13972235112", // 短信接收者
// Array( // 短信模板中字段的值
// "code"=>"12345",
// "product"=>"dsd"
// ),
// "123" // 流水號(hào),選填
// );
浙公網(wǎng)安備 33010602011771號(hào)