123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899 |
- <?php
- class Sms
- {
- private $api_url, $account, $password, $extno, $errorMsg;
- function __construct($api_url, $account,$password,$extno)
- {
- $this->api_url = $api_url;
- $this->account = $account;
- $this->password = $password;
- $this->extno = $extno;
- }
- /**
- * 实现短信验证码接口
- *
- */
- public function sendSms($mobile, $code)
- {
- $send = array(
- 'action' => 'send',
- 'account' => $this->account,
- 'password' => $this->password,
- 'mobile' => $mobile,
- 'content' => $code,
- 'extno' => $this->extno
- );
- $data = http_build_query($send);
- $res = simplexml_load_string($this->_httpClient($this->api_url,$data));
- $resArr = $this->objectToArray($res);
- $resultcode = !empty($resArr) ? explode('#@#',$resArr['resplist']['resp'])[2] : '';
- if ($resultcode == '0') return true;
- else {
- if (empty($this->errorMsg)) $this->errorMsg = !empty($resultcode) ? $this->getErrorMsg($resultcode) : '未知错误';
- return false;
- }
- }
- function getErrorMsg($code){
- $msg = '';
- switch($code){
- case 6: $msg = '错误代码:6,请联系我们客服';break;
- case 10: $msg = '错误代码:10,请联系我们客服';break;
- case 12: $msg = '检查接收短信手机号码格式是否正确';break;
- case 15: $msg = '错误代码:15,请联系我们客服';break;
- case 16: $msg = '一天时间内同一个手机号码不能太频繁接收短信';break;
- case 17: $msg = '错误代码:17,请联系我们客服';break;
- default : $msg = '错误代码:400,请联系我们客服';break;
- }
- return $msg;
- }
- //对象转数组,使用get_object_vars返回对象属性组成的数组
- function objectToArray($array)
- {
- if (is_object($array)) {
- $array = (array)$array;
- }
- if (is_array($array)) {
- foreach ($array as $key => $value) {
- $array[$key] = $this->objectToArray($value);
- }
- }
- return $array;
- }
- /**
- * POST方式访问短信接口
- * @param string $data
- * @return mixed
- */
- private function _httpClient($api_url, $data)
- {
- try {
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL,$api_url.$data);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch, CURLOPT_HEADER, 0);
- curl_setopt($ch, CURLOPT_TIMEOUT, 10);
- $res = curl_exec($ch);
- curl_close($ch);
- return $res;
- } catch (Exception $e) {
- $this->errorMsg = $e->getMessage();
- return false;
- }
- }
- /**
- * POST方式访问短信接口
- * @param string $data
- * @return mixed
- */
- public function getErrors()
- {
- return $this->errorMsg;
- }
- }
|