tp5-微信消息接收和处理

微信后台只能填写一个服务器地址,所以 服务器验证 与 消息的接收与回复,都在这一个链接内完成交互。

一、服务器验证:配置地址可写为:http://域名/openapi/wechat/wxapi

<?phpnamespace Openapi;use ApiBase;
use EasyWeChatFactory;
use WechatOfficialAccount;class Wechat extends Base{ var $wx_config = null; public function wxapi() { try { $wx_config = $this->config->wechat->toArray(); $app = Factory::officialAccount($wx_config); $log = $this->logger; $redis = $this->redisDb; $app->server->push(function ($message) use ($app, $log, $redis) { //消息接收 $openid = $message[‘FromUserName‘]; //微信用户信息 $user = $app->user->get($openid); $log->info(json_encode($message)); $official_account = new OfficialAccount(); $official_account->replyMessage($message,$user); }); $response = $app->server->serve(); $response->send(); } catch (Exception $e) { $this->logw($e->getMessage()); } }
}

 

二、消息处理

<?php
namespace Wechat;

use ComponentWechatWechat;
use PhalconDi;
use MvcDbFilter;

class OfficialAccount{
public function replyMessage($message ,$data){ switch ($message[‘MsgType‘]) { case ‘event‘: switch ($message[‘Event‘]) { case ‘subscribe‘: $restaurant_id = 0; $restaurant_str = $message[‘EventKey‘]; .... //业务逻辑处理
break; case ‘unsubscribe‘: //取消关注return "您已取消关注"; break; case ‘SCAN‘: if ($message[‘EventKey‘]) { $restaurant_id = 0; $restaurant_arr = explode(‘_‘, $message[‘EventKey‘]);
......
break; } return ‘欢迎关注‘; break; case ‘text‘: return ‘收到,但是目前没有接下来的动作‘; break; default: return ‘收到其它消息‘; break; } }
}

 三、demo

$app->server->push(function ($message) { switch ($message[‘MsgType‘]) { case ‘event‘: return ‘收到事件消息‘; break; case ‘text‘: return ‘收到文字消息‘; break; case ‘image‘: return ‘收到图片消息‘; break; case ‘voice‘: return ‘收到语音消息‘; break; case ‘video‘: return ‘收到视频消息‘; break; case ‘location‘: return ‘收到坐标消息‘; break; case ‘link‘: return ‘收到链接消息‘; break; case ‘file‘: return ‘收到文件消息‘; // ... 其它消息 default: return ‘收到其它消息‘; break; } // ...});

 

tp5-微信消息接收和处理

相关文章