Smsbao.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. <?php
  2. namespace addons\smsbao\library;
  3. class Smsbao
  4. {
  5. private $_params = [];
  6. protected $error = '';
  7. protected $config = [];
  8. protected static $instance = null;
  9. protected $statusStr = array(
  10. "0" => "短信发送成功",
  11. "-1" => "参数不全",
  12. "-2" => "服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!",
  13. "30" => "密码错误",
  14. "40" => "账号不存在",
  15. "41" => "余额不足",
  16. "42" => "帐户已过期",
  17. "43" => "IP地址限制",
  18. "50" => "内容含有敏感词"
  19. );
  20. public function __construct($options = [])
  21. {
  22. if ($config = get_addon_config('smsbao')) {
  23. $this->config = array_merge($this->config, $config);
  24. }
  25. $this->config = array_merge($this->config, is_array($options) ? $options : []);
  26. }
  27. /**
  28. * 单例
  29. * @param array $options 参数
  30. * @return Smsbao
  31. */
  32. public static function instance($options = [])
  33. {
  34. if (is_null(self::$instance)) {
  35. self::$instance = new static($options);
  36. }
  37. return self::$instance;
  38. }
  39. /**
  40. * 立即发送短信
  41. *
  42. * @return boolean
  43. */
  44. public function send()
  45. {
  46. $this->error = '';
  47. $params = $this->_params();
  48. $postArr = array(
  49. 'u' => $params['u'],
  50. 'p' => $params['p'],
  51. 'm' => $params['mobile'],
  52. 'c' => $params['msg']
  53. );
  54. $options = [
  55. CURLOPT_HTTPHEADER => array(
  56. 'Content-Type: application/json; charset=utf-8'
  57. )
  58. ];
  59. $result = \fast\Http::sendRequest('http://api.smsbao.com/sms', $postArr, 'GET', $options);
  60. if ($result['ret']) {
  61. if (isset($result['msg']) && $result['msg'] == '0')
  62. return TRUE;
  63. $this->error = isset($this->statusStr[$result['msg']]) ? $this->statusStr[$result['msg']] : 'InvalidResult';
  64. } else {
  65. $this->error = $result['msg'];
  66. }
  67. return FALSE;
  68. }
  69. private function _params()
  70. {
  71. return array_merge([
  72. 'u' => $this->config['username'],
  73. 'p' => md5($this->config['password']),
  74. ], $this->_params);
  75. }
  76. /**
  77. * 获取错误信息
  78. * @return string
  79. */
  80. public function getError()
  81. {
  82. return $this->error;
  83. }
  84. /**
  85. * 接收手机
  86. * @param string $mobile 手机号码
  87. * @return Smsbao
  88. */
  89. public function mobile($mobile = '')
  90. {
  91. $this->_params['mobile'] = $mobile;
  92. return $this;
  93. }
  94. /**
  95. * 短信内容
  96. * @param string $msg 短信内容
  97. * @return Smsbao
  98. */
  99. public function msg($msg = '')
  100. {
  101. $this->_params['msg'] = $this->config['sign'] . $msg;
  102. return $this;
  103. }
  104. }