WechatService.php 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | Think.Admin
  4. // +----------------------------------------------------------------------
  5. // | 版权所有 2014~2017 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
  6. // +----------------------------------------------------------------------
  7. // | 官方网站: http://think.ctolog.com
  8. // +----------------------------------------------------------------------
  9. // | 开源协议 ( http://www.apache.org/licenses/LICENSE-2.0 )
  10. // +----------------------------------------------------------------------
  11. // | github开源项目:https://github.com/zoujingli/Think.Admin
  12. // +----------------------------------------------------------------------
  13. namespace service;
  14. use think\Db;
  15. use think\Log;
  16. /**
  17. * 微信数据服务
  18. * Class WechatService
  19. * @package service
  20. * @author Anyon <zoujingli@qq.com>
  21. * @date 2017/03/22 15:32
  22. */
  23. class WechatService
  24. {
  25. /**
  26. * 通过图文ID读取图文信息
  27. * @param int $id 本地图文ID
  28. * @param array $where 额外的查询条件
  29. * @return array
  30. */
  31. public static function getNewsById($id, $where = [])
  32. {
  33. $data = Db::name('WechatNews')->where('id', $id)->where($where)->find();
  34. $article_ids = explode(',', $data['article_id']);
  35. $articles = Db::name('WechatNewsArticle')->where('id', 'in', $article_ids)->select();
  36. $data['articles'] = [];
  37. foreach ($article_ids as $article_id) {
  38. foreach ($articles as $article) {
  39. if (intval($article['id']) === intval($article_id)) {
  40. unset($article['create_by'], $article['create_at']);
  41. $data['articles'][] = $article;
  42. }
  43. }
  44. }
  45. unset($articles);
  46. return $data;
  47. }
  48. /**
  49. * 上传图片到微信服务器
  50. * @param string $local_url
  51. * @return string|null
  52. */
  53. public static function uploadImage($local_url)
  54. {
  55. # 检测文件上否已经上传过了
  56. if (($img = Db::name('WechatNewsImage')->where('md5', md5($local_url))->find()) && isset($img['media_url'])) {
  57. return $img['media_url'];
  58. }
  59. # 下载临时文件到本地
  60. $filename = 'wechat/image/' . join('/', str_split(md5($local_url), 16)) . '.' . strtolower(pathinfo($local_url, 4));
  61. $result = FileService::local($filename, file_get_contents($local_url));
  62. # 上传图片到微信服务器
  63. if ($result && isset($result['file'])) {
  64. $wechat = &load_wechat('media');
  65. $info = $wechat->uploadImg(['media' => "@{$result['file']}"]);
  66. if (!empty($info)) {
  67. $data = ['local_url' => $local_url, 'media_url' => $info['url'], 'md5' => md5($local_url)];
  68. Db::name('WechatNewsImage')->insert($data);
  69. return $info['url'];
  70. }
  71. Log::error("图片上传失败,请稍后再试!{$wechat->errMsg}[{$wechat->errCode}]");
  72. }
  73. return null;
  74. }
  75. /**
  76. * 上传图片永久素材
  77. * @param string $local_url 文件URL地址
  78. * @param string $type 文件类型
  79. * @param bool $is_video 是否为视频文件
  80. * @param array $video_info 视频信息
  81. * @return string|null
  82. */
  83. public static function uploadForeverMedia($local_url = '', $type = 'image', $is_video = false, $video_info = [])
  84. {
  85. # 检测文件上否已经上传过了
  86. $wechat = &load_wechat('media');
  87. # 检查文件URL是否已经上传为永久素材
  88. $map = ['md5' => md5($local_url), 'appid' => $wechat->appid];
  89. if (($img = Db::name('WechatNewsMedia')->where($map)->find()) && isset($img['media_id'])) {
  90. return $img['media_id'];
  91. }
  92. # 下载临时文件到本地
  93. $filename = 'wechat/image/' . join('/', str_split(md5($local_url), 16)) . '.' . strtolower(pathinfo($local_url, 4));
  94. $upload = FileService::local($filename, file_get_contents($local_url));
  95. if (!empty($upload) && isset($upload['file']) && file_exists($upload['file'])) {
  96. # 上传图片到微信服务器
  97. if (false !== ($result = $wechat->uploadForeverMedia(['media' => "@{$upload['file']}"], $type, $is_video, $video_info))) {
  98. $data = ['md5' => $map['md5'], 'type' => $type, 'appid' => $wechat->appid, 'media_id' => $result['media_id'], 'local_url' => $local_url];
  99. isset($result['url']) && $data['media_url'] = $result['url'];
  100. Db::name('WechatNewsMedia')->insert($data);
  101. return $data['media_id'];
  102. }
  103. }
  104. Log::error("素材上传失败, 请稍后再试! {$wechat->errMsg}[{$wechat->errCode}]");
  105. return null;
  106. }
  107. /**
  108. * 从微信服务器获取所有标签
  109. * @return bool
  110. */
  111. public static function syncFansTags()
  112. {
  113. $wechat = &load_wechat("User");
  114. if (($result = $wechat->getTags()) !== false) {
  115. $tags = $result['tags'];
  116. foreach ($tags as &$tag) {
  117. $tag['appid'] = $wechat->appid;
  118. }
  119. Db::name('WechatFansTags')->where('appid', $wechat->appid)->delete();
  120. foreach (array_chunk($tags, 100) as $list) {
  121. Db::name('WechatFansTags')->insertAll($list);
  122. }
  123. }
  124. return true;
  125. }
  126. /**
  127. * 同步粉丝的标签
  128. * @param string $openid
  129. * @return bool
  130. */
  131. public static function syncFansTagsByOpenid($openid)
  132. {
  133. $wechat = &load_wechat('User');
  134. $tagsid = $wechat->getUserTags($openid);
  135. if ($tagsid === false || !is_array($tagsid)) {
  136. return false;
  137. }
  138. $data = ['appid' => $wechat->appid, 'openid' => $openid, 'tagid_list' => join(',', $tagsid)];
  139. return DataService::save('wechat_fans', $data, 'openid', ['appid' => $wechat->appid]);
  140. }
  141. /**
  142. * 保存/更新粉丝信息
  143. * @param array $user
  144. * @param string $appid
  145. * @return bool
  146. */
  147. public static function setFansInfo($user, $appid = '')
  148. {
  149. if (!empty($user['subscribe_time'])) {
  150. $user['subscribe_at'] = date('Y-m-d H:i:s', $user['subscribe_time']);
  151. }
  152. if (!empty($user['tagid_list']) && is_array($user['tagid_list'])) {
  153. $user['tagid_list'] = join(',', $user['tagid_list']);
  154. }
  155. $user['appid'] = $appid;
  156. $user['nickname'] = ToolsService::emojiEncode($user['nickname']);
  157. return DataService::save('WechatFans', $user, 'openid');
  158. }
  159. /**
  160. * 读取粉丝信息
  161. * @param string $openid 微信用户openid
  162. * @param string $appid 公众号appid
  163. * @return array|false
  164. */
  165. public static function getFansInfo($openid, $appid = null)
  166. {
  167. $map = ['openid' => $openid];
  168. is_string($appid) && $map['appid'] = $appid;
  169. if (($fans = Db::name('WechatFans')->where($map)->find()) && isset($fans['nickname'])) {
  170. $fans['nickname'] = ToolsService::emojiDecode($fans['nickname']);
  171. }
  172. return $fans;
  173. }
  174. /**
  175. * 同步获取粉丝列表
  176. * @param string $next_openid
  177. * @return bool
  178. */
  179. public static function syncAllFans($next_openid = '')
  180. {
  181. $wechat = &load_wechat('User');
  182. if (false === ($result = $wechat->getUserList($next_openid)) || empty($result['data']['openid'])) {
  183. Log::error("获取粉丝列表失败, {$wechat->errMsg} [{$wechat->errCode}]");
  184. return false;
  185. }
  186. foreach (array_chunk($result['data']['openid'], 100) as $openids) {
  187. if (false === ($info = $wechat->getUserBatchInfo($openids)) || !is_array($info)) {
  188. Log::error("获取用户信息失败, {$wechat->errMsg} [{$wechat->errCode}]");
  189. return false;
  190. }
  191. foreach ($info as $user) {
  192. if (false === self::setFansInfo($user, $wechat->appid)) {
  193. Log::error('更新粉丝信息更新失败!');
  194. return false;
  195. }
  196. if ($result['next_openid'] === $user['openid']) {
  197. unset($result['next_openid']);
  198. }
  199. }
  200. }
  201. return empty($result['next_openid']) ? true : self::syncAllFans($result['next_openid']);
  202. }
  203. /**
  204. * 同步获取黑名单信息
  205. * @param string $next_openid
  206. * @return bool
  207. */
  208. public static function syncBlackFans($next_openid = '')
  209. {
  210. $wechat = &load_wechat('User');
  211. $result = $wechat->getBacklist($next_openid);
  212. if ($result === false || (empty($result['data']['openid']))) {
  213. if (empty($result['total'])) {
  214. return true;
  215. }
  216. Log::error("获取粉丝黑名单列表失败,{$wechat->errMsg} [{$wechat->errCode}]");
  217. return false;
  218. }
  219. foreach ($result['data']['openid'] as $openid) {
  220. if (false === ($user = $wechat->getUserInfo($openid))) {
  221. Log::error("获取用户[{$openid}]信息失败,$wechat->errMsg");
  222. return false;
  223. }
  224. $user['is_back'] = '1';
  225. if (false === self::setFansInfo($user)) {
  226. Log::error('更新粉丝信息更新失败!');
  227. return false;
  228. }
  229. if ($result['next_openid'] === $openid) {
  230. unset($result['next_openid']);
  231. }
  232. }
  233. return empty($result['next_openid']) ? true : self::syncBlackFans($result['next_openid']);
  234. }
  235. }