1. 程式人生 > >thinkphp5使用容聯傳送簡訊驗證碼

thinkphp5使用容聯傳送簡訊驗證碼

thinkphp5開發的時候需要用到簡訊驗證碼,在官網下載下來demo後,不放入thinkphp框架中能正常執行,但是放入框架中出現了很多錯誤,直接貼上配置好的程式碼吧,特別注意的是,demo程式碼中有new stdClass();但是框架報錯not found,經過除錯,找到的解決辦法是將new stdClass();改為new \stdClass();就可以了,只是在stdClass前面加了一個反斜槓‘\’我把容聯的demo放到框架的extend目錄下,修改後的程式碼如下:

1.SendCode.php

<?php
/*
 *  Copyright (c) 2014 The CCP project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a Beijing Speedtong Information Technology Co.,Ltd license
 *  that can be found in the LICENSE file in the root of the web site.
 *
 *   http://www.yuntongxun.com
 *
 *  An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */
namespace verify;
class SendCode
{

    //主帳號,對應開官網發者主賬號下的 ACCOUNT SID
    private $accountSid = '你自己容聯的ACCOUNT SID';

    //主帳號令牌,對應官網開發者主賬號下的 AUTH TOKEN
    private $accountToken = '你自己容聯的AUTH TOKEN';

    //應用Id,在官網應用列表中點選應用,對應應用詳情中的APP ID
    //在開發除錯的時候,可以使用官網自動為您分配的測試Demo的APP ID
    private $appId = '你自己容聯的App ID';

    //請求地址
    //沙盒環境(用於應用開發除錯):sandboxapp.cloopen.com
    //生產環境(使用者應用上線使用):app.cloopen.com
    private $serverIP = 'sandboxapp.cloopen.com';


    //請求埠,生產環境和沙盒環境一致
    private $serverPort = '8883';

    //REST版本號,在官網文件REST介紹中獲得。
    private $softVersion = '2013-12-26';

    /**
     * 傳送模板簡訊
     * @param to 手機號碼集合,用英文逗號分開
     * @param datas 內容資料 格式為陣列 例如:array('Marry','Alon'),如不需替換請填 null
     * @param $tempId 模板Id,測試應用和未上線應用使用測試模板請填寫1,正式應用上線後填寫已申請稽核通過的模板ID
     */
    function sendTemplateSMS($to, $datas, $tempId)
    {
        // 初始化REST SDK
        $rest = new REST($this->serverIP, $this->serverPort, $this->softVersion);
        $rest->setAccount($this->accountSid, $this->accountToken);
        $rest->setAppId($this->appId);

        // 傳送模板簡訊
        echo "Sending TemplateSMS to $to <br/>";
        $result = $rest->sendTemplateSMS($to, $datas, $tempId);
        if ($result == NULL) {
            echo "result error!";
        }
        if ($result->statusCode != 0) {
            echo "error code :" . $result->statusCode . "<br>";
            echo "error msg :" . $result->statusMsg . "<br>";
            //TODO 新增錯誤處理邏輯
        } else {
            echo "Sendind TemplateSMS success!<br/>";
            // 獲取返回資訊
            $smsmessage = $result->TemplateSMS;
            echo "dateCreated:" . $smsmessage->dateCreated . "<br/>";
            echo "smsMessageSid:" . $smsmessage->smsMessageSid . "<br/>";
            //TODO 新增成功處理邏輯
        }
    }

}

2.REST.php

<?php
/*
 *  Copyright (c) 2014 The CCP project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a Beijing Speedtong Information Technology Co.,Ltd license
 *  that can be found in the LICENSE file in the root of the web site.
 *
 *   http://www.yuntongxun.com
 *
 *  An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */
namespace verify;
class REST {
	private $AccountSid;
	private $AccountToken;
	private $AppId;
	private $ServerIP;
	private $ServerPort;
	private $SoftVersion;
	private $Batch;  //時間戳
	private $BodyType = "xml";//包體格式,可填值:json 、xml
	private $enabeLog = true; //日誌開關。可填值:true、
	private $Filename="./log.txt"; //日誌檔案
	private $Handle;
	function __construct($ServerIP,$ServerPort,$SoftVersion)	
	{
		$this->Batch = date("YmdHis");
		$this->ServerIP = $ServerIP;
		$this->ServerPort = $ServerPort;
		$this->SoftVersion = $SoftVersion;
    $this->Handle = fopen($this->Filename, 'a');
	}

