PHP之封裝夢網雲通訊短信發送類

PHP夢網雲通訊API版本

<?php
/**
 * Created by PhpStorm.
 * User: Trevor Lan
 * Date: 2020/3/20 0020
 * Time: 17:40
 */

namespace app\v1\controller;


class Message
{
    /**
     * API請求地址
     */
    private $BaseUrl;


    public $ERROR_310099=-310099;//http請求失敗錯誤碼

    public function  __construct($BaseUrl)
    {
        if (!empty($BaseUrl)) {
            $this->BaseUrl = $BaseUrl;
        } else {
            throw new Exception("API請求地址錯誤");
        }
    }

    /**
     * 密碼加密
     * $userid:用戶賬號
     * $pwd:用戶密碼
     */
    public function encrypt_pwd($userid, $pwd)
    {
        try {
            $char = '00000000';//固定字符串
            $time = date('mdHis', time());//時間戳
            $pwd = md5($userid . $char . $pwd . $time);//拼接字符串進行加密
            return array('pwd' => $pwd, 'time' => $time);
        } catch (Exception $e) {
            print_r($e->getMessage());  //輸出捕獲的異常消息
        }
    }
    /**
     * 短信內容加密
     * $content:短信內容
     */
    public function encrypt_content($content)
    {
        try {
            return urlencode(iconv('UTF-8', 'GBK', $content));//短信內容轉化爲GBK格式再進行urlencode格式加密
        }catch (Exception $e) {
            print_r($e->getMessage());  //輸出捕獲的異常消息
        }
    }

    /**
     * 短連接請求方法
     * $url:請求地址
     * $post_data:請求數據
     */
    private function connection($url,$post_data)
    {
        try {
            $attributes = array('Accept:text/plain;charset=utf-8', 'Content-Type:application/json', 'charset=utf-8', 'Expect:', 'Connection: Close');//請求屬性
            $ch = curl_init();//初始化一個會話
            /* 設置驗證方式 */
            curl_setopt($ch, CURLOPT_HTTPHEADER, $attributes);//設置訪問
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//設置返回結果爲流
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);//設置請求超時時間
            curl_setopt($ch, CURLOPT_TIMEOUT, 60);//設置響應超時時間
            /* 設置通信方式 */
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);//使用urlencode格式請求

