解决了access_token的问题,让我们来看看怎么主动给用户发消息
主动消息有两类,客服消息和模板消息,微信对滥发消息很敏感,所以对这两个功能限制很多,并且,这两个功能也都术语高级接口
客服消息
顾名思义,客服消息是给客服用的,具体限制是:用户给公众号发送过消息后(发送消息、菜单点击、支付成功、用户维权、扫描带参数二维码、订阅),48小时内,开发者可以调用客服消息接口,给该用户发送消息,消息的类型可以是文本、图片、语音、视频、音乐、图文,数据的格式是json~~注意,除了前面讲到的同步回复消息疑问,以后和微信的交互的数据格式都是json
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | //$data可以是字符串,也可能是数组,随具体的$type而改变 public function sendCustom($openId, $data, $type = 'text'){ $msg = array( 'touser' => $openId, ); switch($type){ case 'text': $msg['msgtype'] = 'text'; $msg['text'] = array('content' => urlencode($data)); break; case 'image': $msg['msgtype'] = 'image'; $msg['image'] = array('media_id' => $data); break; case 'voice': $msg['msgtype'] = 'voice'; $msg['voice'] = array('media_id' => $data); break; case 'video': $msg['msgtype'] = 'video'; $msg['video'] = $data; break; case 'music': $msg['msgtype'] = 'music'; $msg['music'] = $data; break; case 'news': $msg['msgtype'] = 'news'; foreach($data as $k => $v){ if(isset($v['title'])) $v['title'] = urlencode($v['title']); if(isset($v['description'])) $v['description'] = urlencode($v['description']); $data[$k] = $v; } $msg['news'] = array('articles' => $data); break; } $url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token='.self::getAccessToken(); $postData = urldecode(json_encode($msg)); $r = Http::httpsPost($url, $postData, true, false); return $r; } |
getAccessToken,是在取access_token
httpsPost和上次说的httpsGet类似,只多了下面的两行,$input即为post的内容:
1 2 | curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $input); |
模板消息
模板消息,没有上面客服消息的限制,但是必须在微信提供的模板框架内拼出消息,如果用户想使用自己的模板,需要特别申请~~基本上很难
首先,从微信公号后台挑选可用的模板,拿到templateId,然后拼装下面结构的post参数:
1 2 3 4 5 6 7 8 | $postData = array( "touser" => $openId,//接受者 "template_id" => $templateId, //data为模板内的实际内容,字段项目视具体模板而定 "data" => array("NAME"=>"里斯之泪", "PRICE"=>"¥10000.00"), "url" => "http://xxxx.xxx.com/xxxx", "topcolor" => "#333",//顶栏颜色 ); |
然后整理数据、调用接口就ok了
1 2 | $postData = json_encode($postData); $r = Http::httpsPost($url, $postData); |
————
转载请注明出处: http://www.jiangkl.com/2014/01/custom-send_template/