WechatQrcodeServices.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2026 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. namespace app\services\wechat;
  12. use app\dao\wechat\WechatQrcodeDao;
  13. use app\services\BaseServices;
  14. use app\services\other\QrcodeServices;
  15. use app\services\system\attachment\SystemAttachmentServices;
  16. use app\services\user\UserLabelRelationServices;
  17. use app\services\user\UserLabelServices;
  18. use app\services\user\UserServices;
  19. use crmeb\exceptions\AdminException;
  20. use app\services\other\UploadService;
  21. use crmeb\services\app\WechatService;
  22. use think\facade\Config;
  23. /**
  24. * Class WechatQrcodeServices
  25. * @package app\services\wechat
  26. */
  27. class WechatQrcodeServices extends BaseServices
  28. {
  29. /**
  30. * WechatQrcodeServices constructor.
  31. * @param WechatQrcodeDao $dao
  32. */
  33. public function __construct(WechatQrcodeDao $dao)
  34. {
  35. $this->dao = $dao;
  36. }
  37. /**
  38. * 获取渠道码列表
  39. * @param $where
  40. * @return array
  41. * @throws \think\db\exception\DataNotFoundException
  42. * @throws \think\db\exception\DbException
  43. * @throws \think\db\exception\ModelNotFoundException
  44. */
  45. public function qrcodeList($where)
  46. {
  47. /** @var UserLabelServices $userLabel */
  48. $userLabel = app()->make(UserLabelServices::class);
  49. [$page, $limit] = $this->getPageValue();
  50. $list = $this->dao->getList($where, $page, $limit);
  51. foreach ($list as &$item) {
  52. $item['y_follow'] = $item['y_follow'] ?? 0;
  53. $item['stop'] = $item['end_time'] ? ($item['end_time'] > time() ? 1 : -1) : 0;
  54. $item['label_name'] = $userLabel->getColumn([['id', 'in', $item['label_id']]], 'label_name');
  55. $item['end_time'] = date('Y-m-d H:i:s', $item['end_time']);
  56. $item['add_time'] = date('Y-m-d H:i:s', $item['add_time']);
  57. }
  58. $count = $this->dao->count($where);
  59. return compact('list', 'count');
  60. }
  61. /**
  62. * 获取详情
  63. * @param $id
  64. * @return array
  65. * @throws \think\db\exception\DataNotFoundException
  66. * @throws \think\db\exception\DbException
  67. * @throws \think\db\exception\ModelNotFoundException
  68. */
  69. public function qrcodeInfo($id)
  70. {
  71. $info = $this->dao->get($id);
  72. if ($info) {
  73. $info = $info->toArray();
  74. } else {
  75. throw new AdminException('数据不存在');
  76. }
  77. /** @var UserServices $userService */
  78. $userService = app()->make(UserServices::class);
  79. $info['label_id'] = explode(',', $info['label_id']);
  80. foreach ($info['label_id'] as &$item) {
  81. $item = (int)$item;
  82. }
  83. /** @var UserLabelServices $userLabelServices */
  84. $userLabelServices = app()->make(UserLabelServices::class);
  85. $info['label_id'] = $userLabelServices->getLabelList(['ids' => $info['label_id']], ['id', 'label_name']);
  86. $info['time'] = $info['continue_time'];
  87. $info['content'] = json_decode($info['content'], true);
  88. $info['data'] = json_decode($info['data'], true);
  89. $info['avatar'] = $userService->value(['uid' => $info['uid']], 'avatar');
  90. return $info;
  91. }
  92. /**
  93. * 保存渠道码数据
  94. * @param $id
  95. * @param $data
  96. * @return bool
  97. * @throws \think\db\exception\DataNotFoundException
  98. * @throws \think\db\exception\DbException
  99. * @throws \think\db\exception\ModelNotFoundException
  100. */
  101. public function saveQrcode($id, $data)
  102. {
  103. $data['label_id'] = implode(',', $data['label_id']);
  104. $data['add_time'] = time();
  105. $data['continue_time'] = $data['time'];
  106. $data['end_time'] = $data['time'] ? $data['add_time'] + ($data['time'] * 86400) : 0;
  107. /** @var WechatReplyServices $replyServices */
  108. $replyServices = app()->make(WechatReplyServices::class);
  109. $type = $data['type'];
  110. if ($data['type'] == 'url') $type = 'text';
  111. $content = $data['content'];
  112. if ($data['type'] == 'news') $content = $data['content']['list'] ?? [];
  113. $method = 'tidy' . ucfirst($type);
  114. $data['data'] = $replyServices->{$method}($content, 0);
  115. $data['content'] = json_encode($data['content']);
  116. $data['data'] = json_encode($data['data']);
  117. if ($id) {
  118. $info = $this->dao->get($id);
  119. if (!$info) throw new AdminException('数据不存在');
  120. if ($info['image'] == '') $data['image'] = $this->getChannelCode($id);
  121. $info = $this->dao->update($id, $data);
  122. if (!$info) throw new AdminException('保存失败');
  123. } else {
  124. $info = $this->dao->save($data);
  125. $image = $this->getChannelCode($info['id']);
  126. $info = $this->dao->update($info['id'], ['image' => $image]);
  127. if (!$info) throw new AdminException('保存失败');
  128. }
  129. return true;
  130. }
  131. /**
  132. * 生成渠道码
  133. * @param int $id
  134. * @return mixed|string
  135. * @throws \think\db\exception\DataNotFoundException
  136. * @throws \think\db\exception\DbException
  137. * @throws \think\db\exception\ModelNotFoundException
  138. */
  139. public function getChannelCode($id = 0)
  140. {
  141. /** @var SystemAttachmentServices $systemAttachment */
  142. $systemAttachment = app()->make(SystemAttachmentServices::class);
  143. $name = 'wechatqrcode_' . $id . '.jpg';
  144. $siteUrl = sys_config('site_url', '');
  145. $imageInfo = $systemAttachment->getInfo(['name' => $name]);
  146. if (!$imageInfo) {
  147. /** @var QrcodeServices $qrCode */
  148. $qrCode = app()->make(QrcodeServices::class);
  149. //公众号
  150. $resCode = $qrCode->getForeverQrcode('wechatqrcode', $id);
  151. if ($resCode) {
  152. $res = ['res' => $resCode, 'id' => $resCode['id']];
  153. } else {
  154. $res = false;
  155. }
  156. if (!$res) throw new AdminException('二维码生成失败');
  157. $imageInfo = $this->downloadImage($resCode['url'], $name);
  158. $systemAttachment->attachmentAdd($name, $imageInfo['size'], $imageInfo['type'], $imageInfo['att_dir'], $imageInfo['att_dir'], 1, $imageInfo['image_type'], time(), 1);
  159. }
  160. return strpos($imageInfo['att_dir'], 'http') === false ? $siteUrl . $imageInfo['att_dir'] : $imageInfo['att_dir'];
  161. }
  162. /**
  163. * 下载图片
  164. * @param string $url
  165. * @param string $name
  166. * @param int $type
  167. * @param int $timeout
  168. * @param int $w
  169. * @param int $h
  170. * @return string
  171. */
  172. public function downloadImage($url = '', $name = '', $type = 0, $timeout = 30, $w = 0, $h = 0)
  173. {
  174. if (!strlen(trim($url))) return '';
  175. if (!strlen(trim($name))) {
  176. //TODO 获取要下载的文件名称
  177. $downloadImageInfo = $this->getImageExtname($url);
  178. $ext = $downloadImageInfo['ext_name'];
  179. $name = $downloadImageInfo['file_name'];
  180. if (!strlen(trim($name))) return '';
  181. } else {
  182. $ext = $this->getImageExtname($name)['ext_name'];
  183. }
  184. if (!in_array($ext, Config::get('upload.fileExt'))) {
  185. throw new AdminException('格式错误');
  186. }
  187. //TODO 获取远程文件所采用的方法
  188. if ($type) {
  189. $ch = curl_init();
  190. curl_setopt($ch, CURLOPT_URL, $url);
  191. curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
  192. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
  193. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //TODO 跳过证书检查
  194. if (stripos($url, "https://") !== FALSE) curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); //TODO 从证书中检查SSL加密算法是否存在
  195. curl_setopt($ch, CURLOPT_HTTPHEADER, array('user-agent:' . $_SERVER['HTTP_USER_AGENT']));
  196. if (ini_get('open_basedir') == '' && ini_get('safe_mode' == 'Off')) curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);//TODO 是否采集301、302之后的页面
  197. $content = curl_exec($ch);
  198. curl_close($ch);
  199. } else {
  200. try {
  201. ob_start();
  202. readfile($url);
  203. $content = ob_get_contents();
  204. ob_end_clean();
  205. } catch (\Exception $e) {
  206. return $e->getMessage();
  207. }
  208. }
  209. $size = strlen(trim($content));
  210. if (!$content || $size <= 2) return '图片流获取失败';
  211. $upload_type = sys_config('upload_type', 1);
  212. $upload = UploadService::init();
  213. if ($upload->to('attach/spread/agent')->setAuthThumb(false)->stream($content, $name) === false) {
  214. return $upload->getError();
  215. }
  216. $imageInfo = $upload->getUploadInfo();
  217. $data['att_dir'] = $imageInfo['dir'];
  218. $data['name'] = $imageInfo['name'];
  219. $data['size'] = $imageInfo['size'];
  220. $data['type'] = $imageInfo['type'];
  221. $data['image_type'] = $upload_type;
  222. $data['is_exists'] = false;
  223. return $data;
  224. }
  225. /**
  226. * 获取即将要下载的图片扩展名
  227. * @param string $url
  228. * @param string $ex
  229. * @return array|string[]
  230. */
  231. public function getImageExtname($url = '', $ex = 'jpg')
  232. {
  233. $_empty = ['file_name' => '', 'ext_name' => $ex];
  234. if (!$url) return $_empty;
  235. if (strpos($url, '?')) {
  236. $_tarr = explode('?', $url);
  237. $url = trim($_tarr[0]);
  238. }
  239. $arr = explode('.', $url);
  240. if (!is_array($arr) || count($arr) <= 1) return $_empty;
  241. $ext_name = trim($arr[count($arr) - 1]);
  242. $ext_name = !$ext_name ? $ex : $ext_name;
  243. return ['file_name' => md5($url) . '.' . $ext_name, 'ext_name' => $ext_name];
  244. }
  245. /**
  246. * 扫码完成后方法
  247. * @param $qrcodeInfo
  248. * @param $userInfo
  249. * @param $spreadInfo
  250. * @param int $isFollow
  251. * @return mixed
  252. */
  253. public function wechatQrcodeRecord($qrcodeInfo, $userInfo, $spreadInfo, $isFollow = 1)
  254. {
  255. $response = $this->transaction(function () use ($qrcodeInfo, $userInfo, $spreadInfo, $isFollow) {
  256. //绑定用户标签
  257. /** @var UserLabelRelationServices $labelServices */
  258. $labelServices = app()->make(UserLabelRelationServices::class);
  259. foreach ($qrcodeInfo['label_id'] as $item) {
  260. $labelArr[] = [
  261. 'uid' => $userInfo['uid'],
  262. 'label_id' => $item['id'] ?? $item
  263. ];
  264. }
  265. $labelServices->saveAll($labelArr);
  266. //增加二维码扫码数量
  267. $this->dao->upFollowAndScan($qrcodeInfo['id'], $isFollow);
  268. //写入扫码记录
  269. /** @var WechatQrcodeRecordServices $recordServices */
  270. $recordServices = app()->make(WechatQrcodeRecordServices::class);
  271. $data['qid'] = $qrcodeInfo['id'];
  272. $data['uid'] = $userInfo['uid'];
  273. $data['is_follow'] = $isFollow;
  274. $data['add_time'] = time();
  275. $recordServices->save($data);
  276. //回复信息内容
  277. return $this->replyDataByMessage($qrcodeInfo['type'], $qrcodeInfo['data']);
  278. });
  279. return $response;
  280. }
  281. /**
  282. * 发送扫码之后的信息
  283. * @param $type
  284. * @param $data
  285. * @return array|\EasyWeChat\Message\Image|\EasyWeChat\Message\News|\EasyWeChat\Message\Text|\EasyWeChat\Message\Voice
  286. */
  287. public function replyDataByMessage($type, $data)
  288. {
  289. if ($type == 'text') {
  290. return WechatService::textMessage($data['content']);
  291. } else if ($type == 'image') {
  292. return WechatService::imageMessage($data['media_id']);
  293. } else if ($type == 'news') {
  294. $title = $data['title'] ?? '';
  295. $image = $data['image'] ?? '';
  296. $description = $data['synopsis'] ?? '';
  297. $url = $data['url'] ?? '';
  298. return WechatService::newsMessage($title, $description, $url, $image);
  299. } else if ($type == 'url') {
  300. $title = $data['content'];
  301. $image = sys_config('h5_avatar');
  302. $description = $data['content'];
  303. $url = $data['content'];
  304. return WechatService::newsMessage($title, $description, $url, $image);
  305. } else if ($type == 'voice') {
  306. return WechatService::voiceMessage($data['media_id']);
  307. }
  308. }
  309. }