java实现微信小程序登录

一、引入核心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();
相关推荐
华仔啊16 小时前
千万别给数据库字段加默认值 null!真的会出问题
java·数据库·后端
老赵全栈实战19 小时前
【每日一技MyBatis trim标签核心用法
java·mybatis·orm
beata19 小时前
Java基础-19:Java 死锁深度解析:从原理、检测到预防与实战指南
java·前端
吾日三省Java1 天前
Spring Cloud架构下的日志追踪:传统MDC vs 王炸SkyWalking
java·后端·架构
爱玩泥巴的小t1 天前
new Thread().start()底层做了什么?
java
码路飞1 天前
GPT-5.4 Computer Use 实战:3 步让 AI 操控浏览器帮你干活 🖥️
java·javascript
小溪彼岸1 天前
是时候给想做小程序的小伙伴泼盆冷水了
微信小程序
祈安_1 天前
Java实现循环队列、栈实现队列、队列实现栈
java·数据结构·算法
皮皮林5512 天前
拒绝写重复代码,试试这套开源的 SpringBoot 组件,效率翻倍~
java·spring boot
远山枫谷2 天前
一文理清页面/组件通信与 Store 全局状态管理
前端·微信小程序