微信开发JS代码
wx.login({
success: res => {
// 发送 res.code 到后台换取 openId, sessionKey, unionId
var that =this;
wx.request({
url:that.globalData.url+'/api.openid/getOpenid',
method:"post",
data:{code:res.code},
success:res=>{
console.log(res.data);
}
})
}
})
下面是服务器端口的代码
protected $appid = "1";
protected $secret = "2";
protected $grant_type = "authorization_code";
public function getOpenid(){
$res = request()->param();
$url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $this->appid . '&secret=' . $this->secret . '&js_code=' . $res['code'] . '&grant_type=' . $this->grant_type;
$result=$this->http_curl_get($url);
//数据就这这里了[2023-05-16T12:00:07+08:00][info] {"session_key":"R+WxJUIZclFujKdbIkpr6w==","openid":"oSvY85S3DdIx2JfX-aEg_ffmkjDw"}
}
public function http_curl_get($url,$type=1) {
$curl = curl_init();
curl_setopt($curl,CURLOPT_TIMEOUT,5000);
curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,false);
curl_setopt($curl,CURLOPT_USERAGENT,$_SERVER['HTTP_USER_AGENT']);
curl_setopt($curl,CURLOPT_URL,$url);
if($type == 1){
curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
}
$res = curl_exec($curl);
if($res){
curl_close($curl);
return json_decode($res,true);
}else {
$error = curl_errno($curl);
curl_close($curl);
return $error;
}
}
如果出现报错:
{"errcode":40029,"errmsg":"invalid code, rid: 6462ff8e-7f84dae1-58556329"}
检查3个步骤:
1:检查小程序内部设置请求域名是否填写
2:检查appid、AppSecret等参数密码是否正确
3:再调试微信里检查自己的APPid 是否和请求appid一致