demo:登录wx.login 发送 res.code 到后台换取 openId
//测试阶段:点击详情 勾选上不校验合法域名
// 登录 get 异步获取数据
wx.login({
success: res => {
console.log(res);
// 发送 res.code 到后台换取 openId, sessionKey, unionId
//发给服务器端 http://localhost/web/demopro/wechat/getCode.php
wx.request({
url: 'http://localhost/web/demopro/wechat/getCode.php', //仅为示例,并非真实的接口地址
method: "get",
data: {
code: res.code
},
header: {
'content-type': 'application/json' // 默认值
},
success(res) {
//console.log(res.data)
var data = res.data;
var openid = JSON.parse(data).openid;
//得到用户openid,存入数据库
console.log(openid);
}
})
}
})
// 登录 post异步获取数据
wx.login({
success: res => {
console.log(res);
// 发送 res.code 到后台换取 openId, sessionKey, unionId
//发给服务器端 http://localhost/web/demopro/wechat/getCode.php
wx.request({
url: 'http://localhost/web/demopro/wechat/getCode.php', //仅为示例,并非真实的接口地址
method: "post",
data: {
code: res.code
},
header: {
'content-type': 'application/x-www-form-urlencoded' // **********************post请求**************
},
success(res) {
//console.log(res.data)
var data = res.data;
var openid = JSON.parse(data).openid;
//得到用户openid,存入数据库
console.log(openid);
}
})
}
})
getCode.php代码如下:
//根据自己请求数据方式修改
$code=$_GET["code"];
//$code=$_POST["code"];
//得到code换取openid
//https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
$url="https://api.weixin.qq.com/sns/jscode2session?appid=wx1a742e9678438791&secret=7dd080428fdd458e1e184a3ab890fd20&js_code=$code&grant_type=authorization_code";
$data=curl($url,"get","https");
echo $data;
//封装curl 抓取数据
function curl($url, $method = "get", $type = "http", $data = "")
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
if ($type == "https") {
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//不做服务器认证
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);//不做客户端认证
}
if ($method == "post") {
curl_setopt($ch, CURLOPT_POST, true);//设置请求是POST方式
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//设置POST请求的数据
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
curl_close($ch);
return json_encode($data);
}