♦先说一下吧,这篇文章主要教大家如何使用tp5来使用阿里短信平台最新版2.0sdk,也就是所谓的前阿里大鱼。
♦但是高手略过啊,只针对新手,如果大家发现有什么问题,欢迎留言指出,我会更正!
♦首先我们下载官方完整包的SDK:
♦官方标明了啊,PHP版本一定要不低于5.5
♦我这边使用的是PHP轻量版本
◆◆第一步◆◆
下载PHP轻量版sdk,我们只用到其中的一个文件--签名文件
◆◆第二步◆◆
将SignatureHelper.php重命名为Signature.php
◆◆第三步◆◆
新建sms.php同级文件,引用刚重命名的PHP文件
◆◆发送短信◆◆
◆◆Sms.php代码◆◆
namespace app\api\controller;
use think\Controller;
use think\Db;
require_once 'Signature.php';
//短信接口
class Sms extends Controller
{
public function send(){
self::sendSms('156***88507',4,'888888699');
}
public static function sendSms($phone,$type,$code,$remark = ''){
$params = array ();
//阿里云的AccessKey
$accessKeyId = '阿里云后台ak';
//阿里云的Access Key Secret
$accessKeySecret = '阿里云后台sk';
//要发送的手机号
$params["PhoneNumbers"] = $phone;
//签名,第三步申请得到
$params["SignName"] = '悠阿狸';
//模板name,第三步申请得到
switch ($type){
case 1:
//已完成-用户接收此通知 [亲爱的会员,您提交的${name}订单,已经完成交易~感谢您的支持!]
$params["TemplateCode"] ='SMS_178995163';
$params['TemplateParam'] = Array (
"name" => $code
);
break;
case 2:
//确认接单-用户接收 [亲爱的会员,您提交的${name}订单,师傅已经确认接单。我们会尽快上门收货,记得关注我们的公众号喔~感谢您的支持!]
$params["TemplateCode"] = 'SMS_178990166';
$params['TemplateParam'] = Array (
"name" => $code
);
break;
case 3:
//用户下单成功-车夫接收 [您有新的订单待处理,客户联系电话:${phone},订单摘要:${remark},请及时处理。]
$params["TemplateCode"] = 'SMS_178980185';
$params['TemplateParam'] = Array (
"phone" => $code,
"remark" => $remark,
);
break;
case 4:
//新订单通知-车夫接收 [您有一条新订单等待处理,请及时前往车夫系统操作此订单!]
$params["TemplateCode"] = 'SMS_178995204';
break;
default:
echo json_encode('模板参数错误',JSON_UNESCAPED_UNICODE);
break;
}
// *** 需用户填写部分结束, 以下代码若无必要无需更改***
if(!empty($params["TemplateParam"]) && is_array($params["TemplateParam"])) {
$params["TemplateParam"] = json_encode($params["TemplateParam"], JSON_UNESCAPED_UNICODE);
}
// 初始化SignatureHelper实例用于设置参数,签名以及发送请求
$helper = new Signature();
try{
// 此处可能会抛出异常,注意catch
$content = $helper->request(
$accessKeyId,
$accessKeySecret,
"dysmsapi.aliyuncs.com",
array_merge($params, array(
"RegionId" => "cn-hangzhou",
"Action" => "SendSms",
"Version" => "2017-05-25",
))
// fixme 选填: 启用https
// ,true
);
$res=array('errCode'=>0,'msg'=>'ok');
if($content->Message!='OK'){
$res['errCode']=1;
$res['msg']=$content->Message;
}
echo json_encode($res,JSON_UNESCAPED_UNICODE);
}catch(\Exception $e){
echo '短信接口请求错误';exit;
}
}
}
◆◆Signature.php代码◆◆
namespace app\api\controller;
/**
* 签名助手 2017/11/19
*
* Class SignatureHelper
*/
class Signature {
/**
* 生成签名并发起请求
*
* @param $accessKeyId string AccessKeyId (https://ak-console.aliyun.com/)
* @param $accessKeySecret string AccessKeySecret
* @param $domain string API接口所在域名
* @param $params array API具体参数
* @param $security boolean 使用https
* @param $method boolean 使用GET或POST方法请求,VPC仅支持POST
* @return bool|\stdClass 返回API接口调用结果,当发生错误时返回false
*/
public function request($accessKeyId, $accessKeySecret, $domain, $params, $security=false, $method='POST') {
$apiParams = array_merge(array (
"SignatureMethod" => "HMAC-SHA1",
"SignatureNonce" => uniqid(mt_rand(0,0xffff), true),
"SignatureVersion" => "1.0",
"AccessKeyId" => $accessKeyId,
"Timestamp" => gmdate("Y-m-d\TH:i:s\Z"),
"Format" => "JSON",
), $params);
ksort($apiParams);
$sortedQueryStringTmp = "";
foreach ($apiParams as $key => $value) {
$sortedQueryStringTmp .= "&" . $this->encode($key) . "=" . $this->encode($value);
}
$stringToSign = "${method}&%2F&" . $this->encode(substr($sortedQueryStringTmp, 1));
$sign = base64_encode(hash_hmac("sha1", $stringToSign, $accessKeySecret . "&",true));
$signature = $this->encode($sign);
$url = ($security ? 'https' : 'http')."://{$domain}/";
try {
$content = $this->fetchContent($url, $method, "Signature={$signature}{$sortedQueryStringTmp}");
return json_decode($content);
} catch( \Exception $e) {
return false;
}
}
private function encode($str)
{
$res = urlencode($str);
$res = preg_replace("/\+/", "%20", $res);
$res = preg_replace("/\*/", "%2A", $res);
$res = preg_replace("/%7E/", "~", $res);
return $res;
}
private function fetchContent($url, $method, $body) {
$ch = curl_init();
if($method == 'POST') {
curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
} else {
$url .= '?'.$body;
}
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"x-sdk-client" => "php/2.0.0"
));
if(substr($url, 0,5) == 'https') {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
}
$rtn = curl_exec($ch);
if($rtn === false) {
// 大多由设置等原因引起,一般无法保障后续逻辑正常执行,
// 所以这里触发的是E_USER_ERROR,会终止脚本执行,无法被try...catch捕获,需要用户排查环境、网络等故障
trigger_error("[CURL_" . curl_errno($ch) . "]: " . curl_error($ch), E_USER_ERROR);
}
curl_close($ch);
return $rtn;
}
}
网友评论