PHP微信公众号开发--自定义菜单
- 获取access_token,用到php的curl方法!
get
private function http_request(string $url)
{
$ch = curl_init();
//设置请求的url
curl_setopt($ch, CURLOPT_URL, $url);
//请求头关闭
curl_setopt($ch, CURLOPT_HEADER, 0);
//请求结果以字符串方式返回
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//关闭SSL验证
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
$data = curl_exec($ch);
//判断有无出错
if (curl_errno($ch) > 0)
{
echo curl_error($ch);
$data = 'http请求出错!'.'['.curl_error($ch).']';
}
curl_close($ch);
return $data;
}
post
private function http_request_post($url, $data)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,FALSE);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($curl);
//判断有无出错
if (curl_errno($curl) > 0)
{
echo curl_error($curl);
$output = 'http请求出错!'.'['.curl_error($curl).']';
}
curl_close($curl);
return $output;
}
获取access_token
public function getAccessToken()
{
$mem = new Memcache();
$mem->connect('127.0.0.1', 11211);
$men_name = 'auth_'.self::APPID;
$value = $mem->get($men_name);
if ($value)
{
return $value;
}
$wechat_url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s';
$wechat_url = sprintf($wechat_url, self::APPID, self::APPSECRET);
$json_data = $this->http_request($wechat_url);
$arr = json_decode($json_data, True);
$access_token = $arr['access_token'];
$mem->add($men_name, $access_token, 0, 7200);
return $access_token;
}
- 准备按钮,下面是微信公众平台提供给我们的按钮类型参数说明。
- 准备好请求的参数,根据自己要求设定。
return '{
"button":[
{
"type":"click",
"name":"今日歌曲",
"key":"V1001_TODAY_MUSIC"
},
{
"name":"菜单",
"sub_button":[
{
"type":"view",
"name":"搜索",
"url":"http://www.soso.com/"
},
{
"type":"miniprogram",
"name":"wxa",
"url":"http://mp.weixin.qq.com",
"appid":"wx286b93c14bbf93aa",
"pagepath":"pages/lunar/index"
},
{
"type":"click",
"name":"赞一下我们",
"key":"V1001_GOOD"
}]
}]
}';
- 导入
$menu_list = include "./menu.php";
- 请求接口
public function createMenu($menu)
{
if (is_array($menu))
{
$menu = json_encode($menu, JSON_UNESCAPED_UNICODE);
}
$url = 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token=%s';
$url = sprintf($url, $this->getAccessToken());
$data = $this->http_request_post($url, $menu);
return $data;
}
- 效果如下