最全面 think php 实现微信公众号回复编号进行投票,自定义菜单功能
前期准备工作
https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Receiving_standard_messages.html 微信文档
公众号后台,“基本配置”-“服务器配置”,填写服务器地址,注意,填写的方法要经过验证,

test方法只是测试,具体的要看你自己的方法,其中$token就是后台填写的“令牌”,验证通过后,所有在公众号发送的信息,都会转发到所填的链接上,注意:开启服务器配置后,公众号的自定义菜单会失效,公众号的自定义菜单会消失
public function test(){
$nonce = $_GET[‘nonce‘];
$token = ‘*******‘;
$timestamp = $_GET[‘timestamp‘];
$echostr = $_GET[‘echostr‘];
$signature = $_GET[‘signature‘];
//形成数组,然后按字典序排序
$array = array();
$array = array($nonce, $timestamp, $token);
sort($array);
//拼接成字符串,sha1加密 ,然后与signature进行校验
$str = sha1( implode( $array ) );
echo $echostr;
exit;
}$file_in = file_get_contents("php://input"); //接收post数据//用SimpleXML解析POST过来的XML数据$postObj = simplexml_load_string($file_in,‘SimpleXMLElement‘,LIBXML_NOCDATA);$fromUsername = $postObj->FromUserName; //获取发送方帐号(OpenID)$toUsername = $postObj->ToUserName; //获取接收方账号$keyword = trim($postObj->Content); //获取消息内容$masType = $postObj->MsgType;//获取消息类型,可以作分类判断。本例默认是文本消息,不做判断$time = time(); //获取当前时间戳//---------- 返 回 数 据 ---------- ////返回消息模板$textTpl = "<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[%s]]></MsgType><Content><![CDATA[%s]]></Content></xml>";
$msgType = "text"; //消息类型 if($masType != ‘text‘){ $contentStr = "回复内容*****"; }else if(trim($keyword) == ‘‘){ $contentStr = "发送不能为空"; }else if(is_numeric($keyword)){ if(!is_numeric($keyword)||strpos($keyword,".")!==false){ $contentStr = "编号不正确,请查询后再进行投票"; $resultStr = sprintf($textTpl,$fromUsername,$toUsername,$time,$msgType,$contentStr); echo $resultStr; return; } $data1[‘toupiao_time‘] = date("Y-m-d"); $message = M(‘message_cun‘); $b = $message->where("member_id = ‘%s‘ and ip = ‘%s‘ and toupiao_time = ‘%s‘",$keyword,$fromUsername,$data1[‘toupiao_time‘])->count(); if($b > 0 ){ $contentStr = "您已对该项投票,请明天再来!"; $resultStr = sprintf($textTpl,$fromUsername,$toUsername,$time,$msgType,$contentStr); echo $resultStr; return; } $a = $message->where("ip = ‘%s‘ and toupiao_time = ‘%s‘",$fromUsername,$data1[‘toupiao_time‘])->count(); if ($a >= 10) { $contentStr = "您已投满10票,请明天再来!"; $resultStr = sprintf($textTpl,$fromUsername,$toUsername,$time,$msgType,$contentStr); echo $resultStr; return; }else{ $data[‘member_id‘] = $keyword; $data[‘ip‘] =(string) $fromUsername; $data[‘userName‘] = (string) $toUsername; $data[‘toupiao_time‘] = date("Y-m-d"); $res = $message->data($data)->add(); if($res){ $contentStr = "投票成功"; $resultStr = sprintf($textTpl,$fromUsername,$toUsername,$time,$msgType,$contentStr); echo $resultStr; } } }else{ $contentStr = "******回复内容"; }
$resultStr = sprintf($textTpl,$fromUsername,$toUsername,$time,$msgType,$contentStr);echo $resultStr;可以看到,在接受到信息后,获取编号,往记录表中插入一条数据,有两个表,记录表(记录插入的所有票数),投票表(记录要投票的主体,票数),重点:建立一个触发器,在记录表插入时,根据 编号,使投票表中编号对应的票数+1
member_id 就是从微信获取的编号,member_cun就是投票表,code就是投票表中的编号,这样是就实现了微信回复编号,进行投票。

自定义菜单:
开启服务器配置后,之前自定义的菜单就没了,就需要我们通过接口自定义了。
https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Receiving_standard_messages.html 微信文档,
在创建之前,我们可以查询一下 http请求方式: GET(请使用https协议)https://api.weixin.qq.com/cgi-bin/get_current_selfmenu_info?access_token=ACCESS_TOKEN,查询出当前公众号的菜单,创建的时候就不用挨个想之前创建的是啥了,
创建时要注意格式,其他的没有什么特别注意的点,注意发送的json格式一定要对,post请求,可以使用调试工具调试你自己的json格式,

下面是一个可以进行 post请求的方法,
调用如下,其中 $data2 就是json格式的字符串
$res = $this->http("https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$access_token,"POST",$data2);public function http($url, $method, $postfields = null, $headers = array(), $debug = false)
{
$ci = curl_init();
/* Curl settings */
curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ci, CURLOPT_TIMEOUT, 30);
curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
switch ($method) {
case ‘POST‘:
curl_setopt($ci, CURLOPT_POST, true);
if (!empty($postfields)) {
curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields);
$this->postdata = $postfields;
}
break;
}
curl_setopt($ci, CURLOPT_URL, $url);
curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ci, CURLINFO_HEADER_OUT, true);
$response = curl_exec($ci);
$http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
if ($debug) {
echo "=====post data======\r\n";
var_dump($postfields);
echo ‘=====info=====‘ . "\r\n";
print_r(curl_getinfo($ci));
echo ‘=====$response=====‘ . "\r\n";
print_r($response);
}
curl_close($ci);
// return array($http_code, $response);
return $response;
}附上一个json格式,各个参数的意思可以在微信文档中查看,可以放链接,小程序
{
"button": [
{
"name": "***",
"sub_button": [
{
"type": "view",
"name": "***",
"url": "https://www.baidu.com/"
}
]
},
{
"name": "***",
"sub_button": [
{
"type": "miniprogram",
"name": "小程序",
"url": "****",
"appid": "",
"pagepath": ""
}
]
}
]
}其中接口中需要的access_token,需要你通过微信的appid和开发者密码来获取,注意一个过期时间,一天可以访问2000次,access_token的有效期目前为2个小时,需定时刷新,重复获取将导致上次获取的access_token失效,好的做法是建立一个表存token,
判断最后一次获取的时间和当前时间的差,超过多长时间重新获取存库

需要注意的是,ip白名单要添加上,只有添加的ip才可以获取token,还有“公众号设置”-“功能设置”,授权域名要添加,添加的方法都有提示,下载一个txt文档到网站根目录,然后验证就可以了,一遍不行多试几遍,
如果真的因为失误token次数超了,影响业务, 可以在微信后台清空请求次数,再次请求,token一定要存库,不能每次用到都请求新的,不然很容易就超过限制。
$access_time = M("weixin_cun")->order("id desc")->getField("time");
$time = time() - strtotime($access_time);
if($time>2000){
$url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->app_id."&secret=".$this->app_secret;
$content = file_get_contents($url);
$result = json_decode($content);
$data[‘access_token‘] = $result->access_token;
if(!empty($data[‘access_token‘])){
$weixin = M("weixin_cun")->data($data)->add();
}else{
}
}
至此,实现微信公众号回复编号进行投票,自定义菜单功能 完成。