Uniapp + SpringBoot 开发微信H5项目 微信公众号授权登录 JAVA后台(一、配置使用微信公众平台测试公众号)

申请测试号进行调试开发,测试号拥有大部分服务号有的接口权限。

一、接口配置信息填写校验

这里需要填写一个URL和一个Token验证字符串
我这里是用了natapp内网穿透 将本地的后台8080端口服务映射到了 http://x7zws8.natappfree.cc
https://natapp.cn/在natapp官网注册账号并且申请免费隧道
在这里插入图片描述
申请完了之后把域名绑定到自己的后台
在这里插入图片描述
后台接口:

    @RequestMapping(value = "/check", produces = "text/plain;charset=UTF-8", method = {RequestMethod.GET, RequestMethod.POST})
    //微信服务器根据配置的token,结合时间戳timestamp和随机数nonce通过SHA1生成签名,发起get请求,检验token的正确性,
    //检验正确原样返回随机字符串echostr,失败返回空字符串
    public String check(HttpServletRequest request, HttpServletResponse response,
                        @RequestParam("signature") String signature,
                        @RequestParam("timestamp") String timestamp,
                        @RequestParam("nonce") String nonce,
                        String echostr) throws Exception {
        //若是为get请求,则为开发者模式验证
        if ("get".equals(request.getMethod().toLowerCase())) {
            String checkSignature = SHA1.creatSHA1("token", timestamp, nonce);
            if (checkSignature.equals(signature)) {
                return echostr;
            }
        }
        return null;
    }

SHA1:

import java.security.MessageDigest;
import java.util.Arrays;

//SHA1加密算法类
public class SHA1 {
    /**
     *
     * @param token
     * @param timestamp 时间戳
     * @param nonce 随机字符串
     * @return 安全签名
     * @throws AesException
     */
    public static String creatSHA1(String token, String timestamp, String nonce) throws AesException
    {
        try {
            String[] array = new String[] { token, timestamp, nonce};
            StringBuffer sb = new StringBuffer();
            // 字符串排序
            Arrays.sort(array);
            for (int i = 0; i < 3; i++) {
                sb.append(array[i]);
            }
            String str = sb.toString();
            // SHA1签名生成
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            md.update(str.getBytes());
            byte[] digest = md.digest();

            StringBuffer hexstr = new StringBuffer();
            String shaHex = "";
            for (int i = 0; i < digest.length; i++) {
                shaHex = Integer.toHexString(digest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexstr.append(0);
                }
                hexstr.append(shaHex);
            }
            return hexstr.toString();
        } catch (Exception e) {
            e.printStackTrace();
            throw new AesException(AesException.ComputeSignatureError);
        }
    }
}

AesException:

public class AesException extends Exception {

    public final static int OK = 0;
    public final static int ValidateSignatureError = -40001;
    public final static int ParseXmlError = -40002;
    public final static int ComputeSignatureError = -40003;
    public final static int IllegalAesKey = -40004;
    public final static int ValidateAppidError = -40005;
    public final static int EncryptAESError = -40006;
    public final static int DecryptAESError = -40007;
    public final static int IllegalBuffer = -40008;

    private int code;

    private static String getMessage(int code) {
        switch (code) {
            case ValidateSignatureError:
                return "签名验证错误";
            case ParseXmlError:
                return "xml解析失败";
            case ComputeSignatureError:
                return "sha加密生成签名失败";
            case IllegalAesKey:
                return "SymmetricKey非法";
            case ValidateAppidError:
                return "appid校验失败";
            case EncryptAESError:
                return "aes加密失败";
            case DecryptAESError:
                return "aes解密失败";
            case IllegalBuffer:
                return "解密后得到的buffer非法";
            default:
                return null; // cannot be
        }
    }

    public int getCode() {
        return code;
    }

    public AesException(int code) {
        super(getMessage(code));
        this.code = code;
    }
}

校验走完之后配置测试号中 网页服务下的网页授权获取基本用户
在这里插入图片描述
在这里插入图片描述

这里填自己前端项目运行后的地址 我的后端项目端口是8080 uniapp前端运行完了之后的端口是8081所以我配置的是本地的ipv4 ip+端口号

二、后端配置 + 拼装URL + 通过Code获取用户OpenID和基本信息

在SpringBoot项目的pom中引入依赖

        <dependency>
            <groupId>com.github.binarywang</groupId>
            <artifactId>weixin-java-mp</artifactId>
            <version>4.6.0</version>
        </dependency>

