Driver.php 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2017~2021 https://www.yiovo.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
  8. // +----------------------------------------------------------------------
  9. // | Author: 萤火科技 <admin@yiovo.com>
  10. // +----------------------------------------------------------------------
  11. declare (strict_types = 1);
  12. namespace app\common\library\sms;
  13. use think\Exception;
  14. /**
  15. * 短信通知模块驱动
  16. * Class driver
  17. * @package app\common\library\sms
  18. */
  19. class Driver
  20. {
  21. private $config; // 配置信息
  22. private $engine; // 当前短信服务引擎类
  23. private $engineName; // 当前短信引擎名称
  24. private $error = ''; // 错误信息
  25. /**
  26. * 构造方法
  27. * Driver constructor.
  28. * @param array $config
  29. * @throws Exception
  30. */
  31. public function __construct(array $config)
  32. {
  33. // 配置信息
  34. $this->config = $config;
  35. // 当前引擎名称
  36. $this->engineName = $this->config['default'];
  37. // 实例化当前存储引擎
  38. $this->engine = $this->getEngineClass();
  39. }
  40. /**
  41. * 发送短信通知
  42. * @param string $sceneValue 场景值
  43. * @param array $templateParams 短信模板变量
  44. * @param array $sceneConfig 短信场景配置
  45. * @param bool $isTest
  46. * @return bool
  47. */
  48. public function sendSms(string $sceneValue, array $templateParams, array $sceneConfig = [], bool $isTest = false)
  49. {
  50. // 短信场景配置
  51. $sceneConfig = array_merge($this->config['scene'][$sceneValue], $sceneConfig);
  52. if ($isTest == false && !$sceneConfig['isEnable']) {
  53. $this->error = '短信通知服务未开启,请在商户后台中设置';
  54. return false;
  55. }
  56. // 执行发送短信
  57. if (!$this->engine->sendSms($sceneConfig, $templateParams)) {
  58. $this->error = $this->engine->getError();
  59. return false;
  60. }
  61. return true;
  62. }
  63. /**
  64. * 获取错误信息
  65. * @return mixed
  66. */
  67. public function getError()
  68. {
  69. return $this->error;
  70. }
  71. /**
  72. * 获取当前的存储引擎
  73. * @return mixed
  74. * @throws Exception
  75. */
  76. private function getEngineClass()
  77. {
  78. $classSpace = __NAMESPACE__ . '\\engine\\' . ucfirst($this->engineName);
  79. if (!class_exists($classSpace)) {
  80. throwError('未找到存储引擎类: ' . $this->engineName);
  81. }
  82. return new $classSpace($this->config['engine'][$this->engineName]);
  83. }
  84. }