java integrated payment platform Alipay

Sign sandbox account
to ants gold dress registered developer account, registered address: https://open.alipay.com , use your PayPal account to log scan code, improve personal information, select the type of service.

Creating springboot project import dependence
pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.louis</groupId>
    <artifactId>epay-service</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>epay-service</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- alipay -->
        <dependency>    
            <groupId>com.alipay.sdk</groupId>
            <artifactId>alipay-sdk-java</artifactId>
            <version>3.1.0</version>
        </dependency>
        <!-- fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.48</version>
        </dependency>
        
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

Profiles resources add alipay.properties file, configuration information is written Alipay

# Application ID, your APPID, receiving account both your APPID correspond Alipay account 
appId: 2,016,092,300,579,321 
# private business, your PKCS8 format RSA2 private 
privateKey: get yourself in a gold suit ant in 
publicKey: ants gold dress themselves in get 
notifyUrl: http: // external network ip: port /error.html 
returnUrl: HTTP: // external network ip: port /sccess.html 

## or less fixed 
# signature way 
signType: RSA2 
# character encoding format 
charset: utf-8 
# Alipay gateway 
GatewayUrl: https://openapi.alipaydev.com/gateway.do 
# Alipay gateway 
logPath: "C: \\"

  

PropertiesListener increase a listener to load profile property when the application starts.

PropertiesListener.java

package com.louis.epay.config;

import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import com.louis.epay.alipay.AlipayProperties;

/**
 * 配置文件监听器,用来加载自定义配置文件
 * @author Louis
 * @date Dec 12, 2018
 */
@Component
public class PropertiesListener implements ApplicationListener<ApplicationStartedEvent> {

    @Override
    public void onApplicationEvent(ApplicationStartedEvent event) {
        AlipayProperties.loadProperties();
    }
}

  

The above loading listener property, is loaded by a loader specific properties, such as class loading Alipay following properties.

AlipayProperties.java

package com.louis.epay.alipay;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.stereotype.Component;

/**
 * 应用启动加载文件
 * @author Louis
 * @date Dec 12, 2018
 */
@Component
public class AlipayProperties {
    
    public static final String APP_ID = "appId";
    public static final String PRIVARY_KEY = "privateKey";
    public static final String PUBLIC_KEY = "publicKey";
    public static final String NOTIFY_URL = "notifyUrl";
    public static final String RETURN_URL = "returnUrl";
    public static final String SIGN_TYPE = "signType";
    public static final String CHARSET = "charset";
    public static final String GATEWAY_URL = "gatewayUrl";
    public static final String LOG_PATH = "logPath";
    
    /**
     * 保存加载配置参数
     */
    private static Map<String, String> propertiesMap = new HashMap<String, String>();

    /**
     * 加载属性
     */
    public static void loadProperties() {
        // 获得PathMatchingResourcePatternResolver对象
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            // load the resource file (you can also load resources)
        {the try
            Resources = resolver.getResource the Resource ( "CLASSPATH: alipay.properties"); 
            PropertiesFactoryBean new new PropertiesFactoryBean config = (); 
            config.setLocation (Resources); 
            config.afterPropertiesSet (); 
            the Properties prop = config.getObject (); 
            // Loop through All key-value pairs have set and stored 
            for (String Key: prop.stringPropertyNames ()) { 
                propertiesMap.put (Key, (String) prop.get (Key)); 
            } 
        } the catch (Exception E) { 
            new new Exception ( " profile load failure "); 
        }  
    } 
    
    / **
     * Gets the configuration parameter values 
     * @param Key 
     * @return 
     * /
    public static String getKey(String key) {
        return propertiesMap.get(key);
    }

    public static String getAppId() {
        return propertiesMap.get(APP_ID);
    }

    public static String getPrivateKey() {
        return propertiesMap.get(PRIVARY_KEY);
    }

    public static String getPublicKey() {
        return propertiesMap.get(PUBLIC_KEY);
    }

    public static String getNotifyUrl() {
        return propertiesMap.get(NOTIFY_URL);
    }

