Api.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | Think.Admin
  4. // +----------------------------------------------------------------------
  5. // | 版权所有 2014~2017 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
  6. // +----------------------------------------------------------------------
  7. // | 官方网站: http://think.ctolog.com
  8. // +----------------------------------------------------------------------
  9. // | 开源协议 ( https://mit-license.org )
  10. // +----------------------------------------------------------------------
  11. // | github开源项目:https://github.com/zoujingli/Think.Admin
  12. // +----------------------------------------------------------------------
  13. namespace app\wechat\controller;
  14. use service\DataService;
  15. use service\WechatService;
  16. use Wechat\WechatReceive;
  17. use think\Controller;
  18. use think\Log;
  19. use think\Db;
  20. /**
  21. * 微信接口控制器
  22. * Class Api
  23. * @package app\wechat\controller
  24. * @author Anyon <zoujingli@qq.com>
  25. */
  26. class Api extends Controller {
  27. /**
  28. * 微信openid
  29. * @var string
  30. */
  31. protected $openid;
  32. /**
  33. * 微信消息对象
  34. * @var WechatReceive
  35. */
  36. protected $wechat;
  37. /**
  38. * 微信消息接口
  39. * @return string
  40. */
  41. public function index() {
  42. // 实例接口对象
  43. $this->wechat = &load_wechat('Receive');
  44. // 验证接口请求
  45. if ($this->wechat->valid() === false) {
  46. $msg = "{$this->wechat->errMsg}[{$this->wechat->errCode}]";
  47. Log::error($msg);
  48. return $msg;
  49. }
  50. // 获取消息来源用户OPENID
  51. $this->openid = $this->wechat->getRev()->getRevFrom();
  52. // 获取并同步粉丝信息到数据库
  53. $this->_syncFans(true);
  54. // 分别执行对应类型的操作
  55. switch ($this->wechat->getRev()->getRevType()) {
  56. case WechatReceive::MSGTYPE_TEXT:
  57. $keys = $this->wechat->getRevContent();
  58. return $this->_keys("wechat_keys#keys#{$keys}");
  59. case WechatReceive::MSGTYPE_EVENT:
  60. return $this->_event();
  61. case WechatReceive::MSGTYPE_IMAGE:
  62. return $this->_image();
  63. case WechatReceive::MSGTYPE_LOCATION:
  64. return $this->_location();
  65. default:
  66. return 'success';
  67. }
  68. }
  69. /**
  70. * 关键字处理
  71. * @param string $keys 关键字(常规或规格关键字)
  72. * @param bool $isDefaultMode 是否启用默认模式
  73. * @return string
  74. */
  75. private function _keys($keys, $isDefaultMode = false) {
  76. list($table, $field, $value) = explode('#', $keys . '##');
  77. $info = Db::name($table)->where($field, $value)->find();
  78. if ($info && is_array($info) && isset($info['type'])) {
  79. // 转发给多客服
  80. if (!empty($info['type']) && $info['type'] === 'customservice') {
  81. $this->wechat->sendCustomMessage(['touser' => $this->openid, 'msgtype' => 'text', 'text' => ['content' => $info['content']]]);
  82. return $this->wechat->transfer_customer_service()->reply(false, true);
  83. }
  84. // 无法给出回复时调用默认回复机制
  85. if (array_key_exists('status', $info) && empty($info['status'])) {
  86. return 'success';
  87. }
  88. switch ($info['type']) {
  89. case 'keys': /* 关键字 */
  90. if (empty($info['content']) && empty($info['name'])) {
  91. return 'success';
  92. }
  93. return $this->_keys('wechat_keys#keys#' . (empty($info['content']) ? $info['name'] : $info['content']));
  94. case 'text': /* 文本消息 */
  95. if (empty($info['content']) && empty($info['name'])) {
  96. return 'success';
  97. }
  98. return $this->wechat->text($info['content'])->reply(false, true);
  99. case 'news': /* 图文消息 */
  100. if (empty($info['news_id'])) {
  101. return 'success';
  102. }
  103. return $this->_news($info['news_id']);
  104. case 'music': /* 音频消息 */
  105. if (empty($info['music_url']) || empty($info['music_title']) || empty($info['music_desc'])) {
  106. return 'success';
  107. }
  108. $media_id = empty($info['music_image']) ? '' : WechatService::uploadForeverMedia($info['music_image'], 'image');
  109. if (empty($media_id)) {
  110. return 'success';
  111. }
  112. return $this->wechat->music($info['music_title'], $info['music_desc'], $info['music_url'], $info['music_url'], $media_id)->reply(false, true);
  113. case 'voice': /* 语音消息 */
  114. if (empty($info['voice_url'])) {
  115. return 'success';
  116. }
  117. $media_id = WechatService::uploadForeverMedia($info['voice_url'], 'voice');
  118. if (empty($media_id)) {
  119. return 'success';
  120. }
  121. return $this->wechat->voice($media_id)->reply(false, true);
  122. case 'image': /* 图文消息 */
  123. if (empty($info['image_url'])) {
  124. return 'success';
  125. }
  126. $media_id = WechatService::uploadForeverMedia($info['image_url'], 'image');
  127. if (empty($media_id)) {
  128. return 'success';
  129. }
  130. return $this->wechat->image($media_id)->reply(false, true);
  131. case 'video': /* 视频消息 */
  132. if (empty($info['video_url']) || empty($info['video_desc']) || empty($info['video_title'])) {
  133. return 'success';
  134. }
  135. $data = ['title' => $info['video_title'], 'introduction' => $info['video_desc']];
  136. $media_id = WechatService::uploadForeverMedia($info['video_url'], 'video', true, $data);
  137. return $this->wechat->video($media_id, $info['video_title'], $info['video_desc'])->reply(false, true);
  138. }
  139. }
  140. if ($isDefaultMode) {
  141. return 'success';
  142. }
  143. return $this->_keys('wechat_keys#keys#default', true);
  144. }
  145. /**
  146. * 回复图文
  147. * @param int $news_id
  148. * @return bool|string
  149. */
  150. protected function _news($news_id = 0) {
  151. if (is_array($newsinfo = WechatService::getNewsById($news_id)) && !empty($newsinfo['articles'])) {
  152. $newsdata = array();
  153. foreach ($newsinfo['articles'] as $vo) {
  154. $newsdata[] = [
  155. 'Title' => $vo['title'],
  156. 'Description' => $vo['digest'],
  157. 'PicUrl' => $vo['local_url'],
  158. 'Url' => url("@wechat/review", '', true, true) . "?content={$vo['id']}&type=article",
  159. ];
  160. }
  161. return $this->wechat->news($newsdata)->reply();
  162. }
  163. return 'success';
  164. }
  165. /**
  166. * 事件处理
  167. */
  168. protected function _event() {
  169. $event = $this->wechat->getRevEvent();
  170. switch (strtolower($event['event'])) {
  171. /* 粉丝关注事件 */
  172. case 'subscribe':
  173. $this->_syncFans(true);
  174. if (!empty($event['key']) && stripos($event['key'], 'qrscene_') !== false) {
  175. $this->_spread(preg_replace('|^.*?(\d+).*?$|', '$1', $event['key']));
  176. }
  177. return $this->_keys('wechat_keys#keys#subscribe');
  178. /* 粉丝取消关注 */
  179. case 'unsubscribe':
  180. $this->_syncFans(false);
  181. return 'success';
  182. /* 点击菜单事件 */
  183. case 'click':
  184. return $this->_keys($event['key']);
  185. /* 扫码推事件 */
  186. case 'scancode_push':
  187. case 'scancode_waitmsg':
  188. $scanInfo = $this->wechat->getRev()->getRevScanInfo();
  189. if (isset($scanInfo['ScanResult'])) {
  190. return $this->_keys($scanInfo['ScanResult']);
  191. }
  192. return 'success';
  193. case 'scan':
  194. if (!empty($event['key'])) {
  195. return $this->_spread($event['key']);
  196. }
  197. return 'success';
  198. }
  199. return 'success';
  200. }
  201. /**
  202. * 推荐好友扫码关注
  203. * @param string $key
  204. * @return mixed
  205. */
  206. private function _spread($key) {
  207. // 检测推荐是否有效
  208. $fans = Db::name('WechatFans')->where('id', $key)->find();
  209. if (!is_array($fans) || !isset($fans['openid']) || $fans['openid'] === $this->openid) {
  210. return false;
  211. }
  212. // 标识推荐关系
  213. $data = ['spread_by' => $fans['openid'], 'spread_at' => date('Y-m-d H:i:s')];
  214. Db::name('WechatFans')->where("openid='{$this->openid}' and (spread_openid is null or spread_openid='')")->setField($data);
  215. // @todo 推荐成功的奖励
  216. }
  217. /**
  218. * 位置事情回复
  219. * @return string
  220. */
  221. private function _location() {
  222. return 'success';
  223. }
  224. /**
  225. * 图片事件处理
  226. */
  227. private function _image() {
  228. return 'success';
  229. }
  230. /**
  231. * 同步粉丝状态
  232. * @param bool $subscribe 关注状态
  233. */
  234. protected function _syncFans($subscribe = true) {
  235. if ($subscribe) {
  236. $fans = WechatService::getFansInfo($this->openid);
  237. if (empty($fans) || empty($fans['subscribe'])) {
  238. $wechat = &load_wechat('User');
  239. $userInfo = $wechat->getUserInfo($this->openid);
  240. $userInfo['subscribe'] = intval($subscribe);
  241. WechatService::setFansInfo($userInfo, $wechat->appid);
  242. }
  243. } else {
  244. $data = ['subscribe' => '0', 'appid' => $this->wechat->appid, 'openid' => $this->openid];
  245. DataService::save('wechat_fans', $data, ['appid', 'openid']);
  246. }
  247. }
  248. }