search
HomeJavajavaTutorialHow to implement Java payment function?

The simplest payment SDK in history

First let’s take a look at the API:

package com.joe.pay;

import com.joe.pay.pojo.*;

/**
 * 支付服务接口
 *
 * @author joe
 * @version 2018.06.29 11:32
 */
public interface PayService {
    /**
     * 调用第三方支付
     *
     * @param request 支付参数
     * @return 支付结果
     */
    SysResponse<payresponse> pay(PayRequest request);

    /**
     * 申请退款
     *
     * @param request 退款请求
     * @return 退款响应
     */
    SysResponse<refundresponse> refund(RefundRequest request);
}</refundresponse></payresponse>

As you can see, the PayService interface provides payment methods and refund methods. Let’s look at the parameter definitions of the payment methods:

package com.joe.pay.pojo;

import lombok.Data;

/**
 * 支付参数,除了openid外所有参数必填
 *
 * @author joe
 * @version 2018.07.02 10:36
 */
@Data
public class PayRequest implements Request{
    /**
     * 商户网站唯一订单号
     */
    private String outTradeNo;
    /**
     * 对一笔交易的描述信息
     */
    private String body;
    /**
     * 商品的标题/交易标题/订单标题/订单关键字等。
     * <p>
     * 对于微信支付来说需传入应用市场上的APP名字-实际商品名称,天天爱消除-游戏充值。
     */
    private String subject;
    /**
     * 订单生成时间,格式为yyyy-MM-dd HH:mm:ss
     */
    private String createTime;
    /**
     * 支付时长,单位为秒,如果设置300就是五分钟,超过五分钟订单自动取消
     */
    private int expire = 300;
    /**
     * 订单金额,单位为分
     */
    private int totalAmount;
    /**
     * 发起请求的用户的实际IP
     */
    private String ip;
    /**
     * 支付类型:APP、WEB(微信对应公众号,支付宝对应网页支付)
     */
    private String tradeType = "APP";
    /**
     * 用户openid,只有在微信公众号支付时需要
     */
    private String openid;
    /**
     * 附加数据,会与结果一并返回
     */
    private String attach;
}</p>

OK, I believe that the above parameters can be understood clearly and intuitively even by students who have never made a payment. They are some basic order information. Let’s look at the definition of refund parameters:

package com.joe.pay.pojo;

import lombok.Data;
import org.hibernate.validator.constraints.NotEmpty;

import javax.validation.constraints.Size;

/**
 * 退款请求
 *
 * @author joe
 * @version 2018.07.05 17:12
 */
@Data
public class RefundRequest {
    /**
     * 第三方账单ID,与outTradeNo不能同时为空
     */
    private String orderId;
    /**
     * 商户系统订单ID,与orderId不能同时为空
     */
    private String outTradeNo;
    /**
     * 商户退款单号
     * <p>
     * 退款支持单笔交易分多次退款,多次退款需要提交原支付订单的商户订单号和设置不同的退款单号。申请退款总金
     * </p><p>
     * 额不能超过订单金额。 一笔退款失败后重新提交,请不要更换退款单号,请使用原商户退款单号。
     */
    @NotEmpty(message = "商户退款单号不能为空")
    private String outRefundNo;
    /**
     * 订单总金额,单位为分
     */
    @Size(min = 1)
    private int totalFee;
    /**
     * 退款金额,不能大于订单总金额
     * </p><p>
     * 注:多次退款总金额不能大于订单总金额
     */
    @Size(min = 1)
    private int refundFee;
    /**
     * 退款原因
     * </p><p>
     * 可以为空
     */
    private String refundDesc;
}</p>

The refund parameters are even simpler and require quite little information. With this in place, we can look at the payment test code:

package com.joe.pay;

import com.joe.pay.pojo.*;
import com.joe.pay.pojo.prop.PayProp;
import com.joe.utils.common.DateUtil;
import com.joe.utils.common.Tools;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

/**
 * 支付测试
 *
 * @author joe
 * @version 2018.07.02 14:38
 */
public class PayServiceTest {
    /**
     * 微信配置
     */
    private PayProp wxProp;
    private PayProp aliProp;
    /**
     * 微信服务
     */
    private PayService wxPayService;
    private PayService aliPayService;

