最近做微信小程序,要做一个排行榜的功能,摸索了一天,终于找到获取用户openid,昵称和头像方法。
先上wxml:
<button bindtap="getInfo">test</button><view>{{nickname}}</view><image src="{{headpic}}"></image>
再来js:
/*** 页面的初始数据*/data: {nickname:"",headpic:""},/*** 生命周期函数--监听页面加载*/onLoad: function (options) {wx.login({success (res) {if (res.code) {//发起网络请求wx.request({url: 'http://www.happy360.top/wxlogin.php',data: {code: res.code},success:function(r){console.log(r.data);}})} else {console.log('登录失败!' + res.errMsg)}}})},getInfo:function(){wx.getUserProfile({desc:"test",success:(res)=>{console.log(res);this.setData({nickname:res.userInfo.nickName,headpic:res.userInfo.avatarUrl})}})},
最后后端的php:
<?php $code = $_GET['code'];$appid = '你的微信小程序id';$AppSecret = '你的秘钥';$url = "https://api./sns/jscode2session?appid=".$appid."&secret=".$AppSecret."&js_code=".$code."&grant_type=authorization_code";$str = file_get_contents($url);$json = json_decode($str);$arr = get_object_vars($json);echo $openid = $arr['openid']; //这是openid// echo $session_key = $arr['session_key']; //这是session_key?>
希望对大家有帮助!