paypal支付-收付款-java
paypal收款
简介
paypal支付逻辑是
创建订单—用户授权—服务端扣款—查询扣款结果,不是用户直接扣款,也没有回调
还有个坑
paypal 不同接口的 正确返回代码是 200 或 201,并非统一
依赖
<dependency>
<groupId>com.paypal.sdk</groupId>
<artifactId>checkout-sdk</artifactId>
<version>2.0.0</version>
</dependency>
创建订单
//环境、id、密钥
@Value("${paypal.mode}")
private String mode;//sandbox or live
@Value("${paypal.clientId}")
private String clientId;
@Value("${paypal.clientSecret}")
private String clientSecret;
//构建client
public PayPalHttpClient client(String mode, String clientId, String clientSecret) {
PayPalEnvironment environment = mode.equals("live") ?
new PayPalEnvironment.Live(clientId, clientSecret) :
new PayPalEnvironment.Sandbox(clientId, clientSecret);
return new PayPalHttpClient(environment);
}
public String createOrder(String coinType, String num) throws Exception {
//构建订单
OrderRequest orderRequest = new OrderRequest();
orderRequest.checkoutPaymentIntent("CAPTURE");
List<PurchaseUnitRequest> purchaseUnitRequests = new ArrayList<>();
PurchaseUnitRequest purchaseUnitRequest = new PurchaseUnitRequest()
.amountWithBreakdown(new AmountWithBreakdown()
.currencyCode(coinType)
.value(num));
purchaseUnitRequest.referenceId(UUID.fastUUID().toString());
purchaseUnitRequests.add(purchaseUnitRequest);
orderRequest.purchaseUnits(purchaseUnitRequests);
//创建订单
OrdersCreateRequest request = new OrdersCreateRequest();
request.header("prefer","return=representation");
request.requestBody(orderRequest);
HttpResponse<Order> response = client(mode, clientId, clientSecret).execute(request);
if(response.statusCode() != 201){
throw new Exception("statusCode: " + response.statusCode());
}
return response.result().id();
}
测试用法
@RequestMapping(value = "/test1", method = RequestMethod.POST)
public JSONObject test1() throws Exception {
String id = payPalservice.createOrder("USD", "1");
JSONObject jsonObject = new JSONObject();
jsonObject.put("id", id);
return jsonObject;
}
扣款
public String capture(String orderId) throws Exception {
OrdersCaptureRequest request = new OrdersCaptureRequest(orderId);
HttpResponse<Order> response = client(mode, clientId, clientSecret).execute(request);
if(response.statusCode() != 201){
throw new Exception("statusCode: " + response.statusCode());
}
String status = response.result().status();
if("COMPLETED".equals(status)) {
//支付成功
} else if("PENDING".equals(status)){
//pending中 丢到mq延迟查询支付结果 这里相当于递归去查 所以一定要mq延迟十秒或更久查询
} else {
//支付失败
}
return "";
}
查询支付结果
public String getCaptures(String orderId) throws Exception {
CapturesGetRequest request = new CapturesGetRequest(orderId);
HttpResponse<Capture> response = client(mode, clientId, clientSecret).execute(request);
if(response.statusCode() != 200){
throw new Exception("statusCode: " + response.statusCode());
}
String status = response.result().status();
if("COMPLETED".equals(status)) {
//支付成功
} else if("PENDING".equals(status)){
//pending中 丢到mq延迟查询支付结果 这里相当于递归去查 所以一定要mq延迟十秒或更久查询
} else {
//支付失败
}
return "";
}
paypal付款
依赖
<dependency>
<groupId>com.paypal.sdk</groupId>
<artifactId>rest-api-sdk</artifactId>
<version>1.14.0</version>
</dependency>
付款(有几个导不到包的类是自定义的 文章后面有附)
/**
*
* @param tradeId 订单号 自己生成
* @param email 收款邮箱
* @param coinType 货币类型 usd thb。。。
* @param num 数量
* @return
* @throws Exception
*/
public void payout(int tradeId, String email, String coinType, String num) throws Exception {
//付款头信息
PayoutSenderBatchHeader senderBatchHeader = new PayoutSenderBatchHeader();
senderBatchHeader.setSenderBatchId("payout_" + tradeId);
senderBatchHeader.setEmailSubject("receive a payout");
senderBatchHeader.setRecipientType("EMAIL");
//付款list
List<PayoutItem> items = new ArrayList<>();
//付款结构
PayoutItem payoutItem = new PayoutItem();
payoutItem.setSenderItemId("1");
payoutItem.setReceiver(email);
payoutItem.setNote("receive U");
//付款金额 单位
Currency currency = new Currency();
currency.setCurrency(coinType);
currency.setValue(num);
//付款对象
payoutItem.setAmount(currency);
items.add(payoutItem);
//付款body结构
Payout payout = new Payout(senderBatchHeader, items);
//付款请求体
PayoutRequest request = new PayoutRequest();
request.requestBody(payout);
//请求付款
HttpResponse<JSONObject> response = client(mode, clientId, clientSecret).execute(request);
if(response.statusCode() != 201){
throw new Exception("statusCode: " + response.statusCode());
}
JSONObject result = response.result();
String batch_status = result.getJSONObject("batch_header").getString("batch_status");
//订单号
String payout_batch_id = result.getJSONObject("batch_header").getString("payout_batch_id");
if("SUCCESS".equals(batch_status)) {
//支付成功
} else if("PENDING".equals(batch_status)){
//丢到mq 查询订单 与支付同理 递归查 要延迟mq
} else {
//支付失败
}
}
查询付款结果
public String getPayout(String payout_batch_id) throws Exception {
PayoutGetRequest request = new PayoutGetRequest(payout_batch_id);
HttpResponse<JSONObject> response = client(mode, clientId, clientSecret).execute(request);
if(response.statusCode() != 200){
throw new Exception("statusCode: " + response.statusCode());
}
String status = response.result().getJSONObject("batch_header").getString("batch_status");
if("SUCCESS".equals(status)) {
//支付成功
} else if("PENDING".equals(status)){
//丢到mq 查询订单 与支付同理 递归查 要延迟mq
} else {
//支付失败
}
}
几个model和工具类
Currency.java
import com.paypal.http.annotations.Model;
import com.paypal.http.annotations.SerializedName;
@Model
public class Currency {
@SerializedName("currency")
private String currency;
@SerializedName("value")
private String value;
public Currency() {
}
public Currency(String currency, String value) {
this.currency = currency;
this.value = value;
}
public String getCurrency() {
return this.currency;
}
public String getValue() {
return this.value;
}
public Currency setCurrency(String currency) {
this.currency = currency;
return this;
}
public Currency setValue(String value) {
this.value = value;
return this;
}
}
Payout.java
import com.paypal.api.payments.Links;
import com.paypal.base.rest.PayPalResource;
import com.paypal.http.annotations.Model;
import com.paypal.http.annotations.SerializedName;
import java.util.List;
@Model
public class Payout extends PayPalResource {
@SerializedName("sender_batch_header")
private PayoutSenderBatchHeader senderBatchHeader;
@SerializedName("items")
private List<PayoutItem> items;
@SerializedName("links")
private List<Links> links;
public Payout() {
}
public Payout(PayoutSenderBatchHeader senderBatchHeader, List<PayoutItem> items) {
this.senderBatchHeader = senderBatchHeader;
this.items = items;
}
public PayoutSenderBatchHeader getSenderBatchHeader() {
return this.senderBatchHeader;
}
public List<PayoutItem> getItems() {
return this.items;
}
public List<Links> getLinks() {
return this.links;
}
public Payout setSenderBatchHeader(PayoutSenderBatchHeader senderBatchHeader) {
this.senderBatchHeader = senderBatchHeader;
return this;
}
public Payout setItems(List<PayoutItem> items) {
this.items = items;
return this;
}
public Payout setLinks(List<Links> links) {
this.links = links;
return this;
}
}
PayoutItem.java
import com.paypal.http.annotations.Model;
import com.paypal.http.annotations.SerializedName;
@Model
public class PayoutItem {
@SerializedName("recipient_type")
private String recipientType;
@SerializedName("amount")
private Currency amount;
@SerializedName("note")
private String note;
@SerializedName("receiver")
private String receiver;
@SerializedName("sender_item_id")
private String senderItemId;
public PayoutItem() {
}
public PayoutItem(Currency amount, String receiver) {
this.amount = amount;
this.receiver = receiver;
}
public String getRecipientType() {
return this.recipientType;
}
public Currency getAmount() {
return this.amount;
}
public String getNote() {
return this.note;
}
public String getReceiver() {
return this.receiver;
}
public String getSenderItemId() {
return this.senderItemId;
}
public PayoutItem setRecipientType(String recipientType) {
this.recipientType = recipientType;
return this;
}
public PayoutItem setAmount(Currency amount) {
this.amount = amount;
return this;
}
public PayoutItem setNote(String note) {
this.note = note;
return this;
}
public PayoutItem setReceiver(String receiver) {
this.receiver = receiver;
return this;
}
public PayoutItem setSenderItemId(String senderItemId) {
this.senderItemId = senderItemId;
return this;
}
}
PayoutSenderBatchHeader.java
import com.paypal.http.annotations.Model;
import com.paypal.http.annotations.SerializedName;
@Model
public class PayoutSenderBatchHeader {
@SerializedName("sender_batchId")
private String senderBatchId;
@SerializedName("email_subject")
private String emailSubject;
@SerializedName("recipient_type")
private String recipientType;
public PayoutSenderBatchHeader() {
}
public String getSenderBatchId() {
return this.senderBatchId;
}
public String getEmailSubject() {
return this.emailSubject;
}
public String getRecipientType() {
return this.recipientType;
}
public PayoutSenderBatchHeader setSenderBatchId(String senderBatchId) {
this.senderBatchId = senderBatchId;
return this;
}
public PayoutSenderBatchHeader setEmailSubject(String emailSubject) {
this.emailSubject = emailSubject;
return this;
}
public PayoutSenderBatchHeader setRecipientType(String recipientType) {
this.recipientType = recipientType;
return this;
}
}
PayoutGetRequest.java
public class PayoutGetRequest extends HttpRequest<JSONObject> {
public PayoutGetRequest(String orderId) {
super("/v1/payments/payouts/{order_id}?", "GET", JSONObject.class);
try {
this.path(this.path().replace("{order_id}", URLEncoder.encode(String.valueOf(orderId), "UTF-8")));
} catch (UnsupportedEncodingException var3) {
}
this.header("Content-Type", "application/json");
}
public PayoutGetRequest authorization(String authorization) {
this.header("Authorization", String.valueOf(authorization));
return this;
}
public PayoutGetRequest contentType(String contentType) {
this.header("Content-Type", String.valueOf(contentType));
return this;
}
public PayoutGetRequest payPalPartnerAttributionId(String payPalPartnerAttributionId) {
this.header("PayPal-Partner-Attribution-Id", String.valueOf(payPalPartnerAttributionId));
return this;
}
public PayoutGetRequest prefer(String prefer) {
this.header("Prefer", String.valueOf(prefer));
return this;
}
public PayoutGetRequest requestBody(Payout payout) {
super.requestBody(payout);
return this;
}
}
PayoutRequest.java
public class PayoutRequest extends HttpRequest<JSONObject> {
public PayoutRequest() {
super("/v1/payments/payouts?", "POST", JSONObject.class);
this.header("Content-Type", "application/json");
}
public PayoutRequest authorization(String authorization) {
this.header("Authorization", String.valueOf(authorization));
return this;
}
public PayoutRequest contentType(String contentType) {
this.header("Content-Type", String.valueOf(contentType));
return this;
}
public PayoutRequest payPalPartnerAttributionId(String payPalPartnerAttributionId) {
this.header("PayPal-Partner-Attribution-Id", String.valueOf(payPalPartnerAttributionId));
return this;
}
public PayoutRequest prefer(String prefer) {
this.header("Prefer", String.valueOf(prefer));
return this;
}
public PayoutRequest requestBody(Payout payout) {
super.requestBody(payout);
return this;
}
}