   /**
    * 設定主帳號
    * 
    * @param AccountSid 主帳號
    * @param AccountToken 主帳號Token
    */    
    function setAccount($AccountSid,$AccountToken){
      $this->AccountSid = $AccountSid;
      $this->AccountToken = $AccountToken;   
    }
    
    
   /**
    * 設定應用ID
    * 
    * @param AppId 應用ID
    */
    function setAppId($AppId){
       $this->AppId = $AppId; 
    }
    
   /**
    * 列印日誌
    * 
    * @param log 日誌內容
    */
    function showlog($log){
      if($this->enabeLog){
         fwrite($this->Handle,$log."\n");  
      }
    }
    
    /**
     * 發起HTTPS請求
     */
     function curl_post($url,$data,$header,$post=1)
     {
       //初始化curl
       $ch = curl_init();
       //引數設定  
       $res= curl_setopt ($ch, CURLOPT_URL,$url);  
       curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
       curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
       curl_setopt ($ch, CURLOPT_HEADER, 0);
       curl_setopt($ch, CURLOPT_POST, $post);
       if($post)
          curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
       curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
       curl_setopt($ch,CURLOPT_HTTPHEADER,$header);
       $result = curl_exec ($ch);
       //連線失敗
       if($result == FALSE){
          if($this->BodyType=='json'){
             $result = "{\"statusCode\":\"172001\",\"statusMsg\":\"網路錯誤\"}";
          } else {
             $result = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><Response><statusCode>172001</statusCode><statusMsg>網路錯誤</statusMsg></Response>"; 
          }    
       }

       curl_close($ch);
       return $result;
     } 

   
    
   /**
    * 傳送模板簡訊
    * @param to 簡訊接收彿手機號碼集合,用英文逗號分開
    * @param datas 內容資料
    * @param $tempId 模板Id
    */       
    function sendTemplateSMS($to,$datas,$tempId)
    {
        //主帳號鑑權資訊驗證,對必選引數進行判空。
        $auth=$this->accAuth();
        if($auth!=""){
            return $auth;
        }
        // 拼接請求包體
        if($this->BodyType=="json"){
           $data="";
           for($i=0;$i<count($datas);$i++){
              $data = $data. "'".$datas[$i]."',"; 
           }
           $body= "{'to':'$to','templateId':'$tempId','appId':'$this->AppId','datas':[".$data."]}";
        }else{
           $data="";
           for($i=0;$i<count($datas);$i++){
              $data = $data. "<data>".$datas[$i]."</data>"; 
           }
           $body="<TemplateSMS>
                    <to>$to</to> 
                    <appId>$this->AppId</appId>
                    <templateId>$tempId</templateId>
                    <datas>".$data."</datas>
                  </TemplateSMS>";
        }
        $this->showlog("request body = ".$body);
        // 大寫的sig引數 
        $sig =  strtoupper(md5($this->AccountSid . $this->AccountToken . $this->Batch));
        // 生成請求URL        
        $url="https://$this->ServerIP:$this->ServerPort/$this->SoftVersion/Accounts/$this->AccountSid/SMS/TemplateSMS?sig=$sig";
        $this->showlog("request url = ".$url);
        // 生成授權:主帳戶Id + 英文冒號 + 時間戳。
        $authen = base64_encode($this->AccountSid . ":" . $this->Batch);
        // 生成包頭  
        $header = array("Accept:application/$this->BodyType","Content-Type:application/$this->BodyType;charset=utf-8","Authorization:$authen");
        // 傳送請求
        $result = $this->curl_post($url,$body,$header);
        $this->showlog("response body = ".$result);
        if($this->BodyType=="json"){//JSON格式
           $datas=json_decode($result); 
        }else{ //xml格式
           $datas = simplexml_load_string(trim($result," \t\n\r"));
        }
      //  if($datas == FALSE){
//            $datas = new stdClass();
//            $datas->statusCode = '172003';
//            $datas->statusMsg = '返回包體錯誤'; 
//        }
        //重新裝填資料
        if($datas->statusCode==0){
         if($this->BodyType=="json"){
            $datas->TemplateSMS =$datas->templateSMS;
            unset($datas->templateSMS);   
          }
        }
 
        return $datas; 
    } 
   
