vue中代码:
<template> <div> <i-button open-type="getUserInfo" @getuserinfo="onGotUserInfo1" type="success" class="login" shape="circle" size="large">微信授权登录</i-button> </div> </template> <script> import card from '@/components/card' import * as userApi from '../api/userApi' export default { data () { return { motto: 'Hello miniprograme', userInfo: { } } }, components: { card }, methods: { onGotUserInfo1: function () { getCode(); function getCode(){ wx.login({ //调用login获取code withCredentials: true, success (res) { var code = res.code; getUserInfo(code); }, }) } function getUserInfo(code){ wx.getUserInfo({//调用getUserInfo获取用户信息 success: function (res) { var data = { code:code, nickName:res.userInfo.nickName, wSex:res.userInfo.gender, wAvatarurl:res.userInfo.avatarUrl } userApi.openid(data).then(resa => { mpvue.reLaunch({url:'/pages/index/main'}) }) }, fail: function () { console.log('获取用户信息失败') } }) } } }, } </script> <style scoped> .login{ margin-top: 20px; display: flex; align-items: center; justify-content: center; } </style>
配置mpvue中获取用户信息的步骤
1. 进入到node_modules --> mpvue --> index.js,操作index.js文件
2. 操作LIFECYCLE_HOOKS
在 LIFECYCLE_HOOKS 字段中添加'onGetUserInfo'
在initMP(方法里判断 mpType 格式时除 app component 的 else 里添加方法)
, onGetUserInfo: function onGetUserInfo (options) { callHook$1(rootVueVM, 'onGetUserInfo', options) }
实现:
Controller层:
@ResponseBody @GetMapping("/AddWxuser") public AjaxMessage AddWxuser(String code,String nickName,Integer wSex,String wAvatarurl){ //小程序唯一标识 (在微信小程序管理后台获取) String wxspAppid = "wxf8607bb74fad8980"; //小程序的 app secret (在微信小程序管理后台获取) String wxspSecret = "79e342bb55957552c44f53825aa76cff"; //授权(必填) String grant_type = "authorization_code"; //1、向微信服务器 使用登录凭证 code 获取 session_key 和 openid //请求参数 String params = "appid=" + wxspAppid + "&secret=" + wxspSecret + "&js_code=" + code + "&grant_type=" + grant_type; //发送请求 String sr = HttpRequest.sendGet("https://api.weixin.qq.com/sns/jscode2session", params); //解析相应内容(转换成json对象) // JSONObject json = JSONObject.fromObject(sr); JSONObject json = JSON.parseObject(sr); //获取会话密钥(session_key) String session_key = json.get("session_key").toString(); //用户的唯一标识(openid) String openid = (String) json.get("openid"); Wxuser wu = new Wxuser(); wu.setwNickname(nickName); wu.setwAvatarurl(wAvatarurl); wu.setwOpenid(openid); if(wSex == 1){ wu.setwSex("男"); }else{ wu.setwSex("女"); } AjaxMessage ajaxMessage = wxuserFeign.AddWxuser(wu); return ajaxMessage; }