微信公眾號菜單開發以及授權詳細說明
阿新 • • 發佈:2017-09-07
htm 用戶 授權 例子 acc inf nec encode ima
主代碼請參考:http://www.cnblogs.com/hopelooking/p/7463934.html
難點解析:
在微信創建菜單的時候我們慣用的是curl,但是菜單中難免是要有中文的,如果你的php版本是5.4版本的話,那麽一定會報錯的,主要錯誤原因是對象或者字符串之間的錯誤,那麽我們在使用json_encode的時候就不能單純的只是json一下了,應該json_encode($data,JSON_UNESCAPED_UNICODE)
例子:
public function actionSetMenu(){
if(!empty(Yii::$app->session[‘wx_token‘])){
$token = Yii::$app->session[‘wx_token‘];
}else{
$token = self::actionGetToken();
}
$url = ‘https://api.weixin.qq.com/cgi-bin/menu/create?access_token=‘.$token;
$data = array(
‘button‘=>array(
array(
‘type‘=>‘view‘,
‘name‘=>‘廣告投放‘,
‘url‘=>‘http://fx.peita.net/adShared/pages/home.html‘
),
array(
‘name‘=>‘我的‘,
‘sub_button‘=>array(
array(
‘type‘=>‘view‘,
‘name‘=>‘充值‘,
‘url‘=>‘http://www.peita.net‘
),
array(
‘type‘=>‘click‘,
‘name‘=>‘查看余額‘,
‘key‘=>‘balance‘
)
)
),
),
);
//創建菜單
$res= self::actionCurlRequest($url,json_encode($data,JSON_UNESCAPED_UNICODE));
return $res;
}
好了我們設置好菜單以後,怎麽讓跳轉的頁面獲取到用戶信息呢?
這裏考慮的是微信網頁開發文檔中給出的“網頁授權”
那麽我們就可以通過code換取token這個接口獲取到返回信息中的openid,這下就可以正常運行了!
參考地址:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842
示例代碼:
public function actionCodeGetUserInfo(){
$code = Yii::$app->request->get(‘code‘);
$url = ‘https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx69c7f72146629b05&secret=7367d829b543a55dc99ddf01c9ca0023&code=‘.$code.‘&grant_type=authorization_code‘;
$res = json_decode(self::actionCurlRequest($url));
$openid = $res->openid;
$data = WxUser::find()->where([‘openid‘=>$openid])->one();
if(empty($data)) return Helper::format_data(SUCC,null);
return Helper::format_data(SUCC,$data);
}
public function actionSetMenu(){
if(!empty(Yii::$app->session[‘wx_token‘])){
$token = Yii::$app->session[‘wx_token‘];
}else{
unset(Yii::$app->session[‘wx_token‘]);
$token = self::actionGetToken();
}
$url = ‘https://api.weixin.qq.com/cgi-bin/menu/create?access_token=‘.$token;
$data = array(
‘button‘=>array(
array(
‘type‘=>‘view‘,
‘name‘=>‘廣告投放‘,
‘url‘=>‘https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx69c7f72146629b05&redirect_uri=http://fx.peita.net/adShared/index.html&response_type=code&scope=snsapi_base&state=123&connect_redirect=1#wechat_redirect‘
),
array(
‘name‘=>‘我的‘,
‘sub_button‘=>array(
array(
‘type‘=>‘view‘,
‘name‘=>‘充值‘,
‘url‘=>‘http://www.peita.net‘
),
array(
‘type‘=>‘click‘,
‘name‘=>‘查看余額‘,
‘key‘=>‘balance‘
)
)
),
),
);
THANKS!
微信公眾號菜單開發以及授權詳細說明