<script type="text/javascript">
function callback(result) {
alert(\'cucess\');
alert(result); //输出openid
}
function getQueryString(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
var r = window.location.search.substr(1).match(reg);
if (r != null) return unescape(r[2]); return null;
}
var code = getQueryString("code");
$.ajax({
async: false, url: "", //这是我的服务端处理文件PHP的
type: "GET", //下面几行是jsoup,如果去掉下面几行的注释,后端对应的返回结果也要去掉注释
// dataType: \'jsonp\',
// jsonp: \'callback\', //jsonp的值自定义,如果使用jsoncallback,那么服务器端,要返回一个jsoncallback的值对应的对象.
// jsonpCallback:\'callback\',
data: {code:code}, //传递本页面获取的code到后台,以便后台获取openid
timeout: 5000,
success: function (result) {
callback(result);
},
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus); }
});
</script>
</head><body></body>
后端代码
<?php
$code = $_GET[\'code\'];//前端传来的code值
$appid = "wx468622291a1e99d6";
$appsecret = "98566dc38863aa4395fabebb0de6ecc1";//获取openid
$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$appsecret&code=$code&grant_type=authorization_code";
$result = https_request($url);
$jsoninfo = json_decode($result, true);
$openid = $jsoninfo["openid"];//从返回json结果中读出openid
$access_token = $jsoninfo["access_token"];//从返回json结果中读出openid
$callback=$_GET[\'callback\']; // echo $callback."({result:\'".$openid."\'})";
$url1 = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN";
$result1 = https_request($url1);
$jsoninfo1 = json_decode($result1, true);
$nickname=$jsoninfo1["nickname"];
echo $openid.":".$access_token.":".$nickname; //把openid 送回前端
function https_request($url,$data = null){
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
if (!empty($data)){
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($curl);
curl_close($curl);
return $output;
}