    public static String getReturnUrl() {
        return propertiesMap.get(RETURN_URL);
    }

    public static String getSignType() {
        return propertiesMap.get(SIGN_TYPE);
    }

    public static String getCharset() {
        return propertiesMap.get(CHARSET);
    }

    public static String getGatewayUrl() {
        return propertiesMap.get(GATEWAY_URL);
    }

    public static String getLogPath() {
        return propertiesMap.get(LOG_PATH);
    }
    
}

  

Alipay interface package
Alipay Alipay is packaged function that receives a AlipayBean as a parameter, and ultimately return to the payment page by calling pageExecute method of AlipayClient.

Alipay.java

com.louis.epay.alipay Package; 

Import org.springframework.stereotype.Component; 

Import com.alibaba.fastjson.JSON; 
Import com.alipay.api.AlipayApiException; 
Import com.alipay.api.AlipayClient; 
Import com.alipay. api.DefaultAlipayClient; 
Import com.alipay.api.request.AlipayTradePagePayRequest; 

/ ** 
 * Alipay Interface 
 * @author Louis 
 * 12 is @date On Dec, 2018 
 * / 
@Component 
public class Alipay { 
    
    / ** 
     * payment interface 
     * @param alipayBean 
     * @return 
     * @throws AlipayApiException 
     * / 
    public String pay(AlipayBean alipayBean) throws AlipayApiException {
        // 1, get initialized AlipayClient
        String serverUrl = AlipayProperties.getGatewayUrl();
        String appId = AlipayProperties.getAppId();
        String privateKey = AlipayProperties.getPrivateKey();
        String format = "json";
        String charset = AlipayProperties.getCharset();
        String alipayPublicKey = AlipayProperties.getPublicKey();
        String signType = AlipayProperties.getSignType();
        String returnUrl = AlipayProperties.getReturnUrl();
        String notifyUrl = AlipayProperties.getNotifyUrl();
        AlipayClient alipayClient = new DefaultAlipayClient(serverUrl, appId, privateKey, format, charset, alipayPublicKey, signType);
        // 2、设置请求参数
        = New new AlipayTradePagePayRequest alipayRequest AlipayTradePagePayRequest (); 
        // page jump sync notifications Page path 
        alipayRequest.setReturnUrl (returnUrl); 
        // asynchronous notification page server path 
        alipayRequest.setNotifyUrl (notifyUrl); 
        // package parameters 
        alipayRequest.setBizContent (JSON.toJSONString ( alipayBean)); 
        // 3, Alipay payment request and obtain the payment result 
        String = alipayClient.pageExecute the result (alipayRequest) .getBody (); 
        // return payment information 
        return the result; 
    } 
}

  

Interface call parameters as an encapsulated object.

AlipayBean.java

com.louis.epay.alipay Package; 

/ ** 
 * payment entity object 
 * according Po payment interface protocol, wherein the attribute name, an underscore must not be modified 
 * @author Louis 
 * 12 is @date On Dec, 2018 
 * / 
public class AlipayBean { 
    
    / ** 
     * merchant order number required 
     * 
     * / 
    Private String out_trade_no; 
    / ** 
     * Order name, required 
     * / 
    Private String Subject; 
    / ** 
     * payment amount required 
     * according to Alipay interface protocol, you must use an underscore 
     * / 
    Private String TOTAL_AMOUNT; 
    / ** 
     * product description may be empty 
     * / 
    Private String body; 
    / ** 
     * timeout parameter 
     * /
    private String timeout_express= "10m";
    /**
     * 产品编号
     */
    private String product_code= "FAST_INSTANT_TRADE_PAY";

    public String getOut_trade_no() {
        return out_trade_no;
    }
    public void setOut_trade_no(String out_trade_no) {
        this.out_trade_no = out_trade_no;
    }
    public String getSubject() {
        return subject;
    }
    public void setSubject(String subject) {
        this.subject = subject;
    }
    public String getTotal_amount() {
        return total_amount;
    }
    public void setTotal_amount(String total_amount) {
        this.total_amount = total_amount;
    }
    public String getBody() {
        return body;
    }
    public void setBody(String body) {
        this.body = body;
    }
    public String getTimeout_express() {
        return timeout_express;
    }
    public void setTimeout_express(String timeout_express) {
        this.timeout_express = timeout_express;
    }
    public String getProduct_code() {
        return product_code;
    }
    public void setProduct_code(String product_code) {
        this.product_code = product_code;
    }

}

  

