您的位置:首页 > 移动开发 > 微信开发

从零开始开发微信小程序(四):微信小程序绑定系统账号并授权登录之后台端

2018-02-05 00:00 447 查看
1. 后台开发环境:

语言:java

框架:springboot

2. 代码示例:

package com.zc.wechat.web;

import com.zc.common.api.util.Result;
import com.zc.wechat.model.Token;
import com.zc.wechat.model.app.Jscode2sessionResult;
import com.zc.wechat.service.WechatAppService;
import com.zc.wechat.service.WechatServerService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;

@Controller
@RequestMapping("/wechat")
public class WechatController {

@Value("${wechat.appid}")
private String appid;

@Autowired
private WechatServerService wechatServerService;
@Autowired
private WechatAppService wechatAppService;

/**
* 获取登录系统的token
*
* @return
*/
@RequestMapping(value = "/user/getToken", method = {RequestMethod.GET})
@ResponseBody
public Result<Token> getToken(@RequestParam(value = "code") String code) throws IOException {
final String appId = appid;
Jscode2sessionResult openidResult = wechatAppService.getJscode2session(appId, code, "authorization_code");
Result<Token> result = new Result();
Token token = wechatServerService.getTokenByOpenid(openidResult.getOpenid());
result.setResult(token);
return result;
}

@RequestMapping(value = "/user/bind", method = {RequestMethod.POST})
@ResponseBody
public Result<Token> bindUser(@RequestParam(value = "userName") String userName,
@RequestParam(value = "password") String password,
@RequestParam(value = "state", required = false) String state,
@RequestParam(value = "code") String code) {
Result<Token> result = new Result();
if(!wechatServerService.checkUser(userName, password)){
result.setStatus(Result.STATUS_FAIL);
return result;
}
final String appId = appid;
Jscode2sessionResult openidResult = wechatAppService.getJscode2session(appId, code, "authorization_code");
String openid= openidResult.getOpenid();
if(StringUtils.isEmpty(openid)){
result.setStatus(Result.STATUS_FAIL);
return result;
}
if(!wechatServerService.bindUser(userName, openid)){
result.setStatus(Result.STATUS_FAIL);
return result;
}
result.setResult(wechatServerService.getTokenByOpenid(openid));
return result;
}
}

说明:bindUser方法获取从小程序端传过来的参数,其中userName和password是自身系统的用户名密码,code是上一篇帖子里提到的微信小程序的code,通过微信的API接口拿到openid,和自身的系统进行绑定。getToken方法是获取auth2的用户token,以后用户进入小程序后,去拿token,没有的话跳转到绑定页面。用户的其他请求都要带上token,这样就能判断登录用户了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息