获取的用户的唯一标识openid
思路:
获取openid需要首先使用wx.login()获取登录凭证code,使用code发送wx.request()的get请求,携带参数appid,secret,code给php,php使用file_get_contents()获取返回信息,进而将openid和session_key返回数据给小程序;
返回结果:
小程序示例wxml代码:
给button按钮绑定一个点击事件,view内显示获取成功后的数据(当前只展示openid);
<!-- wxml -->
<button type="primary" bindtap="bindViewTap">获取openid</button>
<view style="height: 80px;width: 750rpx;line-height: 80px;">
获取openid:{{openid}}
</view>
小程序的js代码:
点击事件先执行login()获取code凭证,然后调用requestCode()并传递获取的用户凭证,发送到自己的php后台进行下一步的处理,不设置method,默认发送get请求;
pages({
data: {
phone: '',
openid: '',
},
// 获取code凭证
bindViewTap() {
wx.login({
success: (res) => {
// 调用requestCode() 传递code凭证
this.requestCode()(res.code);
},
})
},
// 接收code凭证,获取手机号
requestCode()(code) {
wx.request({
url: `https://xxx.xxx/getphone.php?openid_code=${code}`,
success: res => {
this.setData({
openid: res.data.openid
})
}
})
}
})
php代码:
php代码较为简单,使用file_get_contents()方式即可;
<?php
// 接收get传参 code;
$code = $_GET['code'];
//你的appid,在小程序公众平台查看
$appid = 'xxxxxxxxxxxxxx';
//你的秘钥,在小程序公众平台获取
$secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$url = "https://api.weixin.qq.com/sns/jscode2session?appid="
. $appid. "&secret="
. $secret . "&js_code="
. $code ."&grant_type=authorization_code";
$wxuserinfo = file_get_contents($url,true);
//获取openid
$openid = json_decode($wxuserinfo,true)['openid'];
//当前返回的只有openid
echo $openid;
/*
如果要获取openid和session_key,可以跳过以下这两步
$wxuserinfo = file_get_contents($url,true);
$openid = json_decode($wxuserinfo,true)['openid'];
执行以下代码即可获取session_key和openid:
$wxuserinfo = file_get_contents($url);
echo $wxuserinfo
*/