支付宝支付之SpringBoot整合支付宝创建自定义支付二维码

文章目录

  • 自定义支付二维码
    • pom.xml
    • application.yml
    • 自定义二维码类
    • AlipayService.java
    • AlipayServiceImpl.java
    • AlipayController.java
    • qrCode.html

自定义支付二维码

继:SpringBoot支付入门

pom.xml

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency><dependency><!--ZXing(Zebra Crossing)核心库,提供了二维码生成和解析的基本功能--><groupId>com.google.zxing</groupId><artifactId>core</artifactId><version>3.4.1</version>
</dependency>
<!--ZXing 的 JavaSE 扩展库,提供了在 Java 环境中生成和解析二维码的更高级功能,例如将二维码保存为图像文件、从图像文件解析二维码等。
-->
<dependency><groupId>com.google.zxing</groupId><artifactId>javase</artifactId><version>3.4.1</version>
</dependency>

application.yml

spring:thymeleaf:enabled: true  # 启用Thymeleafcache: false    # 禁用Thymeleaf缓存,方便开发时查看修改的效果prefix: classpath:/static/html/  # Thymeleaf模板文件所在目录,默认classpath:/static/html/suffix: .html   # Thymeleaf模板文件的后缀,默认为.html

自定义二维码类

package com.sin.demo.utils;import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.HashMap;
import java.util.Map;/*** @createTime 2024/4/17 10:07* @createAuthor SIN* @use 二维码创建工具类*/
public class QRCodeUtil {private static final int WIDTH = 300; // 二维码宽度private static final int HEIGHT = 300; // 二维码高度private static final String FORMAT = "png"; // 二维码格式/*** 生成二维码* @param text 二维码内容,一定是互联网内容,本地是无法扫的到的* @param filePath 二维码生成地址*/public static void generateQRCode(String text, String filePath) {try {// 创建一个存储编码参数的 HashMap 对象Map<EncodeHintType, Object> hints = new HashMap<>();// 设置字符集为 UTF-8hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");// 设置容错级别为 Mhints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);// 设置边距为 2hints.put(EncodeHintType.MARGIN, 2);// 使用 MultiFormatWriter 类将指定文本 text 编码为二维码矩阵BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);// 将二维码矩阵转换为 BufferedImage 对象BufferedImage image = toBufferedImage(bitMatrix);// 创建一个表示目标文件的 File 对象File file = new File(filePath);// 将 BufferedImage 对象保存为图像文件ImageIO.write(image, FORMAT, file);System.out.println("二维码已生成,保存路径:" + filePath);} catch (Exception e) {e.printStackTrace();}}/*** 将二维码矩阵转为可视化图像* @param matrix* @return 生成BufferdImage对象,获得二维码的可视化图像*/private static BufferedImage toBufferedImage(BitMatrix matrix) {// 获取二维码的宽和高int width = matrix.getWidth();int height = matrix.getHeight();// 创建一个新的BufferedImage对象,指定宽和高,已经颜色类型BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);for (int x = 0; x < width; x++) {for (int y = 0; y < height; y++) {// 获取当前坐标 (x, y) 的像素值(true 表示黑色,false 表示白色)boolean pixel = matrix.get(x, y);// 根据像素值设置对应位置的 RGB 值,将黑色或白色像素点绘制到 BufferedImage 对象中int rgb = pixel ? Color.BLACK.getRGB() : Color.WHITE.getRGB();// 设置x,y坐标和颜色image.setRGB(x, y, rgb);}}// 返回生成的 BufferedImage 对象return image;}
}

AlipayService.java

package com.sin.demo.service;import com.alipay.api.AlipayApiException;/*** @createTime 2024/4/17 8:20* @createAuthor SIN* @use*/
public interface AlipayService {/*** 创建支付订单* @param outTradeNo 订单号* @param totalAmount 支付金额* @param subject 支付标题* @return 返回二维码信息* @throws AlipayApiException*/public String getgenerateQrCode(String outTradeNo,double totalAmount,String subject) throws AlipayApiException;
}

AlipayServiceImpl.java

