短信視乎已經被慢慢淡出日常的交流工具隊列,但始終抹不去它的存在,短信驗證碼視乎從未被取代,此外在重要的信息通知的地位也是不可取的的。因此瞭解短信的使用是開發中頗有必要的一環。json
騰訊雲的短信服務提供有100條內免費,因此方便開發測試。app
https://console.cloud.tencent.com/smsdom
https://cloud.tencent.com/document/product/382/13410curl
提供了多種語言的SDK工具
實現短信模板的單次發送post
1 /** 2 * @param string $nationCode 國家碼,如 86 爲中國 3 * @param string $phoneNumber 不帶國家碼的手機號 4 * @param int $templId 模板 id 5 * @param array $params 模板參數列表,如模板 {1}...{2}...{3},那麼須要帶三個參數 6 * @param string $sign 簽名,若是填空串,系統會使用默認簽名 7 * @param string $extend 擴展碼,可填空串 8 * @param string $ext 服務端原樣返回的參數,可填空串 9 * @return string 應答json字符串,詳細內容參見騰訊雲協議文檔 10 */ 11 function sendWithParam($nationCode, $phoneNumber, $templId = 0, $params, $sign = "", $extend = "", $ext = ""){ 12 13 $appid = 1400xxx; //本身的短信appid 14 $appkey = "d80axxxxx"; //本身的短信appkey 15 16 $random = rand(100000, 999999);//生成隨機數 17 $curTime = time(); 18 $wholeUrl = "https://yun.tim.qq.com/v5/tlssmssvr/sendsms". "?sdkappid=" . $appid . "&random=" . $random; 19 20 // 按照協議組織 post 包體 21 $data = new \stdClass();//建立一個沒有成員方法和屬性的空對象 22 $tel = new \stdClass(); 23 $tel->nationcode = "".$nationCode; 24 $tel->mobile = "".$phoneNumber; 25 $data->tel = $tel; 26 $data->sig=hash("sha256", "appkey=".$appkey."&random=".$random."&time=".$curTime."&mobile=".$phoneNumber);// 生成簽名 27 $data->tpl_id = $templId; 28 $data->params = $params; 29 $data->sign = $sign; 30 $data->time = $curTime; 31 $data->extend = $extend; 32 $data->ext = $ext; 33 34 return sendCurlPost($wholeUrl, $data); 35 } 36 /** 37 * 發送請求 38 * 39 * @param string $url 請求地址 40 * @param array $dataObj 請求內容 41 * @return string 應答json字符串 42 */ 43 function sendCurlPost($url, $dataObj){ 44 $curl = curl_init(); 45 curl_setopt($curl, CURLOPT_URL, $url); 46 curl_setopt($curl, CURLOPT_HEADER, 0); 47 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); 48 curl_setopt($curl, CURLOPT_POST, 1); 49 curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 60); 50 curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($dataObj)); 51 curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); 52 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); 53 $ret = curl_exec($curl); 54 if (false == $ret) { 55 // curl_exec failed 56 $result = "{ \"result\":" . -2 . ",\"errmsg\":\"" . curl_error($curl) . "\"}"; 57 } else { 58 $rsp = curl_getinfo($curl, CURLINFO_HTTP_CODE); 59 if (200 != $rsp) { 60 $result = "{ \"result\":" . -1 . ",\"errmsg\":\"". $rsp 61 . " " . curl_error($curl) ."\"}"; 62 } else { 63 $result = $ret; 64 } 65 } 66 curl_close($curl); 67 68 return $result; 69 }
測試代碼:測試
1 function xx(){ 2 $templId = 286xxx; //本身短信模板id 3 $phoneNumber1="159xxxxx";//接受短信手機號碼 4 try { 5 //模板佔位數據 6 $params = array("數據1","數據2"); 7 $result = sendWithParam("86", $phoneNumber1, $templId,$params, "", "", ""); 8 echo $result;//輸出成功的json結果 9 } catch(\Exception $e) { 10 echo var_dump($e);//輸出異常信息 11 } 12 }