springboot使用 WxJava 实现 微信小程序(uniapp开发)的登陆功能

前端使用uniapp来开发微信小程序

后端springboot中使用WxJava来做服务端(WxJava是微信服务端开发 的Java SDK

一、微信小程序登陆流程图

该图来源于微信小程序官方文档

二、前端代码

根据uniapp的官网直接通过它提供的第三方 登陆api直接使用,代码如下


<script setup>
import { onMounted, ref } from "vue";
let nickName = ref('');
let avatarUrl = ref('');
onMounted(()=>{
	getLogin();
});
const getLogin = ()=>{
	uni.login({
	  provider: 'weixin',
	  success: function (loginRes) {
		console.log(loginRes);
		let code = loginRes.code;
		// 获取用户信息
		uni.getUserInfo({
		  provider: 'weixin',
		  success: function (infoRes) {
			console.log(infoRes); 
			nickName.value = infoRes.userInfo.nickName;
			avatarUrl.value = infoRes.userInfo.avatarUrl;
			let param = {
				code: code,       //登陆凭证
				encryptedData: infoRes.encryptedData,  //包括敏感数据在内的完整用户信息的加密数据 
				iv: infoRes.iv,   //加密算法的初始向量,详细见加密数据解密算法
				appId: uni.getAccountInfoSync().miniProgram.appId //小程序的appId
			}
			//提交给服务端
			uni.request({
			    url: 'http://10.72.144.42:8080/wx/auth/login_wx', //仅为示例,并非真实接口地址。
			    method: 'post',
				data: param,
			    header: {
			        // 'custom-header': 'hello' //自定义请求头信息
			    },
			    success: (res) => {
					console.log("提交数据",res);
			    }
			});
		  }
		});
	  }
	});
};
</script>

三、java服务端代码

直接根据WxJava的官方demo

(1) yml配置

#使用weixin-java-miniapp java微信小程序封装的sdk
wx:
  miniapp:
    configs:
        - appid: 1111111111 #微信小程序的appid
          secret: 2222222222 #微信小程序的Secret(登陆凭证)
          token: #微信小程序消息服务器配置的token
          aesKey: #微信小程序消息服务器配置的EncodingAESKey
          msgDataFormat: JSON

(2)两个配置文件

public class WxMaProperties {
    private List<Config> configs;
    @Data
    public static class Config{
        /**
         * 设置微信小程序的appid
         */
        private String appid;

        /**
         * 设置微信小程序的Secret
         */
        private String secret;

        /**
         * 设置微信小程序消息服务器配置的token
         */
        private String token;

        /**
         * 设置微信小程序消息服务器配置的EncodingAESKey
         */
        private String aesKey;

        /**
         * 消息格式,XML或者JSON
         */
        private String msgDataFormat;
    }
}

public class WxMaConfiguration {
    private final WxMaProperties properties;

    //有参构造
    @Autowired
    public WxMaConfiguration(WxMaProperties properties) {
        this.properties = properties;
    }


    @Bean
    public WxMaService wxMaService() {
        List<WxMaProperties.Config> configs = this.properties.getConfigs();
        if (configs == null) {
            throw new WxRuntimeException("大哥,拜托先看下项目首页的说明(readme文件),添加下相关配置,注意别配错了!");
        }
        WxMaService maService = new WxMaServiceImpl();
        maService.setMultiConfigs(
                configs.stream()
                        .map(a -> {
                            WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
//                WxMaDefaultConfigImpl config = new WxMaRedisConfigImpl(new JedisPool());
                            // 使用上面的配置时,需要同时引入jedis-lock的依赖,否则会报类无法找到的异常
                            config.setAppid(a.getAppid());
                            config.setSecret(a.getSecret());
                            config.setToken(a.getToken());
                            config.setAesKey(a.getAesKey());
                            config.setMsgDataFormat(a.getMsgDataFormat());
                            return config;
                        }).collect(Collectors.toMap(WxMaDefaultConfigImpl::getAppid, a -> a, (o, n) -> o)));
        return maService;
    }
}

(3)controller接口代码

  @PostMapping("/wx/auth/login_wx")
    public Map getLogin(@RequestBody JSONObject params){
        //得到数据参数
        String code = params.getString("code");
        String encryptedData = params.getString("encryptedData");
        String iv = params.getString("iv");
        String appId = params.getString("appId");

        if (!wxMaService.switchover(appId)) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置,请核实!", appId));
        }
        WxMaJscode2SessionResult session = null;
        WxMaUserInfo wxMaUserInfo = null;
        try {
            //这一行代码就完成了 与微信开放服务端,要回session
            session = wxMaService.getUserService().getSessionInfo(code);
            log.info(session.getSessionKey());
            log.info(session.getOpenid());

            //session_key是对用户数据解密出全部用户数据
            wxMaUserInfo = wxMaService.getUserService().getUserInfo(session.getSessionKey(),encryptedData,iv);
            log.info(wxMaUserInfo.getNickName());
            log.info(wxMaUserInfo.getAvatarUrl());
            //添加自己的逻辑,关联业务相关数据

        } catch (WxErrorException e) {
            e.printStackTrace();
        }

        Map map = new HashMap();
        return map;
    }
  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

tengyuxin

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值