  /**
    * 主帳號鑑權
    */   
   function accAuth()
   {
       if($this->ServerIP==""){
            $data = new \stdClass();
            $data->statusCode = '172004';
            $data->statusMsg = 'IP為空';
          return $data;
        }
        if($this->ServerPort<=0){
            $data = new \stdClass();
            $data->statusCode = '172005';
            $data->statusMsg = '埠錯誤(小於等於0)';
          return $data;
        }
        if($this->SoftVersion==""){
            $data = new \stdClass();
            $data->statusCode = '172013';
            $data->statusMsg = '版本號為空';
          return $data;
        } 
        if($this->AccountSid==""){
            $data = new \stdClass();
            $data->statusCode = '172006';
            $data->statusMsg = '主帳號為空';
          return $data;
        }
        if($this->AccountToken==""){
            $data = new \stdClass();
            $data->statusCode = '172007';
            $data->statusMsg = '主帳號令牌為空';
          return $data;
        }
        if($this->AppId==""){
            $data = new \stdClass();
            $data->statusCode = '172012';
            $data->statusMsg = '應用ID為空';
          return $data;
        }   
   }
}

3.thinkphp5框架預設的index控制器程式碼(Index.php)

<?php
namespace app\index\controller;
use verify\SendCode;
class Index
{
    public function index()
    {
        $Rest = new SendCode();
        $Rest->sendTemplateSMS("電話號碼",array('驗證碼','有效時間'),"1");
    }
}

將上訴程式碼複製到自己的框架中,修改SendCode.php中的$accountSid、$authToken、$appId,Index.php中填入接收驗證碼的手機號、要傳送的驗證碼、驗證碼有效時間即可,訪問控制器index的index方法即可執行成功。下面是程式碼結構圖


相關推薦

thinkphp5使用傳送簡訊驗證

thinkphp5開發的時候需要用到簡訊驗證碼,在官網下載下來demo後,不放入thinkphp框架中能正常執行,但是放入框架中出現了很多錯誤,直接貼上配置好的程式碼吧,特別注意的是,demo程式碼中有new stdClass();但是框架報錯not found,經過除錯,找

js模擬支付寶傳送簡訊驗證&&&&簡訊倒計時

html <div class="pwdContent"> <div class="pwdBox"></div> <div class="pwdErrorPoint">請輸入數字!</div></div>js // 簡訊驗

1-22.如何傳送簡訊驗證之Laravel框架

簡訊驗證碼的應用場景: 應用場景:簡訊註冊  密碼找回  簡訊通知 場景一:註冊 場景二:賬號繫結手機號 場景三:登陸 簡訊實現原理: 發起請求  =》  簡訊API介面流程處理  =》接收結果 簡訊

傳送簡訊驗證 倒計時

 1、頁面樣式:基於bootstrap  1 <div class="form-group"> 2 <label class="col-md-4 control-label">手機號碼</

如何傳送簡訊驗證之laravel框架

​ 簡訊驗證碼的應用場景: 應用場景:簡訊註冊  密碼找回  簡訊通知 場景一:註冊 場景二:賬號繫結手機號 場景三:登陸 簡訊實現原理: 發起請求  =》  簡訊API介面流程處理  =》接收結果 簡訊平臺網址:http://www.

【Python web 開發】雲片網傳送簡訊驗證

傳送簡訊驗證碼 是要使用第三方服務的,運營商是不可能提供對外的個人傳送簡訊服務功能,我們本身也沒有能力去傳送驗證碼,雲片網是目前提供這種服務使用率較高的服務商之一 我們先來看下雲片網國內單條傳送簡訊的api    根據api 寫了一個指令碼,這個appkey 我還沒申請 如

網易雲傳送簡訊驗證java實現

首先,登陸網易雲信註冊賬號然後獲取自己的App Key與App Secret,這裡就不多說了,可以自行百度。 在服務端API中我們可以很容易的找到這段程式碼,這是用來加密用的(關於如何加密也可以找到) import java.security.MessageDiges

傳送簡訊驗證後60秒倒計時

