1. 开发前准备
- 注册微信公众号完成信息填写等;
- 配置网页授权域名;
2. 前端开发
- onLoad()中初始化临时code
onLoad(options) {
this.initWechatParams();
}
- initWechatParams
async initWechatParams() {
const _this = this;
_this.loginParams.appId = "*****";
//解析URL的参数,获取临时code
//code作为换取access_token的票据,code只能使用一次,5分钟未被使用自动过期
const {code} = helper.getURLParams(window.location.search);
//const code = '021W1lFa1mTcFB0igWFa1nXBD84W1lFv';
if (!code) {
//baseOauth2URL: 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=snsapi_base&state=123#wechat_redirect'
window.location.href = constData.baseOauth2URL.replace("APPID", "******").replace("REDIRECT_URI", "*****");
} else {
// 已取得临时code,存到参数上
_this.loginParams.code = code;
}
}
- 提交按钮(h5Auth)
async submit() {
const _this = this;
//其它业务逻辑
_this.btnLoading = true;
uni.showLoading({mask: true});
await _this.$http.post(h5Auth, _this.loginParams).then(res => {
_this.btnLoading = false;
uni.hideLoading();
if (200 === res.code) {
//成功,业务操作
} else {
_this.showToast('none', res.message);
}
}).catch(err=> {
_this.btnLoading = false;
uni.hideLoading();
_this.showToast('none', err);
});
}
- getURLParams
getURLParams(url) {
let obj = {};
if (url.indexOf("?") != -1) {
let str = url.substr(url.indexOf("?") + 1);
let strs = str.split("&");
for (let i = 0; i < strs.length; i++) {
obj[strs[i].split("=")[0]] = (strs[i].split("=")[1]);
}
}
return obj;
}
3. 后端开发
- 通过临时code获取用户信息
@PostMapping(value = "/h5/h5Auth")
@ResponseBody
public ResponseResult h5Auth(@RequestBody WechatH5AuthBean params) throws Exception {
return wechatService.h5Auth(params);
}
public ResponseResult h5Auth(WechatH5AuthBean params) {
String code = params.getCode();
if (StringUtils.isEmpty(code)) {
return new ResponseResult(ResponseResult.ERROR_400, "临时CODE未初始化,请刷新界面重试");
}
//accessTokenURL:https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
String url = accessTokenURL.replace("APPID", "****").replace("SECRET", "****").replace("CODE", code);
ResponseEntity<WechatResultBean> entity = this.restTemplate.getForEntity(url, WechatResultBean.class, new Object[0]);
if (ResponseResult.SUCCESS != entity.getStatusCodeValue()) {
return new ResponseResult(ResponseResult.ERROR_405, "微信授权登录失败");
}
WechatResultBean wechatResultBean = (WechatResultBean) entity.getBody();
logger.info("webAccessTokenResult1=======>" + wechatResultBean);
if (null != wechatResultBean) {
//code作为换取access_token的票据,每次用户授权带上的code将不一样,code只能使用一次,5分钟未被使用自动过期
String errcode = wechatResultBean.getErrcode();
if ("40029".equals(errcode)) {
return new ResponseResult(ResponseResult.ERROR_405, "无效的临时code");
}
String accessToken = wechatResultBean.getAccess_token();
logger.info("accessToken1=======>" + accessToken);
if (StringUtils.isEmpty(accessToken)) {
return new ResponseResult(ResponseResult.ERROR_405, "微信授权登录失败");
}
//目前H5的授权只需要拿到openId,并存入数据即可
String openId = wechatResultBean.getOpenid();
logger.info("openId1=======>" + openId);
if (StringUtils.isEmpty(openId)) {
return new ResponseResult(ResponseResult.ERROR_405, "微信授权登录失败");
}
//如有必要再进行下一步获取用户信息
//this.getUserInfo(accessToken, openId);
//业务操作
}
return new ResponseResult(ResponseResult.ERROR_400,"微信授权登录失败");
}
private ResponseResult getUserInfo(String accessToken, String openId) throws Exception {
//userInfoURL:https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
String url = userInfoURL.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);
ResponseEntity<WechatUserEntity> entity = this.restTemplate.getForEntity(url, WechatUserEntity.class, new Object[0]);
WechatUserEntity wechatUserEntity = (WechatUserEntity) entity.getBody();
if (null == wechatUserEntity || StringUtils.isEmpty(wechatUserEntity.getOpenid())) {
return new ResponseResult(ResponseResult.ERROR_405, "微信授权登录失败");
}
//wechatUserEntity即用户信息
//进行业务操作...
return new ResponseResult( ResponseResult.SUCCESS,"微信授权登录成功", user);
}