1.微信小程序代码
WXML代码
<!--index.wxml-->
<view class="container">
<view class="userinfo">
<button open-type="getUserInfo" bindgetuserinfo="getUserInfo">头像授权登录</button>
<button open-type="getPhoneNumber" style="margin-top:100rpx" bindgetphonenumber="getPhoneNumber">手机授权</button>
</view>
</view>
js代码(wx.login直接获取code传到后端)
getUserInfo: function ({ detail }) {
var that = this;
wx.login({
success: async (res) => {
wx.request({
url: '后端地址',
method: 'GET',
data: {
code: res.code,
encryptedData: detail.encryptedData,
iv: detail.iv
},
success: function (data) {
console.log(data);(后端直接返回openid)
}
})
}
})
}
2.php后端代码 返回openid
public function get_api_data($code)
{
$appid = "" ;
$secret = "";
$URL = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=$code&grant_type=authorization_code";
$apiData=file_get_contents($URL);
return json_decode($apiData,true);
}