網易雲 短信驗證碼+驗證+tp5

廢話不說 直接上代碼php

PHP部分git

1.ServerAPI.php(這是網易雲短信文檔裏面的代碼,直接複製存在本地而後改了一些 僅供參考)數據庫

<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/8
 * Time: 15:15
 */

namespace app\api\controller;


class ServerApi
{
    private $AppKey;
    private $AppSecret;
    private $Nonce; //隨機數(最大長度128個字符)
    private $CurTime; //當前UTC時間戳,從1970年1月1日0點0 分0 秒開始到如今的秒數(String)
    private $CheckSum;//SHA1(AppSecret + Nonce + CurTime),三個參數拼接的字符串,進行SHA1哈希計算,轉化成16進制字符(String,小寫)
    const   HEX_DIGITS = "0123456789abcdef";

    /**
     * 參數初始化
     * @param $AppKey
     * @param $AppSecret
     * @param $RequestType [選擇php請求方式,fsockopen或curl,若爲curl方式,請檢查php配置是否開啓]
     */
    public function __construct($AppKey,$AppSecret,$RequestType='curl'){
        $this->AppKey    = $AppKey;
        $this->AppSecret = $AppSecret;
        $this->RequestType = $RequestType;
    }

    /**
     * API checksum校驗生成
     * @param  void
     * @return $CheckSum(對象私有屬性)
     */
    public function checkSumBuilder(){
        //此部分生成隨機字符串
        $hex_digits = self::HEX_DIGITS;
        $this->Nonce;
        for($i=0;$i<128;$i++){          //隨機字符串最大128個字符,也能夠小於該數
            $this->Nonce.= $hex_digits[rand(0,15)];
        }
        $this->CurTime = time();  //當前時間戳,以秒爲單位

        $join_string = $this->AppSecret.$this->Nonce.$this->CurTime;
        $this->CheckSum = sha1($join_string);
    }

    /**
     * 將json字符串轉化成php數組
     * @param  $json_str
     * @return $json_arr
     */
    public function json_to_array($json_str){
        if(is_null(json_decode($json_str))){
            $json_str = $json_str;
        }else{
            $json_str = json_decode($json_str);
        }
        $json_arr=array();

        foreach($json_str as $k=>$w){
            if(is_object($w)){
                $json_arr[$k]= $this->json_to_array($w); //判斷類型是否是object
            }else if(is_array($w)){
                $json_arr[$k]= $this->json_to_array($w);
            }else{
                $json_arr[$k]= $w;
            }
        }
        return $json_arr;
    }

