调用接口获取登录凭证(code)。通过凭证进而换取用户登录态信息,包括用户在当前小程序的唯一标识(openid)、微信开放平台帐号下的唯一标识(unionid,若当前小程序已绑定到微信开放平台帐号)及本次登录的会话密钥(session_key)等。
pom.xml文件添加依赖
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-miniapp</artifactId>
<version>3.3.0</version>
</dependency>
配置类WxMaConfiguration:
package wxma.configuration;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.WxMaInMemoryConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class WxMaConfiguration {
/**
* 此处appId和appSecret在配置文件配置
*/
@Value("${info.appId}")
private String appId;
@Value("${info.appSecret}")
private String appSecret;
@Bean
public WxMaInMemoryConfig services(){
WxMaInMemoryConfig config = new WxMaInMemoryConfig();
config.setAppid(appId);
config.setSecret(appSecret);
return config;
}
@Bean
public WxMaService wxMpService() {
WxMaService wxMaService = new WxMaServiceImpl();
wxMaService.setWxMaConfig(services());
return wxMaService;
}
}
项目配置文件application.yml:
info:
appId: 自己的appid
appSecret: 自己的 appSecret
WxMaController编写:
@RestController
@RequestMapping("/wxMa")
public class WeMaController {
@Autowired
private WxMaService wxMaService;
@ResponseBody
@RequestMapping(value = "/getOpenId",method = RequestMethod.GET)
public Map<String,String> getOpenId(String code) {
try {
WxMaJscode2SessionResult result = wxMaService.jsCode2SessionInfo(code);
Map<String,String> map = new HashMap<>();
map.put("openId",result.getOpenid());
map.put("sessionKey",result.getSessionKey());
return map;
} catch (WxErrorException e) {
//此处WxMaException为自定义异常
throw new WxMaException("获取openId异常");
}
}
}