微信直接登录(springboot+wx)
方法1
快速开始
- 配置文件编写
weixin:
appid: wx5bbcac13dbec9fe0
secret: a1ed9ae66689bbaf50b0e04630ec1472
- 业务的编写,前端传来一个 code ,发送到微信解析,然后微信返回一个字符串,这个字符串是固定的,但是同一个用户登录的 code 是不一样的
@Value("${weixin.appid}")
private String appid;
@Value("${weixin.secret}")
private String secret;
@Override
public String getSessionId(String code) {
String url = "https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code";
String replaceUrl = url.replace("{0}", appid).replace("{1}", secret).replace("{2}", code);
String res = HttpUtil.get(replaceUrl);
log.info("发送链接后获得的数据{}",res);
String s = UUID.randomUUID().toString();
redisTemplate.opsForValue().set(RedisKey.WX_SESSION_ID + s, res);
return s;
}
方法2
微信官方文档: https://github.com/Wechat-Group/WxJava/wiki
简介:
这里只介绍他的登录,其他更多的功能需要自己看文档去探索,那文档也有点烂
快速开始
- yml 配置
wx:
miniapp:
app-id: wx5bbcac13dbec9fe0
app-secret: a1ed9ae66689bbaf50b0e04630ec1472
msgDataFormat: JSON
- config 配置
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.WxMaConfig;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class WxConfig {
@Autowired
private WxProperties properties;
@Bean
public WxMaConfig wxMaConfig() {
WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
config.setAppid(properties.getAppId());
config.setSecret(properties.getAppSecret());
config.setMsgDataFormat(properties.getMsgDataFormat());
return config;
}
@Bean
public WxMaService wxMaService(WxMaConfig maConfig) {
WxMaService service = new WxMaServiceImpl();
service.setWxMaConfig(maConfig);
return service;
}
}
- 注入 yml 配置
@Data
@Configuration
@ConfigurationProperties(prefix = "wx.miniapp")
public class WxProperties {
private String appId;
private String appSecret;
private String msgDataFormat;
}
- controller
@Slf4j
@RestController
public class WxOfficialController {
@Autowired
private WxMaService wxService;
@GetMapping("/official")
public String getOfficialId(@RequestParam String code){
WxMaJscode2SessionResult info = null;
String openid=null;
String sessionKey=null;
try {
info =this.wxService.getUserService().getSessionInfo(code);
openid = info.getOpenid();
sessionKey = info.getSessionKey();
} catch (WxErrorException e) {
e.printStackTrace();
}
return openid;
}
}