新版sdk下載下來,整合了很多東西,自己看著都煩,不多說,上原始碼
我寫了兩個類
AliSms.class.php
class AliSms {
//線上地址
const API_DOAMIN = `http://dysmsapi.aliyuncs.com/`;
protected $env;
protected $accesskey;
protected $secretKey;
protected static $method = `POST`;
protected static $header = array(
`x-sdk-client` => `php/2.0.0`,
);
//30 second
public static $connectTimeout = 30;
//80 second
public static $readTimeout = 80;
//公共引數
protected $requestParams = array();
public function __construct($accessKey,$secretKey){
$this->accesskey = $accessKey;
$this->secretKey = $secretKey;
$this->requestParams["AccessKeyId"] = $this->accesskey;
$this->requestParams["RegionId"] = `cn-hangzhou`;
$this->requestParams["Format"] = `JSON`;
$this->requestParams["SignatureMethod"] = `HMAC-SHA1`;
$this->requestParams["SignatureVersion"] = `1.0`;
$this->requestParams["SignatureNonce"] = uniqid();
date_default_timezone_set("GMT");
$this->requestParams["Timestamp"] = date(`Y-m-dTH:i:s`);
$this->requestParams["Action"] = `SendSms`;
$this->requestParams["Version"] = `2017-05-25`;
}
/**
* 傳送簡訊
* @param $phoneNumbers 電話號碼
* @param $signName 簡訊簽名
* @param $templateCode 簡訊模板程式碼
* @param $tempalteParam 簡訊模板引數
* @return HttpResponse
* @throws ThinkException
*/
public function execute($phoneNumbers, $signName, $templateCode, $tempalteParam){
$params = array(
`PhoneNumbers` => $phoneNumbers,
`SignName` => $signName,
`TemplateCode` => $templateCode,
`TemplateParam` => $tempalteParam,
);
if(empty($params[`PhoneNumbers`])) {
throw new Exception(`缺少引數PhoneNumbers`);
}
if(empty($params[`SignName`])) {
throw new Exception(`缺少引數SignName`);
}
if(empty($params[`TemplateCode`])) {
throw new Exception(`缺少引數TemplateCode`);
}
if(empty($params[`TemplateParam`])) {
throw new Exception(`缺少引數TemplateParam`);
}
foreach ($params as $key => $value) {
$apiParams[$key] = $this->prepareValue($value);
}
$params = array_merge($params, $this->requestParams);
$params["Signature"] = $this->computeSignature($params, $this->secretKey);
$response = $this->curl(self::API_DOAMIN, self::$method, $params, self::$header);
return $response;
}
//計算簽名
public function computeSignature($parameters, $accessKeySecret)
{
ksort($parameters);
$canonicalizedQueryString = ``;
foreach($parameters as $key => $value)
{
$canonicalizedQueryString .= `&` . $this->percentEncode($key). `=` . $this->percentEncode($value);
}
$stringToSign = self::$method.`&%2F&` . $this->percentencode(substr($canonicalizedQueryString, 1));
$signature = base64_encode(hash_hmac(`sha1`, $stringToSign, $accessKeySecret."&", true));
return $signature;
}
private function prepareValue($value)
{
if (is_bool($value)) {
if ($value) {
return "true";
} else {
return "false";
}
} else {
return $value;
}
}
public function percentEncode($str)
{
$res = urlencode($str);
$res = preg_replace(`/+/`, `%20`, $res);
$res = preg_replace(`/*/`, `%2A`, $res);
$res = preg_replace(`/%7E/`, `~`, $res);
return $res;
}
/**
* 網路請求
* @param $url
* @param string $httpMethod
* @param null $postFields
* @param null $headers
* @return mixed
* @throws ThinkException
*/
public function curl($url, $httpMethod = "GET", $postFields = null,$headers = null)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $httpMethod);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FAILONERROR, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, is_array($postFields) ? self::getPostHttpBody($postFields) : $postFields);
if (self::$readTimeout) {
curl_setopt($ch, CURLOPT_TIMEOUT, self::$readTimeout);
}
if (self::$connectTimeout) {
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, self::$connectTimeout);
}
//https request
if(strlen($url) > 5 && strtolower(substr($url,0,5)) == "https" ) {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
}
if (is_array($headers) && 0 < count($headers))
{
$httpHeaders =self::getHttpHearders($headers);
curl_setopt($ch,CURLOPT_HTTPHEADER,$httpHeaders);
}
$httpResponse = curl_exec($ch);
if (curl_errno($ch))
{
throw new Exception("Server unreachable: Errno: " . curl_errno($ch) . curl_error($ch));
}
curl_close($ch);
return $httpResponse;
}
public static function getPostHttpBody($postFildes){
$content = "";
foreach ($postFildes as $apiParamKey => $apiParamValue)
{
$content .= "$apiParamKey=" . urlencode($apiParamValue) . "&";
}
return substr($content, 0, -1);
}
public static function getHttpHearders($headers)
{
$httpHeader = array();
foreach ($headers as $key => $value)
{
array_push($httpHeader, $key.":".$value);
}
return $httpHeader;
}
}
下面這個類只是我不想呼叫是new AliSms寫的
Sender.class.php
class Sender {
private $provider;
private static $_instance = null;
private function __construct() {
$this->provider = new AliSms(C(`ALIYUN_AK`),C(`ALIYUN_SK`));
}
//單例
public static function getInstance() {
if(!self::$_instance) {
self::$_instance = new Sender();
}
return self::$_instance;
}
/**
* 傳送簡訊驗證碼
* @param $mobile 電話號碼
* @param $data 驗證碼 array(`code`=>`123456`)
* @return bool
*/
public function sendCode($mobile,$data) {
if(!$data[`code`]) return false;
$tempalteParam = json_encode($data);
$result = $this->provider->execute($mobile,`簡訊簽名`,`簡訊模板編號`,$tempalteParam);
return $this->parseResult($result,$mobile);
}
/**
* 處理簡訊傳送返回結果
* @param $result
* @param string $mobile
* @return bool
*/
private function parseResult($result,$mobile = ``) {
$result = json_decode($result,1);
if($result[`Code`] == `OK` && $result[`Message`] == `OK`){
//傳送成功
$this->onSendSuccess($result,$mobile);
return true;
}else{
//失敗
$this->onSendFail($result,$mobile);
return false;
}
}
/**
* 傳送成功後
* @param array $data
* @param string $mobile
*/
private function onSendSuccess(array $data = null ,$mobile = ``) {
//todo
}
/**
* 傳送失敗後
* @param array $data
* @param string $mobile
*/
private function onSendFail(array $data = null , $mobile = ``) {
//記錄日誌
$logPath = RUNTIME_PATH.`sms_`.date(`y_m_d`).`.log`;
ThinkLog::write(
` 手機號:`.$mobile.
` 大魚返回結果:`.serialize($data),
`INFO`,
``,
$logPath
);
}
使用方法:
$result = Sender::getInstance()->sendCode($mobile,array(`code` => $randCode));