WechatQrcodeServices.php 12 KB

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