            $result = curl_exec($ch);//獲取返回結果集
            $result=preg_replace('/\"msgid":(\d{1,})./', '"msgid":"\\1",', $result);//正則表達式匹配所有msgid轉化爲字符串
            $result = json_decode($result, true);//將返回結果集json格式解析轉化爲數組格式
            if (curl_errno($ch) !== 0) //網絡問題請求失敗
            {
                $result['result'] = $this->ERROR_310099;
                curl_close($ch);//關閉請求會話
                return $result;
            } else {
                $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                if ($statusCode != 200||!isset($result['result']))//域名問題請求失敗或不存在返回結果
                {
                    $result='';//清空result集合
                    $result['result'] = $this->ERROR_310099;
                }
                curl_close($ch);//關閉請求會話
                return $result;
            }
        } catch (Exception $e) {
            print_r($e->getMessage());//輸出捕獲的異常消息
            $result['result'] = $this->ERROR_310099;//返回http請求錯誤代碼
            return $result;
        }
    }

    /*
    * 單條發送
     * $data:請求數據集合
    */
    public function singleSend($data)
    {
        try {
            $data['userid'] = strtoupper($data['userid']);//用戶名轉化爲大寫
            $encrypt=$this->encrypt_pwd($data['userid'],$data['pwd']);//密碼進行MD5加密
            $data['pwd']=$encrypt['pwd'];//獲取MD5加密後的密碼
            $data['timestamp']=$encrypt['time'];//獲取加密時間戳
            $data['content'] = $this->encrypt_content($data['content']);//短信內容進行urlencode加密
            $post_data = json_encode($data);//將數組轉化爲JSON格式
            $result = $this->connection($this->BaseUrl.'single_send',$post_data);//根據請求類型進行請求
            return $result;//返回請求結果
        }catch (Exception $e) {
            print_r($e->getMessage());  //輸出捕獲的異常消息
        }
    }

    /*
   * 相同內容羣發
    * $data:請求數據集合
   */
    public function batchSend($data)
    {
        try{
            $data['userid']=strtoupper($data['userid']);//用戶名轉化爲大寫
            $encrypt=$this->encrypt_pwd($data['userid'],$data['pwd']);//密碼進行MD5加密
            $data['pwd']=$encrypt['pwd'];//獲取MD5加密後的密碼
            $data['timestamp']=$encrypt['time'];//獲取加密時間戳
            $data['content']=$this->encrypt_content($data['content']);//短信內容進行urlencode加密
            $post_data=json_encode($data);//將數組轉化爲JSON格式
            $result = $this->connection($this->BaseUrl.'batch_send',$post_data);//根據請求類型進行請求
            return $result;
        }catch (Exception $e) {
            print_r($e->getMessage());  //輸出捕獲的異常消息
        }
    }

    /*
    * 個性化內容羣發
     * $data:請求數據集合
    */
    public function multiSend($data)
    {
        try{
            $data['userid']=strtoupper($data['userid']);//用戶名轉化爲大寫
            $encrypt=$this->encrypt_pwd($data['userid'],$data['pwd']);//密碼進行MD5加密
            $data['pwd']=$encrypt['pwd'];//獲取MD5加密後的密碼
            $data['timestamp']=$encrypt['time'];//獲取加密時間戳
            foreach($data['multimt'] as $k=>$v)
            {
                $data['multimt'][$k]['content'] = $this->encrypt_content($v['content']);//每一條個性化的短信內容進行urlencode加密
            }
            $post_data=json_encode($data);//將數組轉化爲JSON格式
            $result=$this->connection($this->BaseUrl.'multi_send',$post_data);//根據請求類型進行請求
            return $result;
        }catch (Exception $e) {
            print_r($e->getMessage());  //輸出捕獲的異常消息
        }
    }

    /*
   * 查詢餘額
    * $data:請求數據集合
   */
    public function getBalance($data)
    {
        try{
            $data['userid']=strtoupper($data['userid']);//用戶名轉化爲大寫
            $encrypt=$this->encrypt_pwd($data['userid'],$data['pwd']);//密碼進行MD5加密
            $data['pwd']=$encrypt['pwd'];//獲取MD5加密後的密碼
            $data['timestamp']=$encrypt['time'];//獲取加密時間戳
            $post_data=json_encode($data);//將數組轉化爲JSON格式
            $result=$this->connection($this->BaseUrl.'get_balance',$post_data);//根據請求類型進行請求
            return $result;
        }catch (Exception $e) {
            print_r($e->getMessage());  //輸出捕獲的異常消息
        }
    }

    /*
     * 請求獲取上行
     * $requestPath:請求地址
     * $data:請求數據集合
     * $isEncryptPwd:是否加密
    */
    public function getMo($data)
    {
        try{
            $data['userid']=strtoupper($data['userid']);//用戶名轉化爲大寫
            $encrypt=$this->encrypt_pwd($data['userid'],$data['pwd']);//密碼進行MD5加密
            $data['pwd']=$encrypt['pwd'];//獲取MD5加密後的密碼
            $data['timestamp']=$encrypt['time'];//獲取加密時間戳
            $post_data = json_encode($data);//將數組轉化爲JSON格式
            $result=$this->connection($this->BaseUrl.'get_mo',$post_data);//根據請求類型進行請求
            return $result;//返回請求結果
        }catch (Exception $e) {
            print_r($e->getMessage());  //輸出捕獲的異常消息
        }
    }

    /*
  * 請求獲取狀態報告
  * $requestPath:請求地址
  * $data:請求數據集合
  * $isEncryptPwd:是否加密
 */
    public function getRpt($data)
    {
        try{
            $data['userid']=strtoupper($data['userid']);//用戶名轉化爲大寫
            $encrypt=$this->encrypt_pwd($data['userid'],$data['pwd']);//密碼進行MD5加密
            $data['pwd']=$encrypt['pwd'];//獲取MD5加密後的密碼
            $data['timestamp']=$encrypt['time'];//獲取加密時間戳
            $post_data = json_encode($data);//將數組轉化爲JSON格式
            $result=$this->connection($this->BaseUrl.'get_rpt',$post_data);//根據請求類型進行請求
            return $result;
        }catch (Exception $e) {
            print_r($e->getMessage());  //輸出捕獲的異常消息
        }
    }

}

 

