java对接PayPal支付 (添加物流跟踪信息)

上一篇文章 java对接PayPal支付(v2). 讲了PayPal v2:checkout-sdk 的对接过程,今天我们讲讲如何通过代码对已经发货的订单添加物流信息。

为何要添加物流信息?

上一边文章已经提到过了,通过PayPal支付的订单,一旦出现争议,PayPal大多数时候是偏向用户的,商户这边如果再各个细节上处理的不好,会导致货、钱两空的局面。为了防止这种情况,添加物流信息可避免用户恶意发起没有收到货物的争议。

言归正传,正式开始

一、引入maven依赖

这次我们必须引入 v1 rest-api-sdk,目的是为了获取token,如果你不想再引入这个maven的话,也是可以的,自己根据PayPal官网的文档,写个http请求,获取token也行,下面这幅图就是获取curl的方式
java对接PayPal支付 (添加物流跟踪信息)_第1张图片

		<dependency>
			<groupId>com.paypal.sdk</groupId>
			<artifactId>rest-api-sdk</artifactId>
			<version>LATEST</version>
		</dependency>

二、编写代码

1、AddTracking(添加物流信息)

由于官方并没有将添加物流信息的接口融入SDK,所以我们需要自己写http请求,进行请求访问。

package com.ratta.paypal.info;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.paypal.base.rest.OAuthTokenCredential;
import com.paypal.base.rest.PayPalRESTException;
import com.paypal.http.HttpResponse;
import com.paypal.orders.Order;
import com.paypal.orders.OrdersGetRequest;
import com.ratta.util.HttpUtil;

public class AddTracking {

	private String clientId = "AdTJ2en6Av42r1xoziJj6bJK-X4tRGDHACZId0OPXfGyXs8OyoYEmlm8bHjzrgd3UislDQR0iBP7x-wM";
	private String clientSecret = "EC9DSrfAfVfo-c3K-1dILXA5iijnHtaunKwv2JzECSz9jcdy3t78rDFeAEgaixnnIYYlgQcipbZQWoCa";
	private String mode = "sandbox";
	private static String sandbox = "https://api.sandbox.paypal.com";
	private static String live = "https://api.paypal.com";
	private static String url = "/v1/shipping/trackers-batch";
	
	public TrackingInfo buildRequestBody(String captureId) {
        TrackingInfo trackingInfo = new TrackingInfo();
        trackingInfo.setTransaction_id(captureId);
        //物流单号
        trackingInfo.setTracking_number("443844607822");
		return trackingInfo;
	}
	public String addTrack(String orderId) throws PayPalRESTException, IOException {
		OrdersGetRequest ordersGetRequest = new OrdersGetRequest(orderId);
		PayPalClient payPalClient = new PayPalClient();
        HttpResponse<Order> ordersGetResponse = payPalClient.client(mode, clientId, clientSecret).execute(ordersGetRequest);
		String captureId = ordersGetResponse.result().purchaseUnits().get(0).payments().captures().get(0).id();
        System.out.println("Status Code: " + ordersGetResponse.statusCode());
		System.out.println("Status: " + ordersGetResponse.result().status());
		System.out.println("Order id: " + ordersGetResponse.result().id());
		System.out.println("Capture id: " + captureId);
		Map<String, String> configurationMap = new HashMap<String, String>();
		configurationMap.put("service.EndPoint", "live".equals(mode)? live : sandbox);
		OAuthTokenCredential merchantTokenCredential = new OAuthTokenCredential(
				clientId, clientSecret, configurationMap);
			String accessToken = merchantTokenCredential.getAccessToken();
			System.out.println("token = " + accessToken);
			Map<String, Object> params = new HashMap<String, Object>();
			ArrayList<TrackingInfo> list =  new ArrayList<TrackingInfo>();
			TrackingInfo trackingInfo = new TrackingInfo();
			trackingInfo = buildRequestBody(captureId);
			list.add(trackingInfo);
	        params.put("trackers", list);
	        JSONObject json = new JSONObject(params);
	        String result = HttpUtil.doPost("live".equals(mode)? live + url : sandbox + url, json.toString(), accessToken);
	        System.out.println("result = " + result);
		return result;
	}
	
	public static void main(String[] args) {
		try {
			new AddTracking().addTrack("订单id,CreateOrder 生成");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}


2、TrackingInfo(物流信息主体)

package com.ratta.paypal.info;

import java.io.Serializable;

import lombok.Data;
import lombok.ToString;
@Data
@ToString
public class TrackingInfo implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private String transaction_id;
	private String tracking_number;
	/**
	 * DELIVERED、CANCELLED 退款被拒绝
	 * SHIPPED    已发货
	 * DROPPED_OFF 已尝试发放退款
	 * IN_TRANSIT  已转账
	 */
	private String status = "SHIPPED";

	/**
	 * DHL   DHL Express
	 * FEDEX
	 * 更多物流公司代码,参考官网
	 */
	private String carrier = "FEDEX";
	
}

3、HttpUtil

package com.ratta.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import com.alibaba.csp.sentinel.util.StringUtil;


public class HttpUtil {
	
