SendSms.Class.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. namespace Mall\Framework\Core;
  3. use Mall\Framework\Core\ResultWrapper;
  4. use Mall\Framework\SearchClient\Exception;
  5. class SendSms {
  6. private static $_instance;
  7. protected $error;
  8. static public function getInstance()
  9. {
  10. $key = md5('sendSms');
  11. if (!self::$_instance[$key] instanceof self) {
  12. self::$_instance[$key] = new self;
  13. }
  14. return self::$_instance[$key];
  15. }
  16. /**
  17. * 发送短信消息方法
  18. * 官方文档地址: https://help.aliyun.com/document_detail/55451.html?spm=5176.doc55288.6.556.rZK9dj
  19. * 业务限流 https://help.aliyun.com/knowledge_detail/57710.html?spm=5176.doc55451.6.583.sHFzrz
  20. *
  21. * @param string $mobile 接收短信的手机号
  22. * @param string $signname 短信签名
  23. * @param string $templatecode 短信模板编号
  24. * @param string $templateparam 短信模板替换变量
  25. * @param string $source 发送短信业务来源
  26. */
  27. public function send($mobile, $signname, $templatecode, $templateparam, $source = '')
  28. {
  29. $options = Config::getInstance()->get('sms');
  30. if(empty($options)){
  31. throw new \ErrorException('短信配置错误');
  32. }
  33. $post = [
  34. 'phonenumbers' => $mobile,
  35. 'signname' => $signname,
  36. 'templatecode' => $templatecode,
  37. 'templateparam' => $templateparam,
  38. ];
  39. $result = request($options['api_url'], $post);
  40. if( $result['httpcode'] == 200 && !empty($result['content'])){
  41. $resultContent = json_decode($result['content'],true);
  42. if($resultContent['state']){
  43. return ResultWrapper::success('发送成功');
  44. }else{
  45. return ResultWrapper::fail($resultContent['data'], ErrorCode::$apiNotResult);
  46. }
  47. }else{
  48. if(!empty($result['content'])){
  49. file_put_contents('/tmp/sendSms.log',date('Y-m-d H:i:s').var_export($result['content'],true).PHP_EOL,FILE_APPEND);
  50. return ResultWrapper::fail('请求接口失败,错误原因请留意日志', ErrorCode::$apiNotResult);
  51. }else{
  52. return ResultWrapper::fail('发送失败,接口未返回消息', ErrorCode::$apiNotResult);
  53. }
  54. }
  55. }
  56. public function getError()
  57. {
  58. return $this->error;
  59. }
  60. }