第一種方式: http://bbs.csdn.net/topics/392054241 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時間 date_default_timezone_set("GMT"); $dateTimeFormat = 'Y-m-d\TH:i:s\Z'; // ISO8601規範 $accessKeyId = 'LTAIGsgBVt8MDTyf'; // 這裡填寫您的Access Key ID $accessKeySecret = '5koNqwSpKi0SfjfyHUWqF0lCLIwuoS'; // 這裡填寫您的Access Key Secret $ParamString="{\"code\":\"".strval($mobile_code)."\",\"time\":\"15\"}"; $data = array( // 公共參數 'SignName'=>'代碼派', 'Format' => 'XML', 'Version' => '2016-09-27', 'AccessKeyId' => $accessKeyId, 'SignatureVersion' => '1.0', 'SignatureMethod' => 'HMAC-SHA1', 'SignatureNonce'=> uniqid(), 'Timestamp' => date($dateTimeFormat), // 接口參數 'Action' => 'SingleSendSms', 'TemplateCode' => $template_code, 'RecNum' => $phone, 'ParamString' => $ParamString ); // 計算簽名并把簽名結果加入請求參數 //echo $data['Version']."<br>"; //echo $data['Timestamp']."<br>"; $data['Signature'] = $this->computeSignature($data, $accessKeySecret); // 發送請求 $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 = '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"做替換即滿足ECS API規定的編碼規範 $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) { // 将參數Key按字典順序排序 ksort($parameters); // 生成規範化請求字元串 $canonicalizedQueryString = ''; foreach($parameters as $key => $value) { $canonicalizedQueryString .= '&' . $this->percentEncode($key) . '=' . $this->percentEncode($value); } // 生成用于計算簽名的字元串 stringToSign $stringToSign = 'GET&%2F&' . $this->percentencode(substr($canonicalizedQueryString, 1)); //echo "<br>".$stringToSign."<br>"; // 計算簽名,注意accessKeySecret後面要加上字元'&' $signature = base64_encode(hash_hmac('sha1', $stringToSign, $accessKeySecret . '&', true)); return $signature; }
第二種方式:
去阿裡官網下載下傳sdk
導入項目中 如圖
源碼如下 <?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;
// 加載區域結點配置 Config::load();
class Sms {
static $acsClient = null; public static function getAcsClient() { //産品名稱:雲通信流量服務API産品,開發者無需替換 $product = "Dysmsapi";
//産品域名,開發者無需替換 $domain = "dysmsapi.aliyuncs.com";
// TODO 此處需要替換成開發者自己的AK (https://ak-console.aliyun.com/) $accessKeyId = "LTAISVqnlWld4er1"; // AccessKeyId
$accessKeySecret = "MEuXuWz3kN5uN5J0qi7OEk4DFDEPWO"; // AccessKeySecret
// 暫時不支援多Region $region = "cn-hangzhou";
// 服務結點 $endPointName = "cn-hangzhou";
if(static::$acsClient == null) {
//初始化acsClient,暫不支援region化 $profile = DefaultProfile::getProfile($region, $accessKeyId, $accessKeySecret);
// 增加服務結點 DefaultProfile::addEndpoint($endPointName, $region, $product, $domain);
// 初始化AcsClient用于發起請求 static::$acsClient = new DefaultAcsClient($profile); } return static::$acsClient; }
public static function sendSms($signName,$templateCode, $phoneNumbers, $templateParam = null, $outId = null, $smsUpExtendCode = null) {
// 初始化SendSmsRequest執行個體用于設定發送短信的參數 $request = new SendSmsRequest();
// 必填,設定雉短信接收号碼 $request->setPhoneNumbers($phoneNumbers);
// 必填,設定簽名名稱 $request->setSignName($signName);
// 必填,設定模闆CODE $request->setTemplateCode($templateCode);
// 可選,設定模闆參數 if($templateParam) { $request->setTemplateParam(json_encode($templateParam)); }
// 可選,設定流水号 if($outId) { $request->setOutId($outId); }
// 選填,上行短信擴充碼 if($smsUpExtendCode) { $request->setSmsUpExtendCode($smsUpExtendCode); }
// 發起通路請求 $acsResponse = static::getAcsClient()->getAcsResponse($request);
// 列印請求結果 var_dump($acsResponse);
return $acsResponse;
}
} // header('Content-Type: text/plain; charset=utf-8');
// $response = Sms::sendSms( // "阿裡雲短信測試專用", //簽名 // "SMS_104910077", // 短信模闆編号 // "13972235112", // 短信接收者 // Array( // 短信模闆中字段的值 // "code"=>"12345", // "product"=>"dsd" // ), // "123" // 流水号,選填 // );