/*** 聚合数据短信验证码类*/class Phone{private $key = "";// AppKeypublic $mobile = "";// 手机号private $tpl_id = "";// 短信模板idprivate $code = "";// 验证码public $rands = "";// 随机数/*** 构造函数* @param int $phone 接受短信的手机号码*/public function __construct($phone) {$this->mobile = $phone;}/*** 获取AppKey* @return string AppKey*/private function keys(){return $this->key = '******************************';}/*** 获取短信模板id* @return string 短信模板id*/public function tpl() {return $this->tpl = '****';}/*** 随机拼接六位验证码* @return int 验证码*/public function rand(){return rand(100000, 999999);}/*** 获取验证码的值* @return string 验证码的值*/public function value() {$this->rands = $this->rand();return $this->value = '#code#='.$this->rands;}/*** 短信发送所需数据整合* @return array 短信所需数据*/public function match(){$smsConf = array('key' => $this->keys(), //您申请的APPKEY'mobile' => $this->mobile, //接受短信的用户手机号码'tpl_id' => $this->tpl(), //您申请的短信模板ID,根据实际情况修改'tpl_value' => $this->value() //您设置的模板变量,根据实际情况修改);return $smsConf;}/*** 短信接口的url* @return string 短信接口的url*/private function url(){return $url = '/sms/send';}/*** 发送短信* @return array 返回短信发送结果*/public function sendSms(){header('content-type:text/html;charset=utf-8');$sendUrl = $this->url();//短信接口的URL$smsConf = self::match();$content = self::juhecurl($sendUrl,$smsConf,1); //请求发送短信if($content){$result = json_decode($content,true);$error_code = $result['error_code'];if($error_code == 0){//状态为0,说明短信发送成功// echo "短信发送成功,短信ID:".$result['result']['sid'];return $data = array("msg" => true,"code" => $this->rands,"res" => '短信发送成功');}else{//状态非0,说明失败$msg = $result['reason'];// echo "短信发送失败(".$error_code."):".$msg;return $data = array("msg" => false,"res" => '短信发送失败');}}else{//返回内容异常,以下可根据业务逻辑自行修改// echo "请求发送短信失败";return $data = array("msg" => false,"res" => '短信发送失败');}}/*** 请求接口返回内容* @param string $url [请求的URL地址]* @param string $params [请求的参数]* @param int $ipost [是否采用POST形式]* @return string*/static private function juhecurl($url,$params=false,$ispost=0){$httpInfo = array();$ch = curl_init();curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );curl_setopt( $ch, CURLOPT_USERAGENT , 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22' );curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 30 );curl_setopt( $ch, CURLOPT_TIMEOUT , 30);curl_setopt( $ch, CURLOPT_RETURNTRANSFER , true );if( $ispost ){curl_setopt( $ch , CURLOPT_POST , true );curl_setopt( $ch , CURLOPT_POSTFIELDS , $params );curl_setopt( $ch , CURLOPT_URL , $url );}else{if($params){curl_setopt( $ch , CURLOPT_URL , $url.'?'.$params );}else{curl_setopt( $ch , CURLOPT_URL , $url);}}$response = curl_exec( $ch );if ($response === FALSE) {//echo "cURL Error: " . curl_error($ch);return false;}$httpCode = curl_getinfo( $ch , CURLINFO_HTTP_CODE );$httpInfo = array_merge( $httpInfo , curl_getinfo( $ch ) );curl_close( $ch );return $response;}}//调用短信验证码类$phone = new Phone(手机号);$phone->sendSms();