sms.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. class Sms
  3. {
  4. private $api_url, $auth_key, $errorMsg;
  5. function __construct($api_url, $auth_key)
  6. {
  7. $this->api_url = $api_url;
  8. $this->auth_key = $auth_key;
  9. }
  10. /**
  11. * 实现短信验证码接口
  12. *
  13. */
  14. public function sendSms($mobile, $code)
  15. {
  16. $send = array(
  17. 'apikey' => $this->auth_key,
  18. 'mobile' => $mobile,
  19. 'text' => $code
  20. );
  21. $data = http_build_query($send);
  22. $res = json_decode($this->_httpClient($this->api_url, $data));
  23. $resArr = $this->objectToArray($res);
  24. if (!empty($resArr) && $resArr["code"] == 0) {
  25. return true;
  26. } else {
  27. if (empty($this->errorMsg)) $this->errorMsg = isset($resArr["msg"]) ? $resArr["msg"] : '未知错误';
  28. return false;
  29. }
  30. }
  31. //对象转数组,使用get_object_vars返回对象属性组成的数组
  32. function objectToArray($array)
  33. {
  34. if (is_object($array)) {
  35. $array = (array)$array;
  36. }
  37. if (is_array($array)) {
  38. foreach ($array as $key => $value) {
  39. $array[$key] = $this->objectToArray($value);
  40. }
  41. }
  42. return $array;
  43. }
  44. /**
  45. * POST方式访问短信接口
  46. * @param string $data
  47. * @return mixed
  48. */
  49. private function _httpClient($api_url, $data)
  50. {
  51. try {
  52. $ch = curl_init();
  53. curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept:text/plain;charset=utf-8', 'Content-Type:application/x-www-form-urlencoded', 'charset=utf-8'));
  54. curl_setopt($ch, CURLOPT_URL, $api_url);
  55. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  56. curl_setopt($ch, CURLOPT_POST, 1);
  57. curl_setopt($ch, CURLOPT_TIMEOUT, 10);
  58. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  59. curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  60. $res = curl_exec($ch);
  61. curl_close($ch);
  62. return $res;
  63. } catch (Exception $e) {
  64. $this->errorMsg = $e->getMessage();
  65. return false;
  66. }
  67. }
  68. /**
  69. * POST方式访问短信接口
  70. * @param string $data
  71. * @return mixed
  72. */
  73. public function getErrors()
  74. {
  75. return $this->errorMsg;
  76. }
  77. }