微信小程序授权(java)
引入jar包
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-miniapp</artifactId>
<version>3.8.0</version>
</dependency>
对应的api文档 :
http://binary.ac.cn/weixin-java-miniapp-javadoc/cn/binarywang/wx/miniapp/api/impl/WxMaAnalysisServiceImpl.html
授权核心
public AuthorizeResponse authorize( WxUserRegisterRequest registerRequest) {
try {
WxMaJscode2SessionResult session = Wxconfig.wxService.getUserService().getSessionInfo(registerRequest.getCode());
String accessToken = Wxconfig.wxService.getAccessToken();
WxMaUserInfo userInfo = Wxconfig.wxService.getUserService().getUserInfo(session.getSessionKey(), registerRequest.getEncryptedData(), registerRequest.getIv());
AuthorizeResponse authorizeResponse = new AuthorizeResponse()
.setOpenid(userInfo.getOpenId())
.setUnionid(userInfo.getUnionId())
.setAccessToken(accessToken)
.setSessionKey(session.getSessionKey());
return authorizeResponse;
} catch (WxErrorException e) {
throw new CloudException(ExceptionConstant.DATD_ERROR);
}
}
各类实体
WxUserRegisterRequest
@Data
@Accessors(chain = true)
public class WxUserRegisterRequest {
private String sessionKey;
private String encryptedData;
private String iv;
private String openid;
private String unionid;
private String nickname;
private String avatar;
private int gender;
private String code;
private String ip;
}
Wxconfig
@Component
public class Wxconfig {
public static String APPID = "xxx";
/**
* 设置微信小程序的Secret
*/
public static String SECRET = "xxx";
/**
* 设置微信小程序消息服务器配置的token
*/
public static String token;
/**
* 设置微信小程序消息服务器配置的EncodingAESKey
*/
public static String aesKey;
/**
* 消息格式,XML或者JSON
*/
public static String msgDataFormat = "JSON";
public static WxMaService wxService;
@PostConstruct
public void init(){
wxService = new WxMaServiceImpl();
WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
config.setAppid(Wxconfig.APPID);
config.setSecret(Wxconfig.SECRET);
wxService.setWxMaConfig(config);
}
}
AuthorizeResponse
@Data
@Accessors(chain = true)
public class AuthorizeResponse {
private String sessionKey;
private String openid;
private String unionid;
private String accessToken;
}
之后的登录只要小程序将openid或unionid传上来,然后根据自己的业务处理即可
还没有评论,来说两句吧...