Java 杂谈第三方支付开发

对接Ping++支付

2018-12-14  本文已影响29人  小小蒜头

聚合支付是Ping++的产品之一,当然,Ping++一直走在与时俱进,开拓创新道路的前沿,它的业务不只局限于聚合支付,还有账户系统、商户系统等等。最近还推出了一个新产品裂变坊(一条分享链接,让老用户带来新用户),感兴趣的可以去看看

对接Ping++的支付其实很简单、便捷,官方给出的开发指南、API文档和一些demo可读性都很强。结合Ping++提供的例子,我这里采用SpringMVC架构调试了Ping++的支付宝电脑网站支付。在此之前我有调试过易宝支付,觉得对接流程过于繁复,你们也可以对比一下。

一、建立web工程

我的工程结构

二、配置文件和依赖关系的建立

web.xml

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <!-- 配置DispatchcerServlet -->
  <servlet>
    <servlet-name>springDispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- 配置Spring mvc下的配置文件的位置和名称 -->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>springDispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

springmvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">


    <!-- 配置自动扫描的包 -->
    <context:component-scan base-package="com.pingpp.controller"></context:component-scan>
    <!-- 添加注解驱动 -->
    <mvc:annotation-driven/>
    <!-- 配置视图解析器 如何把handler 方法返回值解析为实际的物理视图 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

    <!--静态资源映射-->
    <mvc:resources mapping="/js/**" location="/js/"/>
    <mvc:resources mapping="/styles/**" location="/styles/"/>
    <mvc:resources mapping="/img/**" location="/img/"/>
    <!--&lt;!&ndash; 加载配置属性文件 &ndash;&gt;-->
    <!--<context:property-placeholder-->
    <!--ignore-unresolvable="true" location="classpath:resource.properties"/>-->

