标签:
由于JS脚本跨域访问的问题,无法通过jQuery的Ajax方法直接调用微信的API,故采用服务器端转发的方式与微信API交互。
配置自定义菜单须先获取Access Token,前端JS代码如下:
1 function getAccessToken() 2 { 3 var appidParam = $("#appid").val(); 4 var secretParam = $("#secret").val(); 5 var date = new Date(); 6 var url = "get_access_token.php?appid="+appidParam+"&secret="+secretParam+"&time="+date.getTime(); 7 $.get(url, function (data,status) { 8 var result = eval("("+data+")"); 9 $("#info").css("display","block"); 10 if(typeof (result["errcode"])!="undefined") 11 { 12 var errorInfo = "错误代码:"+result["errcode"]+";错误信息:"+result["errmsg"]; 13 $("#info").html(errorInfo); 14 $("#changeBtn").attr("disabled","disabled"); 15 } 16 else 17 { 18 var successInfo = "获取Access Token 成功:" + result["access_token"]; 19 $("#accessToken").val(result["access_token"]); 20 $("#info").html(successInfo); 21 $("#changeBtn").removeAttr("disabled"); 22 } 23 }) 24 25 }
服务器端使用PHP的curl工具进行转发,代码如下:
1 $appid = $_GET["appid"]; 2 $secret = $_GET["secret"]; 3 $api_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}"; 4 $ch = curl_init(); 5 curl_setopt($ch,CURLOPT_URL,$api_url); 6 curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); 7 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 8 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); 9 $json_result = curl_exec($ch); 10 curl_close($ch); 11 echo $json_result;
利用获取到的 Access Token,下一步可以配置自定义菜单。目前还需要自己编写自定义菜单的JSON,以后有时间会加上可视化界面。通过POST方法向服务器提交JSON的JS代码如下:
1 function changeButton() 2 { 3 var url = "button_manage.php?access_token="+$("#accessToken").val(); 4 var button_json = $("#buttonBody").val(); 5 $.post(url,{"button_json":button_json}, function (data,status) { 6 var result = eval("("+data+")"); 7 if(result["errcode"] == 0) 8 { 9 alert("配置成功"); 10 } 11 else 12 { 13 alert("配置失败,错误代码:"+result["errcode"]+"错误信息:"+result["errmsg"]); 14 } 15 }) 16 }
服务器端的PHP代码如下:
1 $access_token = $_GET["access_token"]; 2 $api_url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token={$access_token}"; 3 $button_json = $_POST["button_json"]; 4 $ch = curl_init(); 5 curl_setopt($ch,CURLOPT_URL,$api_url); 6 curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); 7 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 8 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); 9 curl_setopt($ch, CURLOPT_POST, 1); 10 curl_setopt($ch, CURLOPT_POSTFIELDS, $button_json); 11 $json_result = curl_exec($ch); 12 curl_close($ch); 13 echo $json_result;
实现效果可访问:
http://leo07.sinaapp.com/button_manage.html
标签:
原文地址:http://www.cnblogs.com/leoyoungblog/p/5032249.html