ShortLetterRepositories.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. namespace crmeb\repositories;
  3. use app\admin\model\sms\SmsRecord;
  4. use crmeb\services\AlismsService;
  5. use crmeb\services\sms\Sms;
  6. use think\Config;
  7. use think\Exception;
  8. use think\facade\Log;
  9. /**
  10. * 短信发送
  11. * Class ShortLetterRepositories
  12. * @package crmeb\repositories
  13. */
  14. class ShortLetterRepositories
  15. {
  16. /**
  17. * 发送短信
  18. * @param $switch 发送开关
  19. * @param $phone 手机号码
  20. * @param array $data 模板替换内容
  21. * @param string $template 模板编号
  22. * @param string $logMsg 错误日志记录
  23. * @return bool|string
  24. * @throws \think\db\exception\DataNotFoundException
  25. * @throws \think\db\exception\ModelNotFoundException
  26. */
  27. public static function send($switch, $phone, array $data, string $template, $logMsg = '')
  28. {
  29. if ($switch && $phone) {
  30. $sms = new Sms([
  31. 'sms_account' => sys_config('sms_account'),
  32. 'sms_token' => sys_config('sms_token'),
  33. 'site_url' => sys_config('site_url')
  34. ]);
  35. $res = $sms->send($phone, $template, $data);
  36. if ($res === false) {
  37. $errorSmg = $sms->getError();
  38. Log::info($logMsg ?? $errorSmg);
  39. return $errorSmg;
  40. } else {
  41. SmsRecord::sendRecord($phone, $res['data']['content'], $res['data']['template'], $res['data']['id']);
  42. }
  43. return true;
  44. } else {
  45. return false;
  46. }
  47. }
  48. /**
  49. * 发送短信
  50. * @param string $phone 手机号码
  51. * @param array $data 模板替换内容
  52. * @param string $template 模板编号
  53. * @return bool|string
  54. */
  55. public static function AliSend(string $phone, array $data, string $template)
  56. {
  57. try {
  58. $sms = new AlismsService(sys_config('sms_account', 'LTAI5t7kFLZDYHL5VPuCU312', true), sys_config('sms_token', 'EJ0WXQqjOcYO9iVlatQc4EBySmjCzH', true));
  59. $res = $sms->setAction('SendSms')->setOptions([
  60. 'PhoneNumbers' => $phone,
  61. 'SignName' => '满园春',
  62. 'TemplateCode' => \think\facade\Config::get('sms.stores.aliyun.template_id.' . $template, 'sms.stores.aliyun.template_id.DEFAULT'),
  63. 'TemplateParam' => json_encode($data),
  64. ])->execute();
  65. if ($res['Code'] != 'OK') {
  66. return $res['Message'];
  67. } else {
  68. SmsRecord::sendRecord($phone, $data['code'], $template, '');
  69. }
  70. return true;
  71. } catch (Exception $exception) {
  72. return $exception->getMessage();
  73. }
  74. }
  75. }