對接Ping++支付

weixin_34037977發表於2018-12-14

聚合支付是Ping++的產品之一,當然,Ping++一直走在與時俱進,開拓創新道路的前沿,它的業務不只侷限於聚合支付,還有賬戶系統、商戶系統等等。最近還推出了一個新產品裂變坊(一條分享連結,讓老使用者帶來新使用者),感興趣的可以去看看

對接Ping++的支付其實很簡單、便捷,官方給出的開發指南、API文件和一些demo可讀性都很強。結合Ping++提供的例子,我這裡採用SpringMVC架構除錯了Ping++的支付寶電腦網站支付。在此之前我有除錯過易寶支付,覺得對接流程過於繁複,你們也可以對比一下。

目前我成功對接了 Ping++ 的支付、退款、訂單、餘額充值、餘額轉賬、餘額提現的功能。

參考:使用Ping++的具體流程

一、建立web工程

1037735-33aefc008b385965.png
我的工程結構

二、配置檔案和依賴關係的建立

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 的切換。

1037735-76ccb682fbc35c6d.png
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>

支付之後的連結填的本地的,所以訪問不成功。下面的gif圖片載入會有些緩慢。

1037735-486798606a4b646f.gif
Test模式支付寶電腦網站支付
1037735-5720137562717fb3.gif
Live模式支付寶電腦網站支付

我目前就只測試了支付寶電腦網站支付,如果在對接Ping++支付的過程中有什麼疑問,歡迎諮詢。

原始碼:https://github.com/yvettee36/pingpp

相關文章