资讯专栏INFORMATION COLUMN

伸手党来吧。thinkphp,新阿里大鱼短信发送,sdk那么多东西,是不是很烦啊

lidashuang / 2593人阅读

摘要:新版下载下来,集成了很多东西,自己看着都烦,不多说,上源码我写了两个类线上地址公共参数发送短信电话号码短信签名短信模板代码短信模板参数缺少参数缺少参数缺少参数缺少参数计算签名网络请求

新版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));

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/26011.html

相关文章

  • 阿里大鱼JavaScript 版本 SDK

    摘要:阿里大鱼兼容服务器端环境,模块加载器如和所有浏览器浏览器直接调用需要两个的依赖文件和,其中网上版本很多,这里使用脚本标签引入文件如示例脚本代码应用密匙见创建实例参数见身份验证短信发送端注意,信息可能泄露出来,可以使用混淆加密代码。 JavaScript Alidayu(阿里大鱼) SDK 兼容服务器端环境node.js,模块加载器如RequireJS和所有浏览器 Client-sid...

    junbaor 评论0 收藏0
  • 阿里大于验证码功能

    摘要:经过各大短信平台进行比较后,选择了阿里大于,一个阿里巴巴的云通信平台,下面我将这次开发经验和遇到的一些问题分享出来。 最近在做一个商城的项目,其中注册、找回密码、换绑手机等功能都需要用到验证码,考虑到上线的安全问题,我决定用手机验证码来提高安全性。经过各大短信平台进行比较后,选择了阿里大于,一个阿里巴巴的云通信平台,下面我将这次开发经验和遇到的一些问题分享出来。 1.登录平台 阿里大...

    jokester 评论0 收藏0
  • 阿里大于验证码功能

    摘要:经过各大短信平台进行比较后,选择了阿里大于,一个阿里巴巴的云通信平台,下面我将这次开发经验和遇到的一些问题分享出来。 最近在做一个商城的项目,其中注册、找回密码、换绑手机等功能都需要用到验证码,考虑到上线的安全问题,我决定用手机验证码来提高安全性。经过各大短信平台进行比较后,选择了阿里大于,一个阿里巴巴的云通信平台,下面我将这次开发经验和遇到的一些问题分享出来。 1.登录平台 阿里大...

    CoderDock 评论0 收藏0
  • NodeJS实现阿里大鱼短信通知发送

    摘要:说明阿里大鱼提供了验证码,短信通知,语音等服务,在使用后感觉挺方便,不愧是阿里旗下的产品。最近想搞个发送短信通知的功能,不过阿里大鱼官网并没有提供版本的示例没有版本的,所以需要自己整一个签名,实现短信发送。 1、说明 阿里大鱼提供了验证码,短信通知,语音等服务,在使用后感觉挺方便,不愧是阿里旗下的产品。 最近想搞个NodeJS发送短信通知的功能,不过阿里大鱼官网API并没有提供JS版本...

    Anshiii 评论0 收藏0
  • thinkphp阿里短信服务,替代原来的阿里大于

    摘要:之前使用的阿里大于,不过很坑的是,新接入的都不能用了,融入进了阿里云服务,当然阿里大于的老用户还可以继续用阿里大于首先还是接入,上图找到短信服务设置短信签名和短信模板设置或找到或下载文档打开下载下来的文档,只需要,将其改名为,并放到项目根目 之前使用的阿里大于,不过很坑的是,新接入的都不能用了,融入进了阿里云服务,当然阿里大于的老用户还可以继续用阿里大于 首先还是接入,上图: (1)找...

    mj 评论0 收藏0

发表评论

0条评论

lidashuang

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<