Wechat.php 2.2 KB

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