Wechat.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. <?php
  2. namespace crmeb\services\template\storage;
  3. use app\common\repositories\wechat\TemplateMessageRepository;
  4. use crmeb\basic\BaseMessage;
  5. use crmeb\services\WechatService;
  6. use think\facade\Log;
  7. class Wechat extends BaseMessage
  8. {
  9. /**
  10. * @var WechatService
  11. */
  12. protected $service;
  13. /**
  14. * 初始化
  15. * @param array $config
  16. * @return mixed|void
  17. */
  18. protected function initialize(array $config)
  19. {
  20. parent::initialize($config); // TODO: Change the autogenerated stub
  21. $this->service = WechatService::create();
  22. }
  23. /**
  24. * @param string $templateId
  25. * @return mixed
  26. */
  27. public function getTempId(string $templateId)
  28. {
  29. return app()->make(TemplateMessageRepository::class)->getTempId($templateId, 1);
  30. }
  31. /**
  32. * 发送消息
  33. * @param string $templateId
  34. * @param array $data
  35. * @return bool|mixed
  36. */
  37. public function send(string $templateId, array $data = [])
  38. {
  39. $templateId = $this->getTemplateCode($templateId);
  40. if (!$templateId) {
  41. return $this->setError('Template number does not exist');
  42. }
  43. $tempid = $this->getTempId($templateId);
  44. if (!$tempid) {
  45. return $this->setError('Template ID does not exist');
  46. }
  47. if (!$this->openId) {
  48. return $this->setError('Openid does not exist');
  49. }
  50. try {
  51. $res = $this->service->sendTemplate($this->openId, $tempid, $data, $this->toUrl, $this->color);
  52. $this->clear();
  53. return $res;
  54. } catch (\Exception $e) {
  55. $this->isLog() && Log::error('发送给openid为:' . $this->openId . '微信模板消息失败,模板id为:' . $tempid . ';错误原因为:' . $e->getMessage());
  56. return $this->setError($e->getMessage());
  57. }
  58. }
  59. /**
  60. * 获取所有模板
  61. * @return \EasyWeChat\Support\Collection|mixed
  62. */
  63. public function list()
  64. {
  65. return $this->service->noticeService()->getPrivateTemplates();
  66. }
  67. /**
  68. * 添加模板消息
  69. * @param string $shortId
  70. * @return \EasyWeChat\Support\Collection|mixed
  71. */
  72. public function add(string $shortId)
  73. {
  74. return $this->service->noticeService()->addTemplate($shortId);
  75. }
  76. /**
  77. * 删除模板消息
  78. * @param string $templateId
  79. * @return \EasyWeChat\Support\Collection|mixed
  80. */
  81. public function delete(string $templateId)
  82. {
  83. return $this->service->noticeService()->deletePrivateTemplate($templateId);
  84. }
  85. /**
  86. * 返回所有支持的行业列表
  87. * @return \EasyWeChat\Support\Collection
  88. */
  89. public function getIndustry()
  90. {
  91. return $this->service->noticeService()->getIndustry();
  92. }
  93. }