创建配置类

import com.ruoyi.system.domain.WechatConfig;
import com.ruoyi.system.service.IWechatConfigService;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.config.WxMpConfigStorage;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class WxMpConfig {

    @Autowired
    private IWechatConfigService wechatConfigService;

    @Bean
    public WxMpConfigStorage wxMpConfigStorage() {
        WxMpDefaultConfigImpl configStorage = new WxMpDefaultConfigImpl();
        WechatConfig wechatConfig = wechatConfigService.selectWechatConfigById(1L);
        //我这里是做成了获取数据库中保存的AppID和AppSercret正常情况下写死就可以
        configStorage.setAppId(wechatConfig.getAppId());
        configStorage.setSecret(wechatConfig.getAppSecret());
        return configStorage;
    }

    @Bean
    public WxMpService wxMpService(WxMpConfigStorage configStorage) {
        WxMpService wxMpService = new WxMpServiceImpl();
        wxMpService.setWxMpConfigStorage(configStorage);
        return wxMpService;
    }
}

之后就可以在Controller中正常使用了
/authorize 接口其实只做了一步操作 就是构建获取code的url 构建完成之后返回给前端 前端直接重定向
buildAuthorizationUrl其中的三个参数
第一个是回调地址
第二个填snsapi_base 或者 snsapi_userinfo
snsapi_base 是之能获取到 openid 而 snsapi_userinfo 是可以获取到用户基本信息
snsapi_base是静默获取 而 snsapi_userinfo 需要用户点击授权

@RestController
@RequestMapping("/wx")
public class WeChatController extends BaseController {
    @GetMapping("/authorize")
    public AjaxResult test() {
        WxOAuth2Service oAuth2Service = wxMpService.getOAuth2Service();
        String redirectUrl = oAuth2Service.buildAuthorizationUrl("http://192.168.1.100:8081", "snsapi_userinfo", null);
        return success(redirectUrl);
    }

    @GetMapping("/userInfo")
    public AjaxResult userInfo(@RequestParam("code") String code) throws WxErrorException {
        WxOAuth2Service oAuth2Service = wxMpService.getOAuth2Service();
        WxOAuth2AccessToken wxMpOAuth2AccessToken = oAuth2Service.getAccessToken(code);
        logger.info("【wxMpOAuth2AccessToken:】{}", wxMpOAuth2AccessToken);
        String openId = wxMpOAuth2AccessToken.getOpenId();
        logger.info("【openid:】{}", openId);
        WxOAuth2UserInfo userInfo = oAuth2Service.getUserInfo(wxMpOAuth2AccessToken, "zh_CN");
        logger.info("【用户信息:】{}", userInfo.toString());
        return success(userInfo);
    }
}

二、uniapp前端调用

前端首先调用 /authorize 获取拼装好的地址然后重定向并获取code
getUrlCode来判断地址中是否包含code如果有的话拿着code去获取用户基本信息和openid

<template>
	<view class="content">
		<image class="logo" :src="loginUser.headImgUrl ? loginUser.headImgUrl : '/static/logo.png'"></image>
		<view class="text-area">
			<text class="title">{{loginUser.openid}}</text>
		</view>
		<button type="default" @click="login">登录</button>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				loginUser:{}
			}
		},
		onLoad(query) {
			const that = this;
			let code = that.getUrlCode();
			if (code) {
				console.log("有code")
				console.log(code)
				uni.request({
					url: "http://192.168.1.100:8080/wx/userInfo",
					data: {
						code: code
					},
					success(res) {
						console.log("获取到用户信息")
						console.log(res.data.data);
						that.loginUser = res.data.data;
					}
				})
			} else {
				console.log("没有code")
			}
		},
		methods: {
			login() {
				uni.request({
					url: "http://192.168.1.100:8080/wx/authorize",
					success(res) {
						window.location.href = res.data.msg;
					}
				})
			},
			getUrlCode() {
				return (
					decodeURIComponent(
						(new RegExp("[?|&]" + "code" + "=" + "([^&;]+?)(&|#|;|$)").exec(
							location.href
						) || [, ""])[1].replace(/\+/g, "%20")
					) || null
				);
			},
		}
	}