    /**
     * 使用CURL方式發送post請求
     * @param  $url     [請求地址]
     * @param  $data    [array格式數據]
     * @return $請求返回結果(array)
     */
    public function postDataCurl($url,$data){
        $this->checkSumBuilder();//發送請求前需先生成checkSum

        $timeout = 5000;
        $http_header = array(
            'AppKey:'.$this->AppKey,
            'Nonce:'.$this->Nonce,
            'CurTime:'.$this->CurTime,
            'CheckSum:'.$this->CheckSum,
            'Content-Type:application/x-www-form-urlencoded;charset=utf-8'
        );
        $postdata = '';
        foreach ($data as $key=>$value){
            $postdata.= ($key.'='.$value.'&');
        }
        $ch = curl_init();
        curl_setopt ($ch, CURLOPT_URL, $url);
        curl_setopt ($ch, CURLOPT_POST, 1);
        curl_setopt ($ch, CURLOPT_POSTFIELDS, $postdata);
        curl_setopt ($ch, CURLOPT_HEADER, false );
        curl_setopt ($ch, CURLOPT_HTTPHEADER,$http_header);
        curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER,false); //處理http證書問題
        curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);

        $result = curl_exec($ch);
        if (false === $result) {
            $result =  curl_errno($ch);
        }
        curl_close($ch);
        return $this->json_to_array($result) ;
    }

    /**
     * 使用FSOCKOPEN方式發送post請求
     * @param  $url     [請求地址]
     * @param  $data    [array格式數據]
     * @return $請求返回結果(array)
     */
    public function postDataFsockopen($url,$data){
        $this->checkSumBuilder();//發送請求前需先生成checkSum

        $postdata = '';
        foreach ($data as $key=>$value){
            $postdata.= ($key.'='.urlencode($value).'&');
        }
        // building POST-request:
        $URL_Info=parse_url($url);
        if(!isset($URL_Info["port"])){
            $URL_Info["port"]=80;
        }
        $request = '';
        $request.="POST ".$URL_Info["path"]." HTTP/1.1\r\n";
        $request.="Host:".$URL_Info["host"]."\r\n";
        $request.="Content-type: application/x-www-form-urlencoded;charset=utf-8\r\n";
        $request.="Content-length: ".strlen($postdata)."\r\n";
        $request.="Connection: close\r\n";
        $request.="AppKey: ".$this->AppKey."\r\n";
        $request.="Nonce: ".$this->Nonce."\r\n";
        $request.="CurTime: ".$this->CurTime."\r\n";
        $request.="CheckSum: ".$this->CheckSum."\r\n";
        $request.="\r\n";
        $request.=$postdata."\r\n";

        print_r($request);
        $fp = fsockopen($URL_Info["host"],$URL_Info["port"]);
        fputs($fp, $request);
        $result = '';
        while(!feof($fp)) {
            $result .= fgets($fp, 128);
        }
        fclose($fp);

        $str_s = strpos($result,'{');
        $str_e = strrpos($result,'}');
        $str = substr($result, $str_s,$str_e-$str_s+1);
        print_r($result);
        return $this->json_to_array($str);
    }

    /**
     * 發送短信驗證碼
     * @param  $templateid    [模板編號(由客服配置以後告知開發者)]
     * @param  $mobile       [目標手機號]
     * @param  $deviceId     [目標設備號,可選參數]
     * @return $codeLen      [驗證碼長度,範圍4~10,默認爲4]
     */
    public function sendSmsCode($templateid,$mobile,$deviceId='',$codeLen){
        $url = 'https://api.netease.im/sms/sendcode.action';
        $data= array(
            'templateid' => $templateid,
            'mobile' => $mobile,
            'deviceId' => $deviceId,
            'codeLen' => $codeLen
        );
        if($this->RequestType=='curl'){
            $result = $this->postDataCurl($url,$data);
        }else{
            $result = $this->postDataFsockopen($url,$data);
        }
        return $result;
    }



    /**
     * 發送模板短信
     * @param  $templateid       [模板編號(由客服配置以後告知開發者)]
     * @param  $mobiles          [驗證碼]
     * @param  $params          [短信參數列表,用於依次填充模板,JSONArray格式,如["xxx","yyy"];對於不包含變量的模板,不填此參數表示模板即短信全文內容]
     * @return $result      [返回array數組對象]
     */
    public function sendSMSTemplate($templateid,$mobiles=array(),$params=''){
        $url = 'https://api.netease.im/sms/sendtemplate.action';
        $data= array(
            'templateid' => $templateid,
            'mobiles' => json_encode($mobiles),
            'params' => json_encode($params)
        );
        if($this->RequestType=='curl'){
            $result = $this->postDataCurl($url,$data);
        }else{
            $result = $this->postDataFsockopen($url,$data);
        }
        return $result;
    }
}

2. 發送短信的方法json

    
 //設置兩個常量 你也能夠存進數據庫而後從數據庫讀取 均可以
  const APP_KEY = '網易雲給你的key';   const APP_SECRET = 'key所對應的密鑰';
  //發送短信的方法
public function SendMsg(){ $AppKey = self::APP_KEY;     //網易雲信分配的帳號,請替換你在管理後臺應用下申請的appSecret $AppSecret = self::APP_SECRET; $p = new ServerAPI($AppKey,$AppSecret,'curl'); //fsockopen僞造請求 $phone = input('phone');     //發送短信驗證碼 $result = $p->sendSmsCode('3882687',"$phone",'','6'); //參數:第一個是短信模板,在網易雲的系統後臺看;第二個是接收驗證碼短信(或者語言電話),第四個參數是驗證碼位數 if($result['code']==200){ $code = $result['obj']; session('code',$code); $this->success('短信發送成功,請注意接聽語言驗證碼'); }else{ $this->error('短信發送失敗'); } }

3.檢測用戶輸入的驗證碼和session儲存的驗證碼是否一致api

    public function msg(){
        if(request()->isAjax()){
            if(!session('?code')){
                $this->error('沒有code');
            }else{
                $code = input('post.code');
                $relCode = session('code');
                if($code!=$relCode){
                    $this->error('驗證碼錯誤');
//                    return ['code'=>'2','msg'=>'驗證碼錯誤'];
                }else{
                    $_SESSION['obj']='';
                    $this->success('驗證碼正確');
//                    return ['code'=>'1','msg'=>'驗證碼正確'];
                }
            }
        }
        return $this->fetch();
    }

以上代碼僅供參考,須要按照實際狀況修改數組

相關文章
相關標籤/搜索