TemplateMessageRepository.php 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2022 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. namespace app\common\repositories\wechat;
  12. use app\common\dao\wechat\TemplateMessageDao;
  13. use app\common\repositories\BaseRepository;
  14. use crmeb\exceptions\WechatException;
  15. use crmeb\services\MiniProgramService;
  16. use crmeb\services\WechatService;
  17. use FormBuilder\Factory\Elm;
  18. use think\exception\ValidateException;
  19. use think\facade\Config;
  20. use think\facade\Route;
  21. /**
  22. * Class TemplateMessageRepository
  23. * @package app\common\repositories\wechat
  24. * @mixin TemplateMessageDao
  25. */
  26. class TemplateMessageRepository extends BaseRepository
  27. {
  28. /**
  29. * @var TemplateMessageDao
  30. */
  31. public $dao;
  32. /**
  33. * TemplateMessageRepository constructor.
  34. * @param TemplateMessageDao $dao
  35. */
  36. public function __construct(TemplateMessageDao $dao)
  37. {
  38. $this->dao = $dao;
  39. }
  40. public function getList($wereh,$page,$limit)
  41. {
  42. $query = $this->dao->search($wereh);
  43. $count = $query->count();
  44. $list = $query->page($page,$limit)->order('template_id DESC')->select();
  45. return compact('count','list');
  46. }
  47. /**
  48. * TODO
  49. * @param int|null $id
  50. * @param int $type
  51. * @return \FormBuilder\Form
  52. * @author Qinii
  53. * @day 2020-06-19
  54. */
  55. public function form(?int $id = null,$type = 0)
  56. {
  57. $form = Elm::createForm(Route::buildUrl('systemTemplateMessageCreate')->build());
  58. $form->setRule([
  59. Elm::hidden('type',$type),
  60. Elm::input('tempkey','模板编号'),
  61. Elm::input('name','模板名'),
  62. Elm::input('tempid','模板ID'),
  63. Elm::textarea('content','回复内容'),
  64. Elm::switches('status','状态',1)->activeValue(1)->inactiveValue(0)->inactiveText('关')->activeText('开'),
  65. ]);
  66. return $form->setTitle(is_null($id) ? '添加' : '编辑');
  67. }
  68. /**
  69. * TODO
  70. * @param $id
  71. * @return \FormBuilder\Form
  72. * @author Qinii
  73. * @day 2020-06-19
  74. */
  75. public function updateForm($id)
  76. {
  77. $tem = $this->dao->get($id);
  78. $form = Elm::createForm(Route::buildUrl('systemTemplateMessageUpdate',['id' => $id])->build());
  79. $form->setRule([
  80. Elm::hidden('type',$tem['type']),
  81. Elm::input('tempkey','模板编号',$tem['tempkey'])->disabled(1),
  82. Elm::input('name','模板名',$tem['name'])->disabled(1),
  83. Elm::input('tempid','模板ID',$tem['tempid']),
  84. Elm::switches('status','状态',$tem['status'])->activeValue(1)->inactiveValue(0)->inactiveText('关')->activeText('开'),
  85. ]);
  86. return $form->setTitle('编辑');
  87. }
  88. public function getSubscribe()
  89. {
  90. $res = [];
  91. $data = $this->dao->search(['type' => 0])->column('tempid','tempkey');
  92. $arr = Config::get('template.stores.subscribe.template_id');
  93. foreach ($arr as $k => $v){
  94. $res[$k] = $data[$v] ?? '';
  95. }
  96. return $res;
  97. }
  98. public function getTemplateList(array $where)
  99. {
  100. $query = $this->dao->search($where);
  101. $count = $query->count();
  102. $list = $query->select();
  103. foreach ($list as &$item) {
  104. if ($item['content']) $item['content'] = explode("\n", $item['content']);
  105. }
  106. return compact('list', 'count');
  107. }
  108. /**
  109. * TODO 同步订阅消息
  110. * @return string
  111. * @author Qinii
  112. * @day 11/24/21
  113. */
  114. public function syncMinSubscribe()
  115. {
  116. if (!systemConfig('routine_appId') || !systemConfig('routine_appsecret')) {
  117. throw new ValidateException('请先配置小程序appid、appSecret等参数');
  118. }
  119. $all = $this->getTemplateList(['type' => 0]);
  120. $errData = [];
  121. $errMessage = [
  122. '-1' => '系统繁忙,此时请稍候再试',
  123. '40001' => 'AppSecret错误或者AppSecret不属于这个小程序,请确认AppSecret 的正确性',
  124. '40002' => '请确保grant_type字段值为client_credential',
  125. '40013' => '不合法的AppID,请检查AppID的正确性,避免异常字符,注意大小写',
  126. '40125' => '小程序配置无效,请检查配置',
  127. '41002' => '缺少appid参数',
  128. '41004' => '缺少secret参数',
  129. '43104' => 'appid与openid不匹配',
  130. '45009' => '达到微信api每日限额上限',
  131. '200011' => '此账号已被封禁,无法操作',
  132. '200012' => '个人模版数已达上限,上限25个',
  133. ];
  134. if ($all['list']) {
  135. $time = time();
  136. foreach ($all['list'] as $template) {
  137. if ($template['tempkey']) {
  138. if (!isset($template['kid'])) {
  139. throw new ValidateException('数据库模版表(template_message)缺少字段:kid');
  140. }
  141. if (isset($template['kid']) && $template['kid']) {
  142. continue;
  143. }
  144. $works = [];
  145. try {
  146. $works = MiniProgramService::create()->getSubscribeTemplateKeyWords($template['tempkey']);
  147. } catch (\Throwable $e) {
  148. $wechatErr = $e->getMessage();
  149. if (is_string($wechatErr))
  150. throw new WechatException('模板ID:'.$template['tempkey'].',错误信息'.$wechatErr);
  151. if (in_array($wechatErr->getCode(), array_keys($errMessage))) {
  152. throw new WechatException($errMessage[$wechatErr->getCode()]);
  153. }
  154. $errData[1] = '获取关键词列表失败:' . $wechatErr->getMessage();
  155. }
  156. $kid = [];
  157. if ($works) {
  158. $works = array_combine(array_column($works, 'name'), $works);
  159. $content = is_array($template['content']) ? $template['content'] : explode("\n", $template['content']);
  160. foreach ($content as $c) {
  161. $name = explode('{{', $c)[0] ?? '';
  162. if ($name && isset($works[$name])) {
  163. $kid[] = $works[$name]['kid'];
  164. }
  165. }
  166. }
  167. if ($kid && isset($template['kid']) && !$template['kid']) {
  168. $tempid = '';
  169. try {
  170. $tempid = MiniProgramService::create()->addSubscribeTemplate($template['tempkey'], $kid, $template['name']);
  171. } catch (\Throwable $e) {
  172. $wechatErr = $e->getMessage();
  173. if ($wechatErr->getCode() == 200022) continue;
  174. if (is_string($wechatErr)) throw new WechatException($wechatErr);
  175. if (in_array($wechatErr->getCode(), array_keys($errMessage))) {
  176. throw new WechatException($errMessage[$wechatErr->getCode()]);
  177. }
  178. $errData[2] = '添加订阅消息模版失败:' . $wechatErr->getMessage();
  179. }
  180. if ($tempid != $template['tempid'] && $tempid) {
  181. $this->dao->update($template['template_id'], ['tempid' => $tempid, 'kid' => json_encode($kid), 'create_time' => $time]);
  182. }
  183. }
  184. }
  185. }
  186. }
  187. return $errData ? implode('\n', $errData) : '同步成功';
  188. }
  189. /**
  190. * 同步模板消息
  191. * @return mixed
  192. * @throws \think\db\exception\DataNotFoundException
  193. * @throws \think\db\exception\DbException
  194. * @throws \think\db\exception\ModelNotFoundException
  195. */
  196. public function syncWechatSubscribe()
  197. {
  198. if (!systemConfig('wechat_appid') || !systemConfig('wechat_appsecret')) {
  199. throw new WechatException('请先配置微信公众号appid、appSecret等参数');
  200. }
  201. $tempall = $this->getTemplateList(['type' => 1]);
  202. /*
  203. * 删除所有模版ID
  204. */
  205. //获取微信平台已经添加的模版
  206. $list = WechatService::create()->getPrivateTemplates();//获取所有模版
  207. foreach ($list->template_list as $v) {
  208. //删除已有模版
  209. WechatService::create()->deleleTemplate($v['template_id']);
  210. }
  211. foreach ($tempall['list'] as $temp) {
  212. //添加模版消息
  213. $res = WechatService::create()->addTemplateId($temp['tempkey']);
  214. if (!$res->errcode && $res->template_id) {
  215. $this->dao->update($temp['template_id'], ['tempid' => $res->template_id]);
  216. }
  217. }
  218. return '模版消息一键设置成功';
  219. }
  220. }