Order Business package
order business Alipay to provide an interface alipay, internal order payment by calling PayService completed.

OrderController.java

package com.louis.epay.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alipay.api.AlipayApiException;
import com.louis.epay.alipay.AlipayBean;
import com.louis.epay.service.PayService;

/**
 * 订单接口
 * 
 * @author Louis
 * @date Dec 12, 2018
 */
@RestController()
@RequestMapping("order")
public class OrderController {

    @Autowired
    private PayService payService;

    /**
     * 阿里支付
     * @param tradeNo
     * @param subject
     * @param amount
     * @param body
     * @return
     * @throws AlipayApiException
     */
    @PostMapping(value = "alipay")
    public String alipay(String outTradeNo, String subject, String totalAmount, String body) throws AlipayApiException {
        AlipayBean alipayBean = new AlipayBean();
        alipayBean.setOut_trade_no(outTradeNo);
        alipayBean.setSubject(subject);
        alipayBean.setTotal_amount(totalAmount);
        alipayBean.setBody(body);
        return payService.aliPay(alipayBean);
    }
}

  

PayService package payment service interface Alipay, unified external offer.

PayService.java

com.louis.epay.service Package Penalty for; 

Import com.alipay.api.AlipayApiException; 
Import com.louis.epay.alipay.AlipayBean; 

/ ** 
 * payment services 
 * @author Louis 
 * @date Dec 12, 2018 
 * / 
public interface {PayService 

    / ** 
     * Alipay Interface 
     * @param alipayBean 
     * @return 
     * @throws AlipayApiException 
     * / 
    String ALIPAY (alipayBean alipayBean) throws AlipayApiException; 

}

  

Payment service implementation class, by calling for a variety of payment codes, common external provide payment services.

PayServiceImpl.java

package com.louis.epay.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alipay.api.AlipayApiException;
import com.louis.epay.alipay.Alipay;
import com.louis.epay.alipay.AlipayBean;
import com.louis.epay.service.PayService;

@Service
public class PayServiceImpl implements PayService {

    @Autowired
    private Alipay alipay;
    
    @Override
    public String aliPay(AlipayBean alipayBean) throws AlipayApiException {
        return alipay.pay(alipayBean);
    }

}

  

No classes start, there are starters comment on it.

EpayApplication.java

package com.louis.epay;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class EpayApplication {

    public static void main(String[] args) {
        SpringApplication.run(EpayApplication.class, args);
    }
}

  

Test page
to create a test.html page in the static directory for entering order information, and make payments.

test.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<H1>支付测试</H1>
<hr>
<div class="form-container">
    <form id="form" action="order/alipay" method="post">
        *商户订单 :
        <input type="text" name="outTradeNo" value="dzcp100010001"><br>
        *订单名称 :
        <input type="text" name="subject" value="红魔手机"><br>
        *付款金额 :
        <input type="text" name="totalAmount "value =" 0.1 "> <br> 
        <the INPUT of the type =" the Button "value =" Alipay "onclick =" submitForm ( 'order
        * Product Description:
        <the INPUT of the type =" text "name =" body "value =" Red Devils produced Games Mobile phone Nubian "> <br>
        <input type="button" value=" 微信支付  " onclick="submitForm('order/wexpay')"> 
    </form>
</div>
</body>

<script language="javascript">
function submitForm(action) {
    document.getElementById("form").action = action
    document.getElementById("form").submit()
}
</script>

<style>
.form-container {
    padding-top:10px;
}
input {
    margin:10px;
    
}
</style>
</html>

  Reprinted from: www.cnblogs.com/xifengxiaoma/p/10107635.html

Guess you like

Origin www.cnblogs.com/snm18/p/10974545.html