对于新关注的用户,在其关注时直接将其用户信息插入数据库表,方法与同步信息时类似。对于取消关注的用户,使用db助手函数将其从表中删除。其相应代码如下。
1 // 接收事件消息
2 private function receiveEvent($object)
3 {
4 $weixin = new \weixin\Wxapi;
5 $openid = strval($object->FromUserName);
6 $content = "";
7 switch ($object->Event)
8 {
9 case "subscribe":
10 $info = $weixin->get_user_info($openid);
11 $municipalities = array("北京", "上海", "天津", "重庆", "香港", "澳门");
12 $sexes = array("", "男", "女");
13 $data = array;
14 $data['openid'] = $openid;
15 $data['nickname'] = str_replace("'", "", $info['nickname']);
16 $data['sex'] = $sexes[$info['sex']];
17 $data['country'] = $info['country'];
18 $data['province'] = $info['province'];
19 $data['city'] = (in_array($info['province'], $municipalities))?$info
['province'] : $info['city'];
20 $data['scene'] = (isset($object->EventKey) && (stripos(strval($object->
EventKey),"qrscene_")))?str_replace("qrscene_","",$object->EventKey):"0";
21 $data['headimgurl'] = $info['headimgurl'];
22 $data['subscribe'] = $info['subscribe_time'];
23 $data['heartbeat'] = time;
24 $data['remark'] = $info['remark'];
25 $data['score'] = 1;
26 $data['tagid'] = $info['tagid_list'];
27 Db::name('user')->insert($data);
28 $content = "欢迎关注,".$info['nickname'];
29 break;
30 case "unsubscribe":
31 db('user')->where('openid',$openid)->delete;
32 break;
33 default:
34 $content = "";
35 break;
36 }
37 if(is_array($content)){
38 $result = $this->transmitNews($object, $content);
39 }else{
40 $result = $this->transmitText($object, $content);
41 }
42 return $result;
43 }