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();
相关推荐
karry_k8 小时前
MyBatis批量insert-select踩坑:useGeneratedKeys=true 可能让PostgreSQL返回大量插入结果
java·后端
karry_k8 小时前
PostgreSQL 在 MyBatis 中执行正常 SQL 失效:一次 DELETE USING 踩坑记录
java·后端
SamDeepThinking12 小时前
从源码到代码:MyBatis-Flex 与 MyBatis-Plus 的逐项对比
java·后端·程序员
她的男孩15 小时前
Spring Boot 接 Flowable 工作流:用 3 个注解搭一个请假审批流程
java·后端·架构
荣码17 小时前
LLM结构化输出:让AI返回JSON而不是废话,我踩了4个坑
java·python
plainGeekDev18 小时前
Gson → kotlinx.serialization
android·java·kotlin
小bo波1 天前
Java Swing 图形用户界面实验 —— 从算术练习到游戏开发的完整实践
java·课程设计·gui·游戏开发·扫雷·swing
咖啡八杯1 天前
GoF设计模式——备忘录模式
java·后端·spring·设计模式