一、引入核心pom
csharp
复制代码
<!-- 微信小程序 -->
<dependency>
<groupId>com.github.binarywang</groupId>
<artifactId>weixin-java-miniapp</artifactId>
<version>4.5.0</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
二、注入依赖配置
csharp
复制代码
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.WxMaUserService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
@Slf4j
@Configuration
public class WxClientConfig {
//小程序服务
@Value("${wx.mini.appId}")
private String miniAppId;
@Value("${wx.mini.secret}")
private String miniSecret;
private WxMaUserService wxMaUserService;
@PostConstruct
public void init() {
//微信小程序
WxMaDefaultConfigImpl wxMaConfig = new WxMaDefaultConfigImpl();
wxMaConfig.setAppid(miniAppId);
wxMaConfig.setSecret(miniSecret);
WxMaService wxMaService = new WxMaServiceImpl();
wxMaService.setWxMaConfig(wxMaConfig);
this.wxMaUserService = wxMaService.getUserService();
}
@Bean(name = "wxMaUserService")
public WxMaUserService wxMaUserService(){
return this.wxMaUserService;
}
三、跟进微信CODE 获取openId
csharp
复制代码
@Resource
private WxMaUserService wxMaUserService;
//根据授权code获取微信用户信息
WxMaJscode2SessionResult session = wxMaUserService.getSessionInfo(authDto.getCode());
WxMaUserInfo wxUser = wxMaUserService.getUserInfo(session.getSessionKey(), authDto.getEncryptedData(), authDto.getIv());
四、根据微信CODE 获取手机信息
csharp
复制代码
String phoneNumber = wxMaUserService.getPhoneNoInfo(bindDto.getCode()).getPhoneNumber();