最近做微信公众号开发,遇到一个扯淡的事情,自定义菜单出不来,然而在网页调试工具里面执行就成功了,这个事情就非常尴尬,附上代码给你们感受一下:
public function addMenu()
{
$url = " https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" . getToken();
$menu['button'] = [
[
"name" => "随便玩",
"sub_button" => [
[ "type" => "click",
"name" => "听歌",
"key" => "Listen" ],
[ "type" => "view",
"name" => "百度",
"url" => "http://www.baidu.com"
]
]
],
[
"name" => "日常生活",
"sub_button" => [
[ "type" => "view",
"name" => "天气",
"url" => "http://www.weather.com.cn/"
],
[ "type" => "click",
"name" => "城市天气",
"key" => "city_weather"
],
[ "type" => "click",
"name" => "星座运势",
"key" => "constellation"
]
]
],
[
"name" => "图片",
"sub_button" => [
[ "type" => "scancode_push",
"name" => "自动扫",
"key" => "auto_scanf",
],
[ "type" => "scancode_waitmsg",
"name" => "扫一扫",
"key" => "scanf",
],
[ "type" => "pic_photo_or_album",
"name" => "传图片",
"key" => "photo"
],
[ "type" => "location_select",
"name" => "发送位置",
"key" => "position"
]
]
]
];
$str = json_encode($menu,JSON_UNESCAPED_UNICODE);
file_put_contents('menu.txt',$str);
var_dump(MyCurl::post($url,$str));
}
因为输出结果一直是null,所以不停的找post的问题,代码如下:
public static function post($url,$data)
{
$ch = curl_init() ;
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_HEADER,false);
curl_setopt($ch,CURLOPT_TIMEOUT,10);
curl_setopt($ch,CURLOPT_POST,true);
curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
$content = curl_exec($ch);
curl_close($ch);
return $content;
}
对比网上的代码,实在找不出哪里有错,直到百度到一篇文章才找到问题,原来是在第一段代码的$url里面,刚开始有一个空格、一个空格、空格、、、我嘞个去,坑死人有木有。
以后注意一下吧,尽量少有空格(╥╯^╰╥)