封裝信息發送類

<?php
/**
 * Created by PhpStorm.
 * User: Trevor Lan
 * Date: 2020/3/20 0020
 * Time: 17:40
 */

namespace app\v1\controller;


class SendMessage
{
    public $url;
    public $smsSendConn;
    public $data = [];

    public function __construct()
    {
        $this->url = 'http://IP或域名:端口/sms/v2/std/';
        $this->data['userid'] = '****';
        $this->data['pwd'] = '****';
        $this->smsSendConn = new Message($this->url);
    }

    /**
     * 發送單條信息
     * @return bool|false|string
     */
    public function singleSend($phone)
    {
        
        $this->data['mobile'] =$phone;

        // 隨機數
        $rand=rand(100000,999999);


        //設置發送短信內容(必填)
        $this->data['content'] ='您的驗證碼是'.$rand.',在5分鐘內輸入有效。如非本人操作請忽略此短信。';
        // 業務類型(可選)
        $this->data['svrtype'] = '';
        // 設置擴展號(可選)
        $this->data['exno'] = '';
        //用戶自定義流水編號(可選)
        $this->data['custid'] = '';
        // 自定義擴展數據(可選)
        $this->data['exdata'] = '';

        try {
            $result = $this->smsSendConn->singleSend($this->data);
            if ($result['result'] === 0) {
                //print_r("單條信息發送成功!");
                $res=[
                    'state'=>1,
                    'msg'=>'Code send success'
                ];
                return json_encode($res);
            } else {
                // print_r("單條信息發送失敗,錯誤碼:" . $result['result']);
                $res=[
                    'state'=>0,
                    'msg'=>'Code send fail'
                ];
                return json_encode($res);
            }
        } catch (Exception $e) {
            print_r($e->getMessage());//輸出捕獲的異常消息,請根據實際情況,添加異常處理代碼
            return false;
        }
    }

    /**
     * 短信剩餘量
     * @return bool
     */
    public function getMessageCount(){
        try {
            $result = $this->smsSendConn->getBalance($this->data);
            if ($result['result'] === 0) {
                if ($result['chargetype'] === 0) {
                    print_r("查詢成功,當前計費模式爲條數計費,剩餘條數爲:" . $result['balance']);
                } else if ($result['chargetype'] === 1) {
                    print_r("查詢成功,當前計費模式爲金額計費,剩餘金額爲:" . $result['money']."元");
                } else {
                    print_r("未知的計費類型");
                }
            } else {
                print_r("查詢餘額失敗,錯誤碼:" . $result['result']);
            }
        }catch (Exception $e) {
            print_r($e->getMessage());//輸出捕獲的異常消息,請根據實際情況,添加異常處理代碼
            return false;
        }
    }

    /**
     * 獲取上行消息
     * @return bool
     */
    public function getUserMessa(){
        $data['retsize']=100;
        try {
            $result = $this->smsSendConn->getMo($this->data);
            if($result['result']===0)
            {
                foreach($result['mos'] as $k=>$v)
                {
                    $result['mos'][$k]['content']=urldecode($v['content']);//將內容進行utf-8解碼
                }
                print_r("獲取上行成功");
                print_r($result['mos']);
            }
            else
            {
                print_r("獲取上行失敗,錯誤碼:" .$result['result']);
            }
        }catch (Exception $e) {
            print_r($e->getMessage());//輸出捕獲的異常消息,請根據實際情況,添加異常處理代碼
            return false;
        }
    }

    /**
     * 獲取發送報告
     * @return bool
     */
    public function getSendReport(){
        $data['retsize']=100;
        try {
            $result = $this->smsSendConn->getRpt($this->data);//獲取狀態報告
            if($result['result']===0)
            {
                print_r("獲取狀態報告成功");
                print_r($result['rpts']);//輸出狀態報告信息
            }
            else
            {
                print_r("獲取狀態報告失敗,錯誤碼:" .$result['result']);
            }
        }catch (Exception $e) {
            print_r($e->getMessage());//輸出捕獲的異常消息,請根據實際情況,添加異常處理代碼
            return false;
        }
    }

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章