</beans>

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>

    <groupId>com.pingpp</groupId>
    <artifactId>pingpp</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>pingpp Maven Webapp</name>
    <!-- FIXME change it to the project's website -->
    <url>http://www.example.com</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
        <spring.version>4.1.3.RELEASE</spring.version>
        <slf4j.version>1.6.6</slf4j.version>
        <jackson.version>2.4.2</jackson.version>
        <servlet-api.version>2.5</servlet-api.version>
        <jsp-api.version>2.0</jsp-api.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>

        <!-- Spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson.version}</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>${servlet-api.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jsp-api</artifactId>
            <version>${jsp-api.version}</version>
            <scope>provided</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.10</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.1.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
        <!--添加ping++依赖包-->
        <dependency>
            <groupId>Pingplusplus</groupId>
            <artifactId>pingpp-java</artifactId>
            <version>2.3.9</version>
            <type>jar</type>
        </dependency>
    </dependencies>

    <!--添加ping++支付远程仓库-->
    <repositories>
        <repository>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
            <id>central</id>
            <name>bintray</name>
            <url>http://jcenter.bintray.com</url>
        </repository>
    </repositories>

    <build>
        <finalName>pingpp</finalName>
        <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
            <plugins>
                <plugin>
                    <artifactId>maven-clean-plugin</artifactId>
                    <version>3.0.0</version>
                </plugin>
                <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
                <plugin>
                    <artifactId>maven-resources-plugin</artifactId>
                    <version>3.0.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.7.0</version>
                </plugin>
                <plugin>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.20.1</version>
                </plugin>
                <plugin>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>3.2.0</version>
                </plugin>
                <plugin>
                    <artifactId>maven-install-plugin</artifactId>
                    <version>2.5.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-deploy-plugin</artifactId>
                    <version>2.8.2</version>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>

三、需要注册成为Ping++的用户建立应用获取基础配置参数信息如APP_ID、APP_KEY、公私钥等。

还需要获取RSA公钥和私钥,我选择的是2048位加密。获取之后要将公钥放在Ping++平台的商户RSA公钥里面。

我将这些信息放在Const类里,方便调用。

Ping++ 提供了 Live 和 Test 两个模式,Test模式是模拟的支付,Live模式是和渠道交互的真实支付。两个模式均需要设置 App ID ,两个模式的变更可以通过代码中的 Live Key 和 Test Key 的切换。

apikey

Const

public class Const {
    public static String APP_ID = "app_******";
//    public static String APP_KEY = "sk_test_*****";
    public static String APP_KEY = "sk_live_******";
    public static String APP_PRIVATE_KEY = null;
    public static String PINGPP_PUBLIC__KEY = null;

    static {
        try {
            Resource resource = new ClassPathResource("private.pem");
            InputStream in = resource.getInputStream();
            APP_PRIVATE_KEY = IOUtils.toString(in);
            Resource resource1 = new ClassPathResource("public.pem");
            InputStream in1 = resource1.getInputStream();
            PINGPP_PUBLIC__KEY = IOUtils.toString(in1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

四、创建支付请求,返回charge对象给客户端

ChargeService

 /**
     * 创建支付
     *
     * @param charge
     * @return
     */
    public String createCharge(Charge charge) {
        Pingpp.appId = Const.APP_ID;
        Pingpp.apiKey = Const.APP_KEY;
        Pingpp.privateKey = Const.APP_PRIVATE_KEY;
        Map<String, Object> chargeMap = new HashMap<String, Object>();
        String orderNo = new Date().getTime() + CommonUtil.randomString(7);
        chargeMap.put("order_no", orderNo);// 推荐使用 8-20 位,要求数字或字母,不允许其他字符
        chargeMap.put("channel", charge.getChannel());// 支付使用的第三方支付渠道取值,请参考:https://www.pingxx.com/api#api-c-new
        chargeMap.put("amount", charge.getAmount());//订单总金额, 人民币单位:分(如订单总金额为 1 元,此处请填 100)
        chargeMap.put("client_ip", charge.getClientIp()); // 发起支付请求客户端的 IP 地址,格式为 IPV4,如: 127.0.0.1
        chargeMap.put("currency", "cny");
        chargeMap.put("subject", "一加6T");
        chargeMap.put("body", "一加,不将就");
        chargeMap.put("description","备注");
        Map<String, String> app = new HashMap<String, String>();
        app.put("id", Const.APP_ID);
        chargeMap.put("app", app);

        // extra 取值请查看相应方法说明
        chargeMap.put("extra", channelExtra(charge.getChannel()));

        try {
            //发起交易请求
            charge = Charge.create(chargeMap);
        } catch (APIConnectionException e) {
            e.printStackTrace();
        } catch (ChannelException e) {
            e.printStackTrace();
        } catch (RateLimitException e) {
            e.printStackTrace();
        } catch (AuthenticationException e) {
            e.printStackTrace();
        } catch (APIException e) {
            e.printStackTrace();
        } catch (InvalidRequestException e) {
            e.printStackTrace();
        }

        // 传到客户端请先转成字符串 .toString(), 调该方法,会自动转成正确的 JSON 字符串
        return charge.toString();
    }

ChargeController

package com.pingpp.controller;

import com.pingplusplus.model.Charge;
import com.pingpp.service.ChargeService;
import com.pingpp.utils.IPUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("/charge")
public class ChargeController {

    private ChargeService chargeService = new ChargeService();

    @RequestMapping(value = "/createCharge")
    @ResponseBody
    public String createCharge(HttpServletRequest request, HttpServletResponse response, @RequestBody Charge charge) {
        charge.setClientIp(IPUtil.getIp(request));
        String chargeString = chargeService.createCharge(charge);

        return chargeString;
    }
}

五、前端调起支付控件

 function wap_pay(channel) {
        var amount = $("#amount").val();
        var params = {
            "channel": channel,
            "amount": amount
        };
        $.ajax({
            type: 'POST',
            data: JSON.stringify(params),
            contentType: "application/json;charset=utf-8",
            dataType: 'json',
            traditional: true, //使json格式的字符串不会被转码
            url: '/charge/createCharge',

            success: function (data) {
                pingpp.createPayment(data, function (result, err) {
                // object 需是 Charge/Order/Recharge 的 JSON 字符串
                // 可按需使用 alert 方法弹出 log
                    console.log(result);
                    console.log(err.msg);
                    console.log(err.extra);
                    if (result == "success") {
                        alert("OK")
                        // 只有微信公众号 (wx_pub)、微信小程序(wx_lite)、QQ 公众号 (qpay_pub)、支付宝小程序(alipay_lite)支付成功的结果会在这里返回,其他的支付结果都会跳转到 extra 中对应的 URL
                    } else if (result == "fail") {
                        alert("fail")
                        // Ping++ 对象 object 不正确或者微信公众号/微信小程序/QQ公众号支付失败时会在此处返回
                    } else if (result == "cancel") {
                        alert("cancel")
                        // 微信公众号、微信小程序、QQ 公众号、支付宝小程序支付取消支付
                    }
                });
            },

            error: function (e) {
                alert("error");

                console.log(e)
            }

        });
    }
</script>

我目前就只测试了支付宝电脑网站支付,如果在对接Ping++支付的过程中有什么疑问,欢迎咨询。

源代码:https://github.com/yvettee36/pingpp

上一篇下一篇

猜你喜欢

热点阅读