配置带参数的二维码同样需要先获取Access Token,获取方法在上一篇文章中有描述:http://www.cnblogs.com/leoyoungblog/p/5032249.html。
利用获取到的Access Token,可以创建二维码的Ticket。通过POST方法向服务器提交相关信息,JS代码如下:
1 function getTicket() 2 { 3 var url = "qrcode_manage.php?access_token="+$("#accessToken").val(); 4 var qrcode_type = $("#qrType").val(); 5 var qrcode_scene_id = $("#qrSceneId").val(); 6 $.post(url, 7 { 8 "qrcode_type":qrcode_type, 9 "qrcode_scene_id":qrcode_scene_id 10 }, 11 function (data,status) { 12 var result = eval("("+data+")"); 13 $("#ticketInfo").css("display","block"); 14 if(typeof (result["errcode"])!="undefined") 15 { 16 var errorInfo = "错误代码:"+result["errcode"]+";错误信息:"+result["errmsg"]; 17 $("#ticketInfo").html(errorInfo); 18 $("#getQrcodeBtn").attr("disabled","disabled"); 19 } 20 else 21 { 22 var successInfo = "获取Ticket 成功,Ticket:" + result["ticket"]; 23 successInfo += "<br>url:" + result["url"]; 24 $("#ticket").val(result["ticket"]); 25 $("#ticketInfo").html(successInfo); 26 $("#getQrcodeBtn").removeAttr("disabled"); 27 } 28 } 29 ); 30 }
服务器端进行转发的PHP代码如下:
1 $access_token = $_GET["access_token"]; 2 $api_url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token={$access_token}"; 3 $qrcode_type = $_POST["qrcode_type"]; 4 $qrcode_scene_id = (int)$_POST["qrcode_scene_id"]; 5 $qrcode_array = array(); 6 if($qrcode_type == "QR_SCENE") 7 { 8 $qrcode_array["expire_seconds"] = 604800; //七天 9 $qrcode_array["action_name"] = "QR_SCENE"; 10 } 11 else 12 { 13 $qrcode_array["action_name"] = "QR_LIMIT_SCENE"; 14 } 15 16 $qrcode_array["action_info"]["scene"]["scene_id"] = $qrcode_scene_id; 17 $qrcode_json = json_encode($qrcode_array); 18 $ch = curl_init(); 19 curl_setopt($ch,CURLOPT_URL,$api_url); 20 curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); 21 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 22 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); 23 curl_setopt($ch, CURLOPT_POST, 1); 24 curl_setopt($ch, CURLOPT_POSTFIELDS, $qrcode_json); 25 $json_result = curl_exec($ch); 26 curl_close($ch); 27 echo $json_result;
之后,可以通过Ticket换取二维码,JS代码如下:
1 function getQrcode() 2 { 3 var ticket = $("#ticket").val(); 4 var date = new Date(); 5 var url = "qrcode_manage.php?ticket="+ticket+"&time="+date.getTime(); 6 $("#qrcode").attr("src","qrcode_manage.php?ticket="+ticket+"&time="+date.getTime()); 7 }
服务器端进行转发的PHP代码如下:
$ticket = $_GET["ticket"]; $api_url = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket={$ticket}"; $ch = curl_init(); curl_setopt($ch,CURLOPT_URL,$api_url); curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); $qrcode_result = curl_exec($ch); curl_close($ch); echo $qrcode_result;
实现效果可访问: