?先說一下吧圾旨,這篇文章主要教大家如何使用tp5來使用阿里短信平臺(tái)最新版2.0sdk摘悴,也就是所謂的前阿里大魚。
?但是高手略過啊碾篡,只針對(duì)新手虱而,如果大家發(fā)現(xiàn)有什么問題,歡迎留言指出耽梅,我會(huì)更正薛窥!
?首先我們下載官方完整包的SDK:
?官方標(biāo)明了啊,PHP版本一定要不低于5.5
?我這邊使用的是PHP輕量版本
◆◆第一步◆◆
下載PHP輕量版sdk,我們只用到其中的一個(gè)文件--簽名文件
◆◆第二步◆◆
將SignatureHelper.php重命名為Signature.php
◆◆第三步◆◆
新建sms.php同級(jí)文件眼姐,引用剛重命名的PHP文件
◆◆發(fā)送短信◆◆
◆◆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 = '阿里云后臺(tái)ak';
? ? ? ? //阿里云的Access Key Secret
? ? ? ? $accessKeySecret = '阿里云后臺(tái)sk';
? ? ? ? //要發(fā)送的手機(jī)號(hào)
? ? ? ? $params["PhoneNumbers"] = $phone;
? ? ? ? //簽名诅迷,第三步申請(qǐng)得到
? ? ? ? $params["SignName"] = '悠阿貍';
? ? ? ? //模板name,第三步申請(qǐng)得到
? ? ? ? switch ($type){
? ? ? ? ? ? case 1:
? ? ? ? ? ? ? ? //已完成-用戶接收此通知? ? [親愛的會(huì)員众旗,您提交的${name}訂單罢杉,已經(jīng)完成交易~感謝您的支持!]
? ? ? ? ? ? ? ? $params["TemplateCode"] ='SMS_178995163';
? ? ? ? ? ? ? ? $params['TemplateParam'] = Array (
? ? ? ? ? ? ? ? ? ? "name" => $code
? ? ? ? ? ? ? ? );
? ? ? ? ? ? ? ? break;
? ? ? ? ? ? case 2:
? ? ? ? ? ? ? ? //確認(rèn)接單-用戶接收? ? ? [親愛的會(huì)員贡歧,您提交的${name}訂單,師傅已經(jīng)確認(rèn)接單滩租。我們會(huì)盡快上門收貨,記得關(guān)注我們的公眾號(hào)喔~感謝您的支持利朵!]
? ? ? ? ? ? ? ? $params["TemplateCode"] = 'SMS_178990166';
? ? ? ? ? ? ? ? $params['TemplateParam'] = Array (
? ? ? ? ? ? ? ? ? ? "name" => $code
? ? ? ? ? ? ? ? );
? ? ? ? ? ? ? ? break;
? ? ? ? ? ? case 3:
? ? ? ? ? ? ? ? //用戶下單成功-車夫接收? [您有新的訂單待處理律想,客戶聯(lián)系電話:${phone},訂單摘要:${remark}绍弟,請(qǐng)及時(shí)處理技即。]
? ? ? ? ? ? ? ? $params["TemplateCode"] = 'SMS_178980185';
? ? ? ? ? ? ? ? $params['TemplateParam'] = Array (
? ? ? ? ? ? ? ? ? ? "phone" => $code,
? ? ? ? ? ? ? ? ? ? "remark" => $remark,
? ? ? ? ? ? ? ? );
? ? ? ? ? ? ? ? break;
? ? ? ? ? ? case 4:
? ? ? ? ? ? ? ? //新訂單通知-車夫接收? ? ? [您有一條新訂單等待處理,請(qǐng)及時(shí)前往車夫系統(tǒng)操作此訂單!]
? ? ? ? ? ? ? ? $params["TemplateCode"] = 'SMS_178995204';
? ? ? ? ? ? ? ? break;
? ? ? ? ? ? default:
? ? ? ? ? ? ? ? echo json_encode('模板參數(shù)錯(cuò)誤',JSON_UNESCAPED_UNICODE);
? ? ? ? ? ? ? ? break;
? ? ? ? }
? ? ? ? // *** 需用戶填寫部分結(jié)束, 以下代碼若無必要無需更改***
? ? ? ? if(!empty($params["TemplateParam"]) && is_array($params["TemplateParam"])) {
? ? ? ? ? ? $params["TemplateParam"] = json_encode($params["TemplateParam"], JSON_UNESCAPED_UNICODE);
? ? ? ? }
? ? ? ? // 初始化SignatureHelper實(shí)例用于設(shè)置參數(shù)樟遣,簽名以及發(fā)送請(qǐng)求
? ? ? ? $helper = new Signature();
? ? ? ? try{
? ? ? ? ? ? // 此處可能會(huì)拋出異常而叼,注意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 '短信接口請(qǐng)求錯(cuò)誤';exit;
? ? ? ? }
}
}
◆◆Signature.php代碼◆◆
namespace app\api\controller;
/**
* 簽名助手 2017/11/19
*
* Class SignatureHelper
*/
class Signature {
? ? /**
? ? * 生成簽名并發(fā)起請(qǐng)求
? ? *
? ? * @param $accessKeyId string AccessKeyId (https://ak-console.aliyun.com/)
? ? * @param $accessKeySecret string AccessKeySecret
? ? * @param $domain string API接口所在域名
? ? * @param $params array API具體參數(shù)
? ? * @param $security boolean 使用https
? ? * @param $method boolean 使用GET或POST方法請(qǐng)求,VPC僅支持POST
? ? * @return bool|\stdClass 返回API接口調(diào)用結(jié)果豹悬,當(dāng)發(fā)生錯(cuò)誤時(shí)返回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) {
? ? ? ? ? ? // 大多由設(shè)置等原因引起葵陵,一般無法保障后續(xù)邏輯正常執(zhí)行,
? ? ? ? ? ? // 所以這里觸發(fā)的是E_USER_ERROR瞻佛,會(huì)終止腳本執(zhí)行脱篙,無法被try...catch捕獲,需要用戶排查環(huán)境、網(wǎng)絡(luò)等故障
? ? ? ? ? ? trigger_error("[CURL_" . curl_errno($ch) . "]: " . curl_error($ch), E_USER_ERROR);
? ? ? ? }
? ? ? ? curl_close($ch);
? ? ? ? return $rtn;
? ? }
}