urlencode,urldecode,微信开发
今天在开发微信自定义菜单的时候碰到问题了,后买你解决了,就分享给大家.构造了一个如下的数组通过curl发送post json数据过去了.结果得到里一个字符集错误的错误提示,后面使用urlencode,及配合urldecode进行了解决.
顺便把贴出来部分代码,有需要直接拿走即可.
function httpCurlPost($url,$json) { //发送json post $ch = curl_init($url); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, $json); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'Content-Length: ' . strlen($json)) ); $result = curl_exec($ch); return($result); } //设置自定义菜单 function setUserMenu() { $url = 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token='.$this->getWXAT(); $arr = array( 'button'=>array( array( 'type'=>'click', 'name'=>'hello', 'key'=>'item1', ), array( 'name'=>urlencode('午饭'), 'sub_button'=>array( array( "name"=>urlencode("歌曲"), "type"=> "click", "key"=>"songs", ), array( "name"=>urlencode('大片'), "type"=>'view', "url"=>'http://iphp.cc' ),// the second two level menu ), 'key'=>'item2', ), array( 'name'=>urlencode('吃晚饭'), 'type'=>'view', 'url'=>'http://www.koalapass.cn', ), ), ); $json = urldecode(json_encode($arr)); $res = json_decode($this->httpCurlPost($url,$json),TRUE); var_dump($res); } //获取wechat token function getWXAT() { if($_SESSION['access_token']&&($_SESSION['expire_time']>time())){ return $_SESSION['access_token']; }else{ $APPID = '你的wei信appid'; $secret = '你的密钥'; $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$APPID.'&secret='.$secret; $arr = json_decode($this->httpCurl($url),TRUE); $_SESSION['access_token'] = $arr['access_token']; $_SESSION['expire_time'] = time()+7000; return $arr['access_token']; } }