</script>
  • 10
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Vue、Spring Boot微信H5支付、电商、Git 是一些常见的技术和工具。下面我将依次对它们进行解释和描述: Vue 是一个现代化的前端框架,采用了一种响应式的编程方式,可以轻松构建交互丰富、高性能、可维护的web应用程序。Vue 提供了诸多的功能和特性,例如组件化开发、虚拟DOM、数据双向绑定等,极大地提高了前端开发的效率。 Spring Boot 是一个轻量级、快速开发Java后端框架,它简化了Spring应用程序的配置和部署,提供了自动化配置和快速启动的特性。Spring Boot具有强大的生态系统和丰富的功能,可以方便地构建高效、安全且可扩展的后端应用程序。 微信H5支付是微信公众平台提供的一种在线支付方式,可以通过微信支付接口实现在手机浏览器中进行支付。它支持用户在H5页面中通过微信进行支付,适用于电商、在线购物等需要在线支付的场景。微信H5支付具有便捷、安全的特点,可以提供良好的用户支付体验。 电商是指以电子商务技术为支撑,通过互联网进行商品、服务的交易和商务活动的行业。电商平台的建设包括商品展示、购物车、订单管理、支付处理等模块,需求复杂多样。Vue和Spring Boot可以结合使用前端通过Vue来实现电商平台的用户界面,后端采用Spring Boot开发后台接口和处理业务逻辑。 Git 是一个分布式版本控制系统,用于保存和管理软件开发过程中的各个版本。团队可以通过Git来协同开发,追踪代码变更、回滚、合并等。在开发电商平台时,Git助力多人合作开发,有效地管理代码库,解决并发开发、版本控制的问题。团队成员可以通过Git来共享和提交自己的代码,并通过分支管理功能来进行并行开发和版本控制。 总结来说,Vue是一个前端框架,Spring Boot是一个后端框架,微信H5支付是一种在线支付方式,电商是基于电子商务技术的行业,Git是一个用于版本控制的工具。这些技术和工具可以相互结合,用于开发电商平台,并实现高效、可靠的软件开发和交付。 ### 回答2: Vue是一种流行的前端框架,它使用JavaScript和HTML来构建交互式的用户界面。它具有简单易学、灵活性强以及性能优化等优势,因此在前端开发中得到了广泛的应用。 Spring Boot是一个用于简化基于Java的应用程序开发的框架。它提供了开箱即用的功能,使开发人员能够快速构建高效、可扩展的应用程序。Spring Boot还具有自动化配置和简化部署等特性,使开发过程更加便捷。 微信H5支付是一种在线支付方式,允许用户在手机端使用微信进行购物支付。它具有支付安全、使用便捷以及适用范围广泛的特点,已经成为电商领域中非常常见的支付方式。 Git是一个分布式版本控制系统,它用于跟踪文件的修改和历史记录。在开发过程中,开发人员可以使用Git来管理代码版本,通过分支、合并等功能来协同开发和解决冲突。 综上所述,Vue和Spring Boot是用于构建应用程序的框架,微信H5支付是一种在线支付方式,而Git是用于版本控制的工具。它们在电商领域中都扮演着重要角色,能够使开发人员更加高效地开发、部署和维护应用程序。 ### 回答3: Vue是一个用于构建用户界面的开源JavaScript框架,它采用了MVVM的架构模式,能够使开发者更高效地构建Web应用程序。Vue具有简单易学、灵活可扩展以及高性能等特点,因此在前端开发中广受欢迎。 Spring Boot是一个基于Spring框架的快速开发框架,它通过内嵌的Web服务器、自动化配置和约定优于配置的原则,极大地简化了Java Web应用的开发工作。Spring Boot提供了丰富的开发工具和组件,使得开发人员可以更轻松地构建出高效、健壮的后端应用。 微信H5支付是指在移动端浏览器中使用微信支付功能的一种支付方式,用户可以通过浏览器直接打开商户的H5页面进行支付。微信H5支付不需要下载或安装微信客户端,能够为电商平台提供更便捷的支付方式,提升用户体验并增加交易转化率。 Git是一个分布式版本控制系统,它可以记录和管理代码的版本变更。在团队协作开发中,Git可以帮助开发人员更好地进行代码管理、合并和回滚等操作,确保团队开发的代码始终处于一个稳定的状态。Git也是目前最流行的版本控制工具之一,被广泛应用于软件开发行业。 综上所述,Vue、Spring Boot微信H5支付和Git分别代表了前端开发后端开发、支付方式和版本控制等不同方面的技术和工具。结合这些技术和工具,我们可以构建出一个使用Vue作为前端框架,Spring Boot作为后端框架,集成微信H5支付的电商平台,并且通过Git进行代码版本管理和团队协作开发

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值