新版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-d\TH:i:s\Z');
$this->requestParams["Action"] = 'SendSms';
$this->requestParams["Version"] = '2017-05-25';
}
/**
* 发送短信
* @param $phoneNumbers 电话号码
* @param $signName 短信签名
* @param $templateCode 短信模板代码
* @param $tempalteParam 短信模板参数
* @return HttpResponse
* @throws \Think\Exception
*/
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 \Think\Exception
*/
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';
\Think\Log::write(
' 手机号:'.$mobile.
' 大鱼返回结果:'.serialize($data),
'INFO',
'',
$logPath
);
}
使用方法:
$result = Sender::getInstance()->sendCode($mobile,array('code' => $randCode));
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。