	private static final String ENCODING = "UTF-8";
	
    public static String doGet(String httpurl) {
        HttpURLConnection connection = null;
        InputStream is = null;
        BufferedReader br = null;
        String result = null;// 返回结果字符串
        try {
            // 创建远程url连接对象
            URL url = new URL(httpurl);
            // 通过远程url连接对象打开一个连接,强转成httpURLConnection类
            connection = (HttpURLConnection) url.openConnection();
            // 设置连接方式:get
            connection.setRequestMethod("GET");
            // 设置连接主机服务器的超时时间:15000毫秒
            connection.setConnectTimeout(15000);
            // 设置读取远程返回的数据时间:60000毫秒
            connection.setReadTimeout(60000);
            // 发送请求
            connection.connect();
            // 通过connection连接,获取输入流
            if (connection.getResponseCode() == 200) {
                is = connection.getInputStream();
                // 封装输入流is,并指定字符集
                br = new BufferedReader(new InputStreamReader(is, ENCODING));
                // 存放数据
                StringBuffer sbf = new StringBuffer();
                String temp = null;
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append("\r\n");
                }
                result = sbf.toString();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            connection.disconnect();// 关闭远程连接
        }

        return result;
    }

    public static String doPost(String httpUrl, String param, String authorization) {
        HttpURLConnection connection = null;
        InputStream is = null;
        OutputStream os = null;
        BufferedReader br = null;
        String result = null;
        try {
            URL url = new URL(httpUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setConnectTimeout(15000);
            connection.setReadTimeout(60000);
            // 默认值为:false,当向远程服务器传送数据/写数据时,需要设置为true
            connection.setDoOutput(true);
            // 默认值为:true,当前向远程服务读取数据时,设置为true,该参数可有可无
            connection.setDoInput(true);
            // 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
            connection.setRequestProperty("Content-Type", "application/json");
            // 设置鉴权信息:Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0
            if(!StringUtil.isEmpty(authorization)) {
            	connection.setRequestProperty("Authorization", authorization);
            }
            // 通过连接对象获取一个输出流
            os = connection.getOutputStream();
            // 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的
            os.write(param.getBytes());
            // 通过连接对象获取一个输入流,向远程读取
            if (connection.getResponseCode() == 200) {

                is = connection.getInputStream();
                // 对输入流对象进行包装:charset根据工作项目组的要求来设置
                br = new BufferedReader(new InputStreamReader(is, ENCODING));

                StringBuffer sbf = new StringBuffer();
                String temp = null;
                // 循环遍历一行一行读取数据
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append("\r\n");
                }
                result = sbf.toString();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // 断开与远程地址url的连接
            connection.disconnect();
        }
        return result;
    }
    
    public static void main(String[] args) {
    	
    	
    }
    
}

不引入v1的maven依赖时。获取token

public static void main(String[] args) {

		String clientId = "AdTJ2en6Av42r1xoziJj6bJK-X4tRGDHACZId0OPXfGyXs8OyoYEmlm8bHjzrgd3UislDQR0iBP7x-wM";
	    String clientSecret = "EC9DSrfAfVfo-c3K-1dILXA5iijnHtaunKwv2JzECSz9jcdy3t78rDFeAEgaixnnIYYlgQcipbZQWoCa";

		String authString = clientId + ":" + clientSecret;

		System.out.println("auth string: " + authString);

		//Base64编码

		byte[] authEncBytes = null;
		try {
			authEncBytes = Base64.encodeBase64(authString.getBytes("utf-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		String authStringEnc = new String(authEncBytes);
		authStringEnc = "Basic " + authStringEnc;
		String param = "grant_type=client_credentials";
		String result = HttpUtil.doPost("https://api.sandbox.paypal.com/v1/oauth2/token", param, authStringEnc);
		System.out.println("result = " + result);
		Map map = JSON.parseObject(result);
		String accessToken = (String) map.get("access_token");
		accessToken = (String) map.get("token_type") + " " + accessToken;
		System.out.println("token = " + accessToken);
	}

java对接PayPal支付 (添加物流跟踪信息)_第2张图片
添加完物流信息后,PayPal订单这里就会如图这样显示

你可能感兴趣的:(PayPal,java,支付)