自定義微信公眾號的個性化菜單欄

問題描述:

  今天接到一個小任務,要求利用介面來設置不同用戶訪問微信公眾號時顯示不同的菜單欄任務,對用戶劃分人群。第一次接手這樣的任務,於是就在網上一頓亂搜,結果搞了半天,浪費了一上午的時間,始終報如下錯誤:

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"
}