由於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