1. 开发前准备
- 申请微信小程序,完成相关信息填写
2. 前端开发
- 初始化openId和sessionKey
async initWechat_MP() {
const _this = this;
console.log('wechat==========>', _this.wechat);
if (_this.wechat && _this.wechat.openId && _this.wechat.sessionKey) {
return;
}
uni.login({
success: res => {
if (!res.code) return;
//通过code获取openId和sessionKey
_this.$http.post(mpCetOpenIdSessionKey, {code: res.code}).then(result => {
// 存储给前端的openId和sessionKey
console.log('code=======>', result.code);
if (200 === result.code) {
console.log('data=========>', result.data);
_this.wechat = result.data;
} else {
_this.$mHelper.toast('初始化微信授权登录参数失败,请退出当前界面重新进入', 3000);
}
}).catch(e => {
_this.$mHelper.toast('初始化微信授权登录参数失败,请退出当前界面重新进入', 3000);
});
},
fail: res => {
console.log('res', res);
_this.$mHelper.toast('初始化微信授权登录参数失败,请退出当前界面重新进入', 3000);
}
});
}
- “授权”按钮(必须添加open-type=“getUserInfo”)
<button
:disabled="btnLoading"
:loading="btnLoading"
class="wechat-auth-btn"
open-type="getUserInfo"
@tap="authClickHandle"
>
<image class="image" :src="wechatLogo"/>
</button>
- 点击“授权”按钮拉起授权
getUserProfile_MP() {
const _this = this;
wx.getUserProfile({
//desc的长度不能超过30个字符
desc: "同意授权查看附近更多商户",
success: res => {
console.log('res=======>', res)
if (res.errMsg === 'getUserProfile:ok' && res.encryptedData) {
//获取用户信息
_this.getUserInfo_MP(res);
}
},
fail: res => {
//拒绝授权
console.log('失败', JSON.stringify(res));
_this.btnLoading = false;
_this.$mHelper.toast('授权失败');
return;
}
});
},
//小程序获取用户信息
getUserInfo_MP(res) {
const _this = this;
wx.showLoading({title: '正在登录...'});
_this.$http.post(mpWechatAuth, {
wechatUser: res.userInfo,
miniName: 'mpshop',
iv: res.iv,
..._this.wechat,
unionId: '',
signature: res.signature
}).then(async result => {
console.log('授权结果==========>', result);
wx.hideLoading();
_this.btnLoading = false;
const user = result.data;
if (200 === result.code && user.accessToken) {
_this.$mHelper.toast('授权登录成功');
//重定向到首页(这句话放到后面,就不能跳转了)
if (!user.mobile) {
//如果之前未绑定过手机号了(也就是手机号为空),进入绑定手机号页码
_this.$mRouter.push({route: '/pages/public/bind-mobile'});
} else {
//如果之前已经绑定过手机号了(也就是手机号不为空),进入首页
_this.$mRouter.reLaunch({route: '/pages/index/index'});
}
//把登录数据保存
_this.$mStore.commit('login', user);
}
}).catch(() => {
_this.btnLoading = false;
});
}
3. 后端开发
- 根据code获取openId和sessionKey
public ResponseResult mpCetOpenIdSessionKey(WechatMPAuthBean query) {
String wxCode = query.getCode();
logger.info("临时code=================>" + wxCode);
if (StringUtils.isEmpty(wxCode)) {
return new ResponseResult(ResponseResult.ERROR_400, "微信临时code为空,请退出小程序重新进入");
}
Map<String, Object> jsonObject = getOpenIdSessionKeyByCode(wxCode, "appId", "appSecret");
if (null == jsonObject) {
return new ResponseResult(ResponseResult.ERROR_400, "微信临时code为空,请退出小程序重新进入");
}
if (!jsonObject.containsKey("openid")) {
return new ResponseResult(ResponseResult.ERROR_400, "微信临时code为空,请退出小程序重新进入");
}
//微信返回的openId
Object openId = jsonObject.get("openid");
logger.info("openid=================>" + openId);
//微信返回的sessionKey
Object sessionKey = jsonObject.get("session_key");
logger.info("sessionKey=================>" + sessionKey);
Map<String, Object> map = new HashMap<>(2);
map.put("openId", openId);
map.put("sessionKey", sessionKey);
return new ResponseResult(map);
}
public Map<String, Object> getOpenIdSessionKeyByCode(String code, String appId, String appSecret) {
Map<String, String> requestUrlParam = new HashMap<String, String>();
//开发者设置中的appId
requestUrlParam.put("appid", appId);
//开发者设置中的appSecret
requestUrlParam.put("secret", appSecret);
//小程序前端调用wx.login返回的临时code
requestUrlParam.put("js_code", code);
//默认参数
requestUrlParam.put("grant_type", "authorization_code");
//jsCode2SessionUrl:https://api.weixin.qq.com/sns/jscode2session
return JSON.parseObject(HttpUtil.sendPost(jsCode2SessionUrl, requestUrlParam));
}
- 授权操作(其实没什么操作)
public ResponseResult mpAuth(WechatMPAuthBean query) {
//TODO 授权在前端已经完成,业务操作
return new ResponseResult();
}
- WechatBean
@Data
public class WechatBean {
@Data
public static class WechatUserBean {
//微信用户头像https://
private String avatarUrl;
//国家China
private String country;
//省份Yunnan
private String province;
//城市Kunming
private String city;
//性别 1男 0女
private String gender;
//语言zh_CN
private String language;
//微信昵称
private String nickName;
}
@Data
public static class WechatMPAuthBean {
//临时code
private String code;
//微信用户
private WechatUserBean wechatUser;
//小程序的名字
private String miniName;
//加密算法的初始向量
private String iv;
//微信返回的openId(已通过其它接口获取)
private String openId;
//微信返回的sessionKey(已通过其它接口获取)
private String sessionKey;
//未知参数
private String unionId;
//解密的密码
private String signature;
}
}