Wechat.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. * 发送消息
  21. * @param string $templateId
  22. * @param array $data
  23. * @return bool|mixed
  24. */
  25. public function send(string $templateId, array $data = [])
  26. {
  27. $templateId = $this->getTemplateCode($templateId);
  28. if (!$templateId) {
  29. return $this->setError('Template number does not exist');
  30. }
  31. $tempid = Db::name('template_message')->where(['tempkey' => $templateId, 'status' => 1, 'type' => 1])->value('tempid');
  32. if (!$tempid) {
  33. return $this->setError('Template ID does not exist');
  34. }
  35. if (!$this->openId) {
  36. return $this->setError('Openid does not exist');
  37. }
  38. try {
  39. $res = WechatService::sendTemplate($this->openId, $tempid, $data, $this->toUrl, $this->color);
  40. $this->clear();
  41. return $res;
  42. } catch (\Exception $e) {
  43. $this->isLog() && Log::error('发送给openid为:' . $this->openId . '微信模板消息失败,模板id为:' . $tempid . ';错误原因为:' . $e->getMessage());
  44. return $this->setError($e->getMessage());
  45. }
  46. }
  47. /**
  48. * 获取所有模板
  49. * @return \EasyWeChat\Support\Collection|mixed
  50. */
  51. public function list()
  52. {
  53. return WechatService::noticeService()->getPrivateTemplates();
  54. }
  55. /**
  56. * 添加模板消息
  57. * @param string $shortId
  58. * @return \EasyWeChat\Support\Collection|mixed
  59. */
  60. public function add(string $shortId)
  61. {
  62. return WechatService::noticeService()->addTemplate($shortId);
  63. }
  64. /**
  65. * 删除模板消息
  66. * @param string $templateId
  67. * @return \EasyWeChat\Support\Collection|mixed
  68. */
  69. public function delete(string $templateId)
  70. {
  71. return WechatService::noticeService()->deletePrivateTemplate($templateId);
  72. }
  73. }