自定义微信公众号的个性化菜单栏

问题描述:

  今天接到一个小任务,要求利用接口来设置不同用户访问微信公众号时显示不同的菜单栏任务,对用户划分人群。第一次接手这样的任务,于是就在网上一顿乱搜,结果搞了半天,浪费了一上午的时间,始终报如下错误:

array(2) {
  ["errcode"] => int(40001)
  ["errmsg"] => string(89) "invalid credential, access_token is invalid or not latest rid: 5faf79a3-00fe0a19-5cca1349"
}

  按照报错的提示说,不是有效的access_token或者不是最新的,然后又一直的打印代码查看access_token值,结果并没有发现有不一样的地方。心态崩了~

发现原因:

  最后查看官方文档发现,所需要的access_token原来是有两个值,现在使用的这个access_token是这个返回给我的,下面的是一个第三方授权的请求

 $url = "//api.weixin.qq.com/sns/oauth2/access_token?appid={$appid}&secret={$appsecret}&code={$code}&grant_type=authorization_code";
        return $this->httpGetForJson($url);

  正确的获取access_token应该是请求下面的url

$appId=$config['appid'];
$appSecret=$config['appsecret'];
$url ='//api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appId.'&secret='.$appSecret;
$arr = $this->http_curl($url,'get','json');

通关大道:

 1  public function getAccessToken(){
 2 //先获取access_token
 3 $appId=$config['appid'];
 4 $appSecret=$config['appsecret'];
 5 $url ='//api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appId.'&secret='.$appSecret;
 6 $arr = $this->http_curl($url,'get','json');
 7 $access_token = $arr['access_token'];
 8  return $access_token;
 9 }
10 
11 //创建菜单 
12 public function createMenu(){
13         $access_token = $this->getAccessToken();
14         $url = "//api.weixin.qq.com/cgi-bin/menu/create?    
15 access_token=".$access_token;
16 $button=array(
17             array(
18             'type'=>'view',
19             'name'=>'未来科技',
20             'url'=>'//www.baidu.com'
21                 ),
22             array(
23                 'name'=>"We*小店",
24                 'sub_button'=>array(
25                     array(
26                         'type'=>'click',
27                         'name'=>'我的订单',
28                         'key'=>'ORDER'
29                     ),
30                     array(
31                         'type'=>'view',
32                         'name'=>'我的中心',
33                         'url'=>'//www.baidu.com'
34                     ),
35                 )
36             )
37         );
38 //转化成json的格式
39         $arrayJson = urldecode(json_encode($array,JSON_UNESCAPED_UNICODE));
40         $res = $this->http_curl($url,'post','json',$arrayJson);
41         dump($res);
42     }

成功提示:

array(2) {
  ["errcode"] => int(0)
  ["errmsg"] => string(2) "ok"
}

tip小陷阱:

1.烦人的报错代码:

解决方案:检查菜单栏设置的url是否是有效的url(已备案且能正常访问的链接)

array(2) {
  ["errcode"] => int(40054)
  ["errmsg"] => string(61) "invalid sub button url domain rid: 5faf808f-4e6897ec-0bf2ff16"
}