附官方文档地址:小程序登陆 | 微信开放文档
编码前准备工作:开发之前我们需要准备两个东西AppID和AppSecret,需要到微信开放平台(https://open.weixin.qq.com)注册开发者账号,并在移动应用中将我们的APP创建进去,填写对应资料后提交审核
准备工作做好后我们开始实现,我们项目用的是springBoot+mybatis框架进行的接口开发
1.第一步是由app端调起微信授权登录页面让用户进行授权操作,用户确认授权后会返回一个code,这个code就是我们后面获取授权用户信息的关键
2.拿着第一步获得的code去获取用户信息并进行登录操作,代码如下
接收微信返回参数的实体类:
package com.xk.hmo.dto.login;
import lombok.Data;
@Data
public class WxLoginInfo {
private String openid;//用户唯一标识
private String session_key;//会话密匙
private String unionid;//用户在开放平台的唯一标识符,在满足 UnionID 下发条件的情况下会返回
private Integer errcode;
private String errmsg;
}
appId 和 appSecret:
package com.xk.hmo.service.mobile.config;
/**
* 小程序微信登陆配置文件
* @author zhangt
*/
public class WxConstant {
//小程序appid
public static final String appid = "xxxxxxxxxxxxxxxx";
//小程序密匙
public static final String secret = "xxxxxxxxxxxxxxxxxxxxxxxx";
}
pom文件引入:
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
FastJsonUtil:
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.JSONLibDataFormatSerializer;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.xml.crypto.dsig.keyinfo.KeyValue;
public class FastJsonUtil {
private static final SerializeConfig config = new SerializeConfig();
private static final SerializerFeature[] features;
private FastJsonUtil() {
throw new AssertionError();
}
public static String toJSONString(Object obj) {
return JSON.toJSONString(obj, config, features);
}
public static String toJSONNoFeatures(Object obj) {
return JSON.toJSONString(obj, config, new SerializerFeature[0]);
}
public static Object toBean(String str) {
return JSON.parse(str);
}
public static <T> T toBean(String str, Class<T> clazz) {
return JSON.parseObject(str, clazz);
}
public static <T> Object[] toArray(String str) {
return toArray(str, (Class)null);
}
public static <T> Object[] toArray(String str, Class<T> clazz) {
return JSON.parseArray(str, clazz).toArray();
}
public static <T> List<T> toList(String str, Class<T> clazz) {
return JSON.parseArray(str, clazz);
}
public static Object beanToJson(KeyValue keyvalue) {
String textJson = JSON.toJSONString(keyvalue);
Object objectJson = JSON.parse(textJson);
return objectJson;
}
public static Object strToJson(String str) {
Object objectJson = JSON.parse(str);
return objectJson;
}
public static Map stringToCollect(String str) {
Map m = JSONObject.parseObject(str);
return m;
}
public static String collectToString(Map map) {
String str = JSONObject.toJSONString(map);
return str;
}
static {
config.put(Date.class, new JSONLibDataFormatSerializer());
config.put(java.sql.Date.class, new JSONLibDataFormatSerializer());
features = new SerializerFeature[]{SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteNullNumberAsZero, SerializerFeature.WriteNullBooleanAsFalse, SerializerFeature.WriteNullStringAsEmpty};
}
}
/**
* 微信授权登陆
*
* @param code
* @throws IOException
*/
@PostMapping("/wxLogin")
@ResponseBody
protected ResultPO wxLogin(@RequestParam String code) {
HttpClient httpclient = new HttpClient();
GetMethod get = new GetMethod("https://api.weixin.qq.com/sns/jscode2session?appid="+ WxConstant.appid +"&secret="+WxConstant.secret +"&js_code="+ code +"&grant_type=authorization_code");
String info ="";
try {
httpclient.executeMethod(get);
info = new String(get.getResponseBody(), "utf-8");
}catch (Exception e){
//抛出异常 微信授权失败,请稍后再试
throw new HMOException(CommonErrorCode.E100035);
}
log.error(info);
WxLoginInfo wxLoginInfo = FastJsonUtil.toBean(info, WxLoginInfo.class);
ResultPO success = ResultPO.success();
if (wxLoginInfo.getErrcode() != null){
success.setErrorMsg(wxLoginInfo.getErrcode().toString(), wxLoginInfo.getErrmsg());
}else{
success.setData(wxLoginInfo);
//成功获取到授权,根据个人业务需求写就可以了。。。
}
return success;
}