Wechat.php 2.4 KB

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