jquery實現的傳送簡訊驗證碼後60秒倒計時功能,完整例項可到http://smsow.zhenzikj.com/doc/sdk.html 下載"註冊驗證碼"的demo。 直接下載:java版: http://smsow.zhenzikj.com/demo/download.html?

小程式開發 —— 傳送簡訊驗證獲取倒計時效果

在小程式開發過程中如何實現簡訊驗證碼功能呢? 主要有兩種方法: 一、 使用小程式的 wx.getPhoneNumber 介面獲取簡訊驗證碼 微信小程式提供了 wx.getPhoneNumber api

celery非同步任務傳送簡訊驗證

1.在專案中建立celery_tasks包 2.在celery_tasks目錄下建立config.py檔案,用於儲存celery的配置資訊 broker_url = "redis://127.0.0.1

python利用第三方模組,傳送簡訊驗證

對於初學者,如何利用第三方python開發包傳送簡訊驗證碼,下面是具體的實現和記錄過程! 環境:虛擬機器上centos7平臺,python3.7版本; 首先,申請賬號的部分就省略了  1. 獲得appid和appSecret 在"我的應用"-&

python3傳送簡訊驗證demo

對於初學者,如何利用第三方python開發包傳送簡訊驗證碼,下面是具體的實現和記錄過程! 環境:虛擬機器上centos7平臺,python3.7版本; 首先,申請賬號的部分就省略了  1. 獲得appid和appSecret 在"我的應用"-&

JS實現註冊登入傳送簡訊驗證動態顯示60S倒計時完整案例

通常在web專案中都會遇到賬戶註冊或者忘記密碼時需要傳送簡訊驗證碼的功能,雖然說這種功能很常見,但是實際開發過程中很多人還會遇到不少坑。筆者經過整理把最近專案中的用到的這個傳送簡訊驗證碼動態顯示60S倒計時的完整實現過程分享給廣大開發者朋友。 1、頁面傳送簡訊驗證碼的表

java整合阿里大於第三方平臺傳送簡訊驗證

閒話不多說,言歸正傳。今天我要分享的是利用阿里大魚實現網站和APP的簡訊驗證。 阿里大魚開放了很多的訊息通知服務,包括簡訊通知,語音通知等。 阿里大魚的簡訊傳送官方API:https://api.alidayu.com/doc2/apiDetail.htm?spm=a3142

java 實現傳送簡訊驗證功能

如何使用java + maven的專案環境傳送簡訊驗證碼,本文使用的是榛子云簡訊 的介面。 1. 安裝sdk 下載地址: http://smsow.zhenzikj.com/doc/sdk.html 下載下來是jar檔案,需要將jar釋出到本地的maven倉庫中, 在c

java向手機號傳送簡訊驗證

需要下載這三個jar包   commons-logging-1.1.1.jarcommons-httpclient-3.1.jarcommons-codec-1.4.jar 點選sms註冊才可以用簡訊驗證碼 1.註冊完畢就需要登入 2.登入完畢需要檢視簡訊金鑰 &

java後臺呼叫簡訊介面,實現傳送簡訊驗證的控制層實現

1.設計:使用者填寫手機號,點選獲取驗證碼按鈕,controller層獲得所要傳送驗證碼的手機號,隨機生成六位數的驗證碼。呼叫傳送簡訊介面url向此手機號傳送驗證碼。注意:下面的程式碼採用的是雲信使的簡訊驗證碼介面,不同的驗證碼更換不同的url格式,即可。 `

傳送簡訊驗證沒有判斷圖形驗證是否正確,被攻擊,臨時用nginx限制ip訪問

在專案中,註冊頁面上傳送簡訊驗證碼沒有判斷圖形驗證碼是否正確,就傳送驗證碼了,結果被攻擊了,nginx的access.log看到訪問的ip,並將訪問過多的ip選擇出來,臨時用nginx限制ip訪問。後面修改程式碼,重新發版。 但是,對於套了一層 CDN 或代理的網站,通過

傳送簡訊驗證時的倒計時功能

this.show = false; const TIME_COUNT = 60; if (!this.timer) { this.co

微信小程式傳送簡訊驗證完整例項

微信小程式註冊完整例項,傳送簡訊驗證碼,帶60秒倒計時功能,無需伺服器端。效果圖:   程式碼: index.wxml <!--index.wxml--> <view class="container"> <view class='row'&g