微信小程序授权一般可以获取用户的openid、昵称、头像、用户所在省和市、性别
第一步:调用wx.login获得code,后台接口用code去微信服务器得到openId
第二步:用open-type=
"getUserInfo"这样的button得到userInfo,包含了用户的头像、昵称等信息,但没有openId
①、接着是获取用户openid,需要用到微信的wx.login函数
1 2 3 4 5 6 7 8 9 10 11 12 | bindGetUserInfo(res) { let info = res; if (info.detail.userInfo) { console.log( "点击了同意授权" ); wx.login({ success: function (res) { console.log(res); } }) } else { console.log( "点击了拒绝授权" ); } |
此时为微信会返回一个临时登录凭证code,只有获取了这个code才能进一步获取openid 和session_key
①、首先引导用户点击授权按钮
1 | <button open-type= "getUserInfo" bindgetuserinfo= "bindGetUserInfo" >点击授权</button> |
②、然后编写bindGetUserInfo函数:
1 2 3 4 5 6 7 8 | bindGetUserInfo(res) { console.log(res); if (res.detail.userInfo) { console.log( "点击了同意授权" ); } else { console.log( "点击了拒绝授权" ); } } |
③、此时会出现一个弹出框,
④、点击允许会返回用户除了openid以外的基本信息:
⑦、请求服务端后台,让后台请求微信再返回openid和session_key,再用微信的本地缓存保存用户的基本信息
官方文档建议:会话密钥session_key 是对用户数据进行加密签名的密钥。为了应用自身的数据安全,开发者服务器不应该把会话密钥下发到小程序,也不应该对外提供这个密钥
请求前端代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | bindGetUserInfo(res) { let info = res; console.log(info); if (info.detail.userInfo) { console.log( "点击了同意授权" ); wx.login({ success: function (res) { if (res.code) { wx.request({ url: 'http://www.test.com/test' , data: { code: res.code, nickName: info.detail.userInfo.nickName, city: info.detail.userInfo.city, province: info.detail.userInfo.province, avatarUrl: info.detail.userInfo.avatarUrl }, header: { 'content-type' : 'application/json' // 默认值 }, success: function (res) { var userinfo = {}; userinfo[ 'id' ]=res.data.id; userinfo[ 'nickName' ] = info.detail.userInfo.nickName; userinfo[ 'avatarUrl' ] = info.detail.userInfo.avatarUrl; wx.setStorageSync( 'userinfo' , userinfo); } }) } else { console.log( "授权失败" ); } }, }) } else { console.log( "点击了拒绝授权" ); } } |
请求后台代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | public static $appid = '你的appid' ; public static $secret = '你的密钥' ; public function test() { $params =Request::instance()->param(); $url = "https://api.weixin.qq.com/sns/jscode2session?appid=" .self:: $appid . "&secret=" .self:: $secret . "&js_code=" . $params [ 'code' ]. "&grant_type=authorization_code" ; $data = $this ->doCurl( $url ); $info [ 'openid' ]= $data ->openid; //获取到用户的openid $info [ 'avatar' ]= $params [ 'avatarUrl' ]; $info [ 'province' ]= $params [ 'province' ]; $info [ 'city' ]= $params [ 'city' ]; $info [ 'nickName' ]= $params [ 'nickName' ]; return json([ 'status' =>1]); } public function doCurl( $url ) { $curl = curl_init(); // 使用curl_setopt()设置要获取的URL地址 curl_setopt( $curl , CURLOPT_URL, $url ); // 设置是否输出header curl_setopt( $curl , CURLOPT_HEADER, false); // 设置是否输出结果 curl_setopt( $curl , CURLOPT_RETURNTRANSFER, 1); // 设置是否检查服务器端的证书 curl_setopt( $curl , CURLOPT_SSL_VERIFYPEER, false); // 使用curl_exec()将CURL返回的结果转换成正常数据并保存到一个变量 $data = curl_exec( $curl ); // 使用 curl_close() 关闭CURL会话 curl_close( $curl ); return json_decode( $data ); } |