package com.sin.demo.service.impl;import com.alipay.api.AlipayApiException;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.sin.demo.service.AlipayService;
import com.sin.demo.utils.QRCodeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;/*** @createTime 2024/4/17 8:23* @createAuthor SIN* @use*/
@Service
@Slf4j
public class AlipayServiceImpl implements AlipayService {// 从配置文件中获取参数值@Value("${alipay.appId}")private String appId; // 支付宝应用ID@Value("${alipay.privateKey}")private String privateKey; // 商户应用私钥@Value("${alipay.publicKey}")private String publicKey; // 支付宝公钥@Value("${alipay.gatewayUrl}")private String gatewayUrl; // 支付宝网关URL@Overridepublic String getgenerateQrCode(String outTradeNo, double totalAmount, String subject) throws AlipayApiException {// 创建支付宝客户端DefaultAlipayClient client = new DefaultAlipayClient(gatewayUrl, appId, privateKey, "json", "UTF-8", publicKey, "RSA2");// 创建预下单请求对象AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();// 设置测试业务参数request.setBizContent("{\"out_trade_no\":\"" + outTradeNo + "\","+ "\"total_amount\":\"" + totalAmount + "\","+ "\"subject\":\"" + subject + "\"}");// 执行预下单请求AlipayTradePrecreateResponse response = client.execute(request);// 判断预下单请求是否成功if (response.isSuccess()) {// 获取生成的支付二维码信息final String qrCode = response.getQrCode();// 打印二维码信息到控制台System.out.println("二维码信息:" + qrCode);// 记录生成支付二维码成功的日志log.info("生成支付二维码成功:{}", response.getBody());// 生成自定义二维码QRCodeUtil.generateQRCode(qrCode,"src/main/resources/static/image/qrcode.png");// 返回生成的支付二维码地址return "支付宝支付二维码地址:" + qrCode;} else {// 记录生成支付二维码失败的日志log.error("生成支付二维码失败:{}", response.getSubMsg());// 返回生成支付二维码失败的信息return "生成支付二维码失败:" + response.getSubMsg();}}
}

AlipayController.java

package com.sin.demo.controller;import com.alipay.api.AlipayApiException;
import com.sin.demo.service.AlipayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;/*** @createTime 2024/4/17 8:28* @createAuthor SIN* @use*/
@Controller
public class AlipayController {@Autowiredprivate AlipayService alipayService;@ResponseBody@GetMapping("/generateQrCode/{outTradeNo}/{totalAmount}/{subject}")public String getGenerateQrCode(@PathVariable("outTradeNo") String outTradeNo,@PathVariable("totalAmount") double totalAmount,@PathVariable("subject")String subject) throws AlipayApiException {String s = alipayService.getgenerateQrCode(outTradeNo, totalAmount, subject);return s;}@GetMapping("/getQrCode")public String getQrCode(){return "qrCode";}}

qrCode.html

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>支付页面</title>
</head>
<body>
<h1>支付页面</h1>
<div><h2>扫描下方二维码进行支付:</h2><img id="qrCode" src="../image/qrcode.png" alt="支付二维码">
</div>
</body>
</html>

在这里插入图片描述

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/diannao/101.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

PHP中常见的@注释的含义

api: 提供给第三方使用的接口 author: 标明作者 param: 参数 return: 返回值 todo: 待办 version: 版本号 inheritdoc: 文档继承 property: 类属性 property-read: 只读属性 property-write: 只写属性 const: 常量 deprecated: 过期方法 example: 示例 final: 标识类是终态, 禁…

前端开发该不该“跳槽”到鸿蒙?

前言 面对互联网行业的激烈竞争&#xff0c;许多人都深感2023年已是不易&#xff0c;而展望2024年&#xff0c;似乎更是难上加难。这一切的根源&#xff0c;皆因行业多年发展后&#xff0c;人才市场的饱和现象愈发严重。那么&#xff0c;作为前端开发者&#xff0c;我们究竟该…

速看!2024年强基计划报考流程及常见问答

01什么是强基计划&#xff1f; 为加强基础学科拔尖创新人才选拔培养&#xff0c;教育部在深入调研、总结高校自主招生和上海等地高考综合改革试点经验的基础上&#xff0c;制定出台了《关于在部分高校开展基础学科招生改革试点工作的意见》&#xff08;也称“强基计划”&#…

SpringBoot启动加载自己的策略类到容器中使用?

使用InitializingBean接口 springboot中在启动的会自动把所有的实现同一个接口的类&#xff0c;都会转配到标注Autowired的list里面 而且实现了InitializingBean接口&#xff0c;在启动的赋值的时候&#xff0c;我们会把所有的策略类&#xff0c;重放到map中&#xff0c;我们在…

c++ 11 添加功能 变量类型推导

1.概要 变量类型推导 2.代码 #include <iostream> #include <map> using namespace std; int main() { std::map<std::string, std::string> m{ {"a", "apple"}, {"b","banana"} }; // 使用迭代器遍历…

发布订阅模式以及mitt源码实现

发布订阅模式以及mitt源码实现 前言&#xff1a;我为什么要写他&#xff1f; 场景1: 我在写一个组件&#xff0c;但是层层传递之后&#xff0c;全是属性/事件的传递。中间有很多缘由&#xff0c;vuex 又不适合&#xff0c;最后选择了eventBus&#xff0c;但是vue3 已经不再提供…

【尚硅谷】Git与GitLab的企业实战 学习笔记

目录 第1章 Git概述 1. 何为版本控制 2. 为什么需要版本控制 3. 版本控制工具 4. Git简史 5. Git工作机制 6. Git和代码托管中心 第2章 Git安装 第3章 Git常用命令 1. 设置用户签名 1.1 基本语法 1.2 案例实操 2. 初始化本地库 2.1 基本语法 2.2 案例实操 3. 查…

【运输层】TCP 的流量控制和拥塞控制

目录 1、流量控制 2、TCP 的拥塞控制 &#xff08;1&#xff09;拥塞控制的原理 &#xff08;2&#xff09;拥塞控制的具体方法 1、流量控制 一般说来&#xff0c;我们总是希望数据传输得更快一些。但如果发送方把数据发送得过快&#xff0c;接收方就可能来不及接收&#x…

milvus服务安装bash脚本指令理解

下拉镜像&#xff1a;docker pull milvusdb/milvus:v2.4.0-rc.1下载文件&#xff1a;https://hub.yzuu.cf/milvus-io/milvus/blob/master/scripts/standalone_embed.sh安装启动&#xff1a;bash standalone_embed.sh start详细解释下这段代码&#xff1a;wait_for_milvus_runni…

伪代码——基础语法入门

1、简介 伪代码是一种用来描述算法或程序逻辑的抽象化编码方式&#xff0c;它不依赖于任何特定的编程语言语法&#xff0c;而是使用类似自然语言的形式来描述算法步骤。通常用于算法设计、教学和沟通&#xff0c;伪代码可以更直观地表达问题的解决方案&#xff0c;而不必受限于…

Ubuntu 22.04 配置VirtualBox安装Windows 10虚拟机

Ubuntu 22.04 配置VirtualBox安装Windows 10虚拟机 文章目录 Ubuntu 22.04 配置VirtualBox安装Windows 10虚拟机1.安装virtualbox2.下载Window.iso文件并载入3.问题解决3.1 Kernel driver not installed (rc-1908)3.2 VT-x is disabled in the BIOS for all CPU modes 4.安装Wi…

【python】python 模块学习之--Fabric

基础一&#xff1a; #!/usr/bin/env pythonfrom fabric.api import *env.userrootenv.hosts[218.78.186.162,125.208.12.56]env.passwords{ root218.78.186.162:22:XXX,root125.208.12.56:22:XXXX0}runs_once ####runs_once代表只执行一次def local_tas…

在开源框架使用自有数据集的方法-以增量学习工具箱PyCIL为例

回答多位朋友提出的&#xff0c;如何在开源框架使用自有数据集。思路是理解开源代码的设计方法&#xff0c;根据其设计方法增加相应的代码。 具体方法如下&#xff1a; 1.查看开源代码提供者的说明 https://github.com/G-U-N/PyCIL#datasets&#xff0c;这里提供了入手的起点…

带你实现一个github注册页面的星空顶

带你实现一个github注册页面的星空顶 github的注册页面可以说是非常的好看&#xff0c;如果没有看过的可以看下面的图片&#xff1a; 那么要如何实现下面的这个效果呢&#xff1f; 首先我们研究一下他的这个官网 首先我看到的后面的这个背景&#xff0c;是不是一个纯色的背景…

Linux安装Docker完整教程及配置阿里云镜像源

官网文档地址 安装方法 1、查看服务器内核版本 Docker要求CentOS系统的内核版本高于3.10 uname -r #通过 uname -r 命令查看你当前的内核版本2、首先卸载已安装的Docker&#xff08;如果有&#xff09; 2.1 确保yum包更新到最新 yum update2.2 清除原有的docker&#xff0c…

02_Fixture定位,Caliper卡尺工具,几何学工具

Fixture定位工具 需求: 测量工件的尺寸 使用Caliper(卡尺)工具 这个时候需要借助Fixture工具 VisionPro中的图像空间 “” 图像的当前空间&#xff0c;即CogImage中的“SelectedSpaceName”表示的名字空间 “#” 像素空间&#xff0c;即坐标原点为图片左上角的坐标空间&am…

TCP/IP协议—MQTT

TCP/IP协议—MQTT MQTT协议MQTT协议特点MQTT通信流程MQTT协议概念 MQTT报文固定报头可变报头有效载荷 MQTT协议 消息队列遥测传输&#xff08;Message Queuing Telemetry Transport&#xff0c;MQTT&#xff09;是一个基于客户端-服务器的消息发布/订阅传输协议。它的设计思想…

windows上安装make

下载地址 https://sourceforge.net/projects/gnuwin32/ 点击框中的下载&#xff0c;下载后安装。把安装路径添加到环境变量 PATH 中. 打开cmd&#xff0c;验证是否生效 安装包下载地址&#xff1a; https://download.csdn.net/download/qq_36314864/89163210

python读取DBF数据

DBF文件通常是由数据库软件&#xff08;如FoxPro或dBASE&#xff09;创建的数据库文件。Python中并没有直接读取DBF文件的内置库&#xff0c;但你可以使用第三方库如dbfread来读取DBF文件。 首先&#xff0c;你需要安装dbfread库。你可以使用pip来安装&#xff1a; pip insta…

【人工智能书籍分享】从ChatGPT到AIGC:人工智能重塑千行百业

今天又来给大家推荐一本人工智能方面的书籍<从ChatGPT到AIGC&#xff1a;人工智能重塑千行百业>。本书介绍了ChatGPT的前世今生&#xff0c;重点聚焦普通人如何使用ChatGPT获得工作和生活效率的提升&#xff0c;各行各业如何通过ChatGPT来改变自己的赛道状态。 使用Chat…