伸手黨來吧。thinkphp,新阿里大魚短信發送,sdk那麼多東西,是否是很煩啊

新版sdk下載下來,集成了不少東西,本身看着都煩,很少說,上源碼
我寫了兩個類
AliSms.class.phpphp

class AliSms {json

//線上地址
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;
}

}api

下面這個類只是我不想調用是new AliSms寫的
Sender.class.php網絡

class Sender {curl

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));ide

相關文章
相關標籤/搜索