    @Before
    public void init() {
        //配置微信支付,需要将下列参数替换为自己的参数
        wxProp = PayProp.builder()
                .appid("123123123")
                .notifyUrl("http://www.baidu.com")
                .useWxPay()
                .certInput(null)
                .key("123123123")
                .mchId("123123123123")
                .password("123123123123")
                .build();

        wxPayService = PayServiceFactory.getInstance(wxProp);

        String privateKey = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDEuQvaAad8+PAUVLeh9tqNsWNDCiAXEal4krM0E1"
                + "4oHiUvzOT8Xf5BYZeMmiA+G+Z4iT2dP6bNRBIth7W5COh51v8TDf4dYxqV3Jw7jyQF2K/p74izFXm96yDXz3cMotRdDW3JdcC"
                + "ME2tgrlSjJxN26qPCrHh+OL9Y/yqJGhsAHKlaIYQ4S8F9B3rIPMAv6MbTuHFrFXkwuJqesupTwUqzmPgriy/2Au9ZApnpVCex"
                + "sKIkjMwpmOe3FxaQ9U6271NA9jmzbg7ge5BlfblQL3lIkEQdoqPPKrfLbO3djN1ORn1vhKrIAUhIQAqWKDVdz9dGxrIZckGOe"
                + "8iuUGOs8D4VAgMBAAECggEBAIzyuJcekE5uXjVy7Y9SOw1Ch5hE/PEKao5FLbimF9ROpP42o+pdvgpCTj8jPu7BNsQuMMM2E+"
                + "EGYK/WiFFnHIlYIbIZWHTdyPKO+jGCQaEevAu04BDP1kZI7WMy9m1LTTTOplat06OJVmoS/flXyg5t159ny31EU3UEfgl1dts"
                + "AayODTTRkRUjYXYXSOSDLZjlxSntNS9seklPgEeinc2umrdzJuzciKspK1XLqpCvc+1WA2NlTkoW6Hc9aj61ySCOTkF/3OVjj"
                + "G58jiUMzSeRsG3gq3PEJfhw2FUiJxn04ZRId74tIKrjKV4Np97WdmFEkpTEUTqvSp3AUYm/wJ5ECgYEA9pzaM+dd7vacLbgkA"
                + "e3N8dfyJggSJWm5TpangYIfQBXp+TiLhHFP6lhpCrs/qoxdsmM6LtzEkchvAQOA1kgNgRhm4s1pihKc7aAqK9YxE2tT5Z8XXd"
                + "9SXdLoHXe7GW3Q2ivouMV+J31mhOwSlogR5q0AztXJCl0FH9HHehMyAC8CgYEAzDYJOTOiHm5xjAJ337dtVe1zGUUBwv58B2O"
                + "wZXp129frnOepM+B663aMbrh+IUzVSQWqufGKUkLwjbRmwjrs9Lw4nFYtNGYVp1wnFawVOXy532tthYG5m3i/KcXjIRwnNHew"
                + "9Xh5q9rDc30yPKMps+Uijrp7ktQIRfh+QbOi8PsCgYBQccXz3GsVwjgb6c9FGc9uLmT85vEUZzJdYmNtqYaMHxndhAZuw4+v/"
                + "/rz1zTjazo9MIUQOE+exmT/Tac/Pu24yL73CM5+jafHE9HtzsbfcMlDQ+wZYPm7RUsWIbJUjy/rmxsk+rc2Jn/EqEU/+U7tkk"
                + "2LKs2TpdhAEuwg9BYBXQKBgQCKAZKmJ7DOJBF0b06X0ByBz6DTWQFhyB4F2GcjjWkNE5TVSvHcbz5i1pD9Wo1S79vMJ5pDY2r"
                + "5QOfUvDAd3zi4BGO1s7+FA+BqZCq9yLfnS9VJmg5ABXVsDmQSVPu0KpSMLr9WhP34FjW0XM2QkSvjuVxrXLeaeNTGhLK+sCnT"
                + "9QKBgHfd3hhLWjO4zh99B+PRYFgpnJa9S5E1zzoejZVIJhK5q60KLV5n/HMxuHTGRZxpbfcH4/44d3Yz7ieccmCiPtqxFYUwP"
                + "W0JukNWDL2tOzTSZ5ABAwqorV3bM67mLUSt0O5dL4YtSBJ2J3F6joO1fTZEcUCybO/A5J4wTZDOV1AR";

        //配置支付宝支付,需要将下列参数替换为自己的参数
        aliProp = PayProp.builder()
                .appid("123123123")
                .notifyUrl("http://www.baidu.com")
                .useAliPay()
                .publicKey("123123")
                .privateKey(privateKey)
                .build();
        aliPayService = PayServiceFactory.getInstance(aliProp);
    }

    /**
     * 测试微信支付
     */
    @Test
    public void doWxPay() {
        doPay(wxPayService);
    }

    /**
     * 测试支付宝支付
     */
    @Test
    public void doAliPay() {
        doPay(aliPayService);
    }

    /**
     * 测试微信退款
     * <p>
     * 注意:该测试当前通不过,因为没有提供正确的证书,若想要测试通过则需要在配置文件中提供正确的微信证书和单号
     */
    @Test
    public void doWxRefund() {
        doRefund(wxPayService);
    }

    /**
     * 测试支付宝退款
     * </p><p>
     * 注意:该测试当前通不过,若想要测试通过则需要提供正确的单号
     */
    @Test
    public void doAliRefund() {
        doRefund(aliPayService);
    }

    /**
     * 校验响应
     *
     * @param response 响应
     */
    private void check(SysResponse extends BizResponse> response) {
        Assert.assertTrue(response.isSuccess());
        Assert.assertTrue(response.getData().isSuccess());
    }

    /**
     * 发起支付请求
     *
     * @param service service
     */
    private void doPay(PayService service) {
        SysResponse<payresponse> response = service.pay(buildPay());
        check(response);
    }

    /**
     * 发起退款请求
     *
     * @param service service
     */
    private void doRefund(PayService service) {
        SysResponse<refundresponse> response = service.refund(buildRefund());
        System.out.println("结果是:" + response);
    }

    /**
     * 构建一个支付订单
     *
     * @return 支付订单
     */
    private PayRequest buildPay() {
        PayRequest payRequest = new PayRequest();
        payRequest.setOutTradeNo(Tools.createUUID());
        payRequest.setBody("天天爱消除-游戏充值");
        payRequest.setSubject("天天爱消除-游戏充值");
        payRequest.setCreateTime(DateUtil.getFormatDate(DateUtil.BASE));
        payRequest.setTotalAmount(100 * 10);
        payRequest.setIp("106.120.141.226");
        return payRequest;
    }

    /**
     * 构建一个退款订单
     *
     * @return 退款订单
     */
    private RefundRequest buildRefund() {
        RefundRequest request = new RefundRequest();
        request.setOutTradeNo("123456");
        request.setOutRefundNo("123456");
        request.setTotalFee(100 * 10);
        request.setRefundFee(100);
        return request;
    }
}</refundresponse></payresponse></p>

The above is the detailed content of How to implement Java payment function?. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software