ios swift java_Paypal支付接入(Android/IOS(swift)/Java后台)

先贴一个http请求封装工具

import javax.net.ssl.HttpsURLConnection;

import java.io.ByteArrayOutputStream;

import java.io.InputStream;

import java.net.HttpURLConnection;

import java.net.Proxy;

import java.net.URL;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

/**

* Created by marking on 2016/11/26.

* 用于模拟http及https的got/post请求

*

*/

public class HttpUtils {

private String HTTPS = "https";

private String GET = "GET";

private String POST = "POST";

private static HttpUtils httpUtils;

private HttpUtils() {

}

public static HttpUtils getInstance() {

if (httpUtils == null) {

httpUtils = new HttpUtils();

}

return httpUtils;

}

public interface IWebCallback {

void onCallback(int status, String message, Map> heard, byte[] data);

void onFail(int status, String message);

}

public byte[] getURLResponse(String urlString, HashMap heads) {

byte[] result = null;

if (urlString != null) {

HttpURLConnection conn = null; //连接对象

InputStream is = null;

ByteArrayOutputStream baos = null;

try {

URL url = new URL(urlString); //URL对象

if (urlString.startsWith(HTTPS)) {

conn = (HttpsURLConnection) url.openConnection();

} else {

conn = (HttpURLConnection) url.openConnection();

}

conn.setConnectTimeout(5 * 1000);

conn.setDoOutput(true);

conn.setRequestMethod(GET);

if (heads != null) {

for (String key : heads.keySet()) {

conn.addRequestProperty(key, heads.get(key));

}

}

is = conn.getInputStream(); //获取输入流,此时才真正建立链接

baos = new ByteArrayOutputStream();

byte[] temp = new byte[1024];

int len;

while ((len = is.read(temp)) != -1) {

baos.write(temp, 0, len);

}

result = baos.toByteArray();

} catch (Exception e) {

} finally {

CloseUtils.closeSilently(is);

CloseUtils.closeSilently(baos);

if (conn != null) {

conn.disconnect();

}

}

}

return result;

}

public void getURLResponse(String urlString, HashMap heads, IWebCallback iWebCallback) {

getURLResponse(urlString, heads, null, iWebCallback);

}

public void getURLResponse(String urlString, HashMap heads, Proxy proxy, IWebCallback iWebCallback) {

if (urlString != null) {

HttpURLConnection conn = null; //连接对象

InputStream is = null;

ByteArrayOutputStream baos = null;

try {

URL url = new URL(urlString); //URL对象

if (proxy == null) {

if (urlString.startsWith(HTTPS)) {

conn = (HttpsURLConnection) url.openConnection();

} else {

conn = (HttpURLConnection) url.openConnection();

}

} else {

if (urlString.startsWith(HTTPS)) {

conn = (HttpsURLConnection) url.openConnection(proxy);

} else {

conn = (HttpURLConnection) url.openConnection(proxy);

}

}

conn.setConnectTimeout(5 * 1000);

conn.setDoOutput(true);

conn.setRequestMethod(GET);

if (heads != null) {

for (String key : heads.keySet()) {

conn.addRequestProperty(key, heads.get(key));

}

}

is = conn.getInputStream(); //获取输入流,此时才真正建立链接

baos = new ByteArrayOutputStream();

byte[] temp = new byte[1024];

int len;

while ((len = is.read(temp)) != -1) {

baos.write(temp, 0, len);

}

if (iWebCallback != null) {

iWebCallback.onCallback(conn.getResponseCode(), conn.getResponseMessage(), conn.getHeaderFields(), baos.toByteArray());

}

} catch (Exception e) {

int code = 600;

try {

code = conn == null ? 600 : conn.getResponseCode();

} catch (Exception e1) {

}

if (iWebCallback != null) {

iWebCallback.onFail(code, e.toString());

}

} finally {

CloseUtils.closeSilently(is);

CloseUtils.closeSilently(baos);

if (conn != null) {

conn.disconnect();

}

}

}

}

public byte[] postURLResponse(String urlString, HashMap headers, byte[] postData) {

byte[] result = null;

if (urlString != null) {

HttpURLConnection conn = null; //连接对象

InputStream is = null;

ByteArrayOutputStream baos = null;

try {

URL url = new URL(urlString); //URL对象

if (urlString.startsWith(HTTPS)) {

conn = (HttpsURLConnection) url.openConnection();

} else {

conn = (HttpURLConnection) url.openConnection();

}

conn.setConnectTimeout(5 * 1000);

conn.setDoOutput(true);

conn.setRequestMethod(POST); //使用post请求

conn.setRequestProperty("Charsert", "UTF-8");

if (headers != null) {

for (Map.Entry temp : headers.entrySet()) {

conn.setRequestProperty(temp.getKey(), temp.getValue());

}

}

conn.getOutputStream().write(postData);

is = conn.getInputStream(); //获取输入流,此时才真正建立链接

baos = new ByteArrayOutputStream();

byte[] temp = new byte[1024];

int len;

while ((len = is.read(temp)) != -1) {

baos.write(temp, 0, len);

}

result = baos.toByteArray();

} catch (Exception e) {

} finally {

CloseUtils.closeSilently(is);

CloseUtils.closeSilently(baos);

if (conn != null) {

conn.disconnect();

}

}

}

return result;

}

public void postURLResponse(String urlString, HashMap headers,

byte[] postData, IWebCallback iWebCallback) {

if (urlString != null) {

HttpURLConnection conn = null; //连接对象

InputStream is = null;

ByteArrayOutputStream baos = null;

try {

URL url = new URL(urlString); //URL对象

if (urlString.startsWith(HTTPS)) {

conn = (HttpsURLConnection) url.openConnection();

} else {

conn = (HttpURLConnection) url.openConnection();

}

conn.setConnectTimeout(5 * 1000);

conn.setDoOutput(true);

conn.setRequestMethod(POST); //使用post请求

conn.setRequestProperty("Charsert", "UTF-8");

if (headers != null) {

for (Map.Entry temp : headers.entrySet()) {

conn.setRequestProperty(temp.getKey(), temp.getValue());

}

}

conn.getOutputStream().write(postData);

is = conn.getInputStream(); //获取输入流,此时才真正建立链接

baos = new ByteArrayOutputStream();

byte[] temp = new byte[1024];

int len;

while ((len = is.read(temp)) != -1) {

baos.write(temp, 0, len);

}

if (iWebCallback != null) {

iWebCallback.onCallback(conn.getResponseCode(), conn.getResponseMessage(), conn.getHeaderFields(), baos.toByteArray());

}

} catch (Exception e) {

int code = 600;

try {

code = conn == null ? 600 : conn.getResponseCode();

} catch (Exception e1) {

}

if (iWebCallback != null) {

iWebCallback.onFail(code, e.toString());

}

} finally {

CloseUtils.closeSilently(is);

CloseUtils.closeSilently(baos);

if (conn != null) {

conn.disconnect();

}

}

}

}

}

主要工具类,为了方便使用,全放一个类里边了,另外由于返回的数据结构实在复杂,所以后面的对象代码偏多,主要看前面几个方法便好。

import com.alibaba.fastjson.JSON;

import org.apache.tomcat.util.codec.binary.Base64;

import java.util.ArrayList;

import java.util.HashMap;

public class PayPalUtils {

// private static final String TOKEN_URL = "https://api.sandbox.paypal.com/v1/oauth2/token";//沙箱链接

// private static final String PAYMENT_DETAIL = "https://api.sandbox.paypal.com/v1/payments/payment/";//沙箱链接

private static final String TOKEN_URL = "https://api.paypal.com/v1/oauth2/token";

private static final String PAYMENT_DETAIL = "https://api.paypal.com/v1/payments/payment/";

private static final String clientId = "";//这两个参数应该很容易在paypal开发者页面找到,文中会贴出截图

private static final String secret = "";

private static String getAccessToken() {

byte[] resultBytes = HttpUtils.getInstance().postURLResponse(TOKEN_URL, new HashMap() {{

put("Accept", "application/json");

put("Accept-Language", "en_US");

put("Authorization", "Basic " + Base64.encodeBase64String((clientId + ":" + secret).getBytes()));

}}, "grant_type=client_credentials".getBytes());

ResponseToken result = resultBytes == null ? null : JSON.parseObject(new String(resultBytes), ResponseToken.class);

return result == null ? null : result.accessToken;

}

private static ResponsePayPayl getResponsePayPayl(String paymentId) {

String token = getAccessToken();

if (token == null) {

System.out.println("verify paypal payment get token error.");

return null;

}

byte[] resultBytes = HttpUtils.getInstance().getURLResponse(PAYMENT_DETAIL + paymentId

, new HashMap() {{

put("Accept", "application/json");

put("Authorization", "Bearer " + token);

}});

return resultBytes == null ? null : JSON.parseObject(new String(resultBytes), ResponsePayPayl.class);

}

public static boolean isSuccess(String paymentId) {

ResponsePayPayl responsePayPayl = getResponsePayPayl(paymentId);

System.out.println("paypal.state=" + (responsePayPayl == null ? "null" : responsePayPayl.state));

return responsePayPayl != null && "approved".equals(responsePayPayl.state);

}

public static String getOrderNumber(String paymentId) {

ResponsePayPayl responsePayPayl = getResponsePayPayl(paymentId);

if (responsePayPayl != null && responsePayPayl.transactions != null

&& responsePayPayl.transactions.size() > 0 && responsePayPayl.transactions.get(0).itemList != null

&& responsePayPayl.transactions.get(0).itemList.items != null

&& responsePayPayl.transactions.get(0).itemList.items.size() > 0) {

return responsePayPayl.transactions.get(0).itemList.items.get(0).sku;

}

return null;

}

public static class ResponsePayPayl {

private String id;

private String intent;

private String state;

private String cart;

private Payer payer;

private ArrayList transactions;

private String createTime;

private ArrayList links;

public String getId() {

return id;

}

public void setId(String id) {

this.id = id;

}

public String getIntent() {

return intent;

}

public void setIntent(String intent) {

this.intent = intent;

}

public String getState() {

return state;

}

public void setState(String state) {

this.state = state;

}

public String getCart() {

return cart;

}

public void setCart(String cart) {

this.cart = cart;

}

public Payer getPayer() {

return payer;

}

public void setPayer(Payer payer) {

this.payer = payer;

}

public ArrayList getTransactions() {

return transactions;

}

public void setTransactions(ArrayList transactions) {

this.transactions = transactions;

}

public String getCreateTime() {

return createTime;

}

public void setCreateTime(String createTime) {

this.createTime = createTime;

}

public ArrayList getLinks() {

return links;

}

public void setLinks(ArrayList links) {

this.links = links;

}

@Override

public String toString() {

return "ResponsePayPayl{" +

"id='" + id + '\'' +

", intent='" + intent + '\'' +

", state='" + state + '\'' +

", cart='" + cart + '\'' +

", payer=" + payer +

", transactions=" + transactions +

", createTime='" + createTime + '\'' +

", links=" + links +

'}';

}

}

public static class Transaction {

private Amount amount;

private Payee payee;

private String description;

private ItemList itemList;

private ArrayList relatedResources;

public Amount getAmount() {

return amount;

}

public void setAmount(Amount amount) {

this.amount = amount;

}

public Payee getPayee() {

return payee;

}

public void setPayee(Payee payee) {

this.payee = payee;

}

public String getDescription() {

return description;

}

public void setDescription(String description) {

this.description = description;

}

public ItemList getItemList() {

return itemList;

}

public void setItemList(ItemList itemList) {

this.itemList = itemList;

}

public ArrayList getRelatedResources() {

return relatedResources;

}

public void setRelatedResources(ArrayList relatedResources) {

this.relatedResources = relatedResources;

}

@Override

public String toString() {

return "Transaction{" +

"amount=" + amount +

", payee=" + payee +

", description='" + description + '\'' +

", itemList=" + itemList +

", relatedResources=" + relatedResources +

'}';

}

}

public static class RelatedResource {

private Sale sale;

public Sale getSale() {

return sale;

}

public void setSale(Sale sale) {

this.sale = sale;

}

@Override

public String toString() {

return "RelatedResource{" +

"sale=" + sale +

'}';

}

}

public static class Sale {

private String id;

private String state;

private Amount amount;

private String paymentMode;

private String protectionEligibility;

private String protectionEligibilityType;

private TransactionFee transactionFee;

private String parentPayment;

private String createTime;

private String updateTime;

private ArrayList links;

public String getId() {

return id;

}

public void setId(String id) {

this.id = id;

}

public String getState() {

return state;

}

public void setState(String state) {

this.state = state;

}

public Amount getAmount() {

return amount;

}

public void setAmount(Amount amount) {

this.amount = amount;

}

public String getPaymentMode() {

return paymentMode;

}

public void setPaymentMode(String paymentMode) {

this.paymentMode = paymentMode;

}

public String getProtectionEligibility() {

return protectionEligibility;

}

public void setProtectionEligibility(String protectionEligibility) {

this.protectionEligibility = protectionEligibility;

}

public String getProtectionEligibilityType() {

return protectionEligibilityType;

}

public void setProtectionEligibilityType(String protectionEligibilityType) {

this.protectionEligibilityType = protectionEligibilityType;

}

public TransactionFee getTransactionFee() {

return transactionFee;

}

public void setTransactionFee(TransactionFee transactionFee) {

this.transactionFee = transactionFee;

}

public String getParentPayment() {

return parentPayment;

}

public void setParentPayment(String parentPayment) {

this.parentPayment = parentPayment;

}

public String getCreateTime() {

return createTime;

}

public void setCreateTime(String createTime) {

this.createTime = createTime;

}

public String getUpdateTime() {

return updateTime;

}

public void setUpdateTime(String updateTime) {

this.updateTime = updateTime;

}

public ArrayList getLinks() {

return links;

}

public void setLinks(ArrayList links) {

this.links = links;

}

@Override

public String toString() {

return "Sale{" +

"id='" + id + '\'' +

", state='" + state + '\'' +

", amount=" + amount +

", paymentMode='" + paymentMode + '\'' +

", protectionEligibility='" + protectionEligibility + '\'' +

", protectionEligibilityType='" + protectionEligibilityType + '\'' +

", transactionFee=" + transactionFee +

", parentPayment='" + parentPayment + '\'' +

", createTime='" + createTime + '\'' +

", updateTime='" + updateTime + '\'' +

", links=" + links +

'}';

}

}

public static class TransactionFee {

private String value;

private String currency;

public String getValue() {

return value;

}

public void setValue(String value) {

this.value = value;

}

public String getCurrency() {

return currency;

}

public void setCurrency(String currency) {

this.currency = currency;

}

@Override

public String toString() {

return "TransactionFee{" +

"value='" + value + '\'' +

", currency='" + currency + '\'' +

'}';

}

}

public static class ItemList {

private ArrayList items;

private ShippingAddress shippingAddress;

public ArrayList getItems() {

return items;

}

public void setItems(ArrayList items) {

this.items = items;

}

public ShippingAddress getShippingAddress() {

return shippingAddress;

}

public void setShippingAddress(ShippingAddress shippingAddress) {

this.shippingAddress = shippingAddress;

}

@Override

public String toString() {

return "ItemList{" +

"items=" + items +

", shippingAddress=" + shippingAddress +

'}';

}

}

public static class Item {

private String name;

private String sku;

private String price;

private String currency;

private String tax;

private int quantity;

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String getSku() {

return sku;

}

public void setSku(String sku) {

this.sku = sku;

}

public String getPrice() {

return price;

}

public void setPrice(String price) {

this.price = price;

}

public String getCurrency() {

return currency;

}

public void setCurrency(String currency) {

this.currency = currency;

}

public String getTax() {

return tax;

}

public void setTax(String tax) {

this.tax = tax;

}

public int getQuantity() {

return quantity;

}

public void setQuantity(int quantity) {

this.quantity = quantity;

}

@Override

public String toString() {

return "Item{" +

"name='" + name + '\'' +

", sku='" + sku + '\'' +

", price='" + price + '\'' +

", currency='" + currency + '\'' +

", tax='" + tax + '\'' +

", quantity=" + quantity +

'}';

}

}

public static class Payee {

private String merchantId;

public String getMerchantId() {

return merchantId;

}

public void setMerchantId(String merchantId) {

this.merchantId = merchantId;

}

@Override

public String toString() {

return "Payee{" +

"merchantId='" + merchantId + '\'' +

'}';

}

}

public static class Amount {

private String total;

private String currency;

private Details details;

public String getTotal() {

return total;

}

public void setTotal(String total) {

this.total = total;

}

public String getCurrency() {

return currency;

}

public void setCurrency(String currency) {

this.currency = currency;

}

public Details getDetails() {

return details;

}

public void setDetails(Details details) {

this.details = details;

}

@Override

public String toString() {

return "Amount{" +

"total='" + total + '\'' +

", currency='" + currency + '\'' +

", details=" + details +

'}';

}

}

public static class Details {

private String subtotal;

public String getSubtotal() {

return subtotal;

}

public void setSubtotal(String subtotal) {

this.subtotal = subtotal;

}

@Override

public String toString() {

return "Details{" +

"subtotal='" + subtotal + '\'' +

'}';

}

}

public static class Link {

private String links;

private String rel;

private String method;

public String getLinks() {

return links;

}

public void setLinks(String links) {

this.links = links;

}

public String getRel() {

return rel;

}

public void setRel(String rel) {

this.rel = rel;

}

public String getMethod() {

return method;

}

public void setMethod(String method) {

this.method = method;

}

@Override

public String toString() {

return "Link{" +

"links='" + links + '\'' +

", rel='" + rel + '\'' +

", method='" + method + '\'' +

'}';

}

}

public static class Payer {

private String paymentMethod;

private String status;

private PayerInfo payerInfo;

public String getPaymentMethod() {

return paymentMethod;

}

public void setPaymentMethod(String paymentMethod) {

this.paymentMethod = paymentMethod;

}

public String getStatus() {

return status;

}

public void setStatus(String status) {

this.status = status;

}

public PayerInfo getPayerInfo() {

return payerInfo;

}

public void setPayerInfo(PayerInfo payerInfo) {

this.payerInfo = payerInfo;

}

@Override

public String toString() {

return "Payer{" +

"paymentMethod='" + paymentMethod + '\'' +

", status='" + status + '\'' +

", payerInfo=" + payerInfo +

'}';

}

}

public static class PayerInfo {

private String email;

private String firstName;

private String lastName;

private String payerId;

private ShippingAddress shippingAddress;

private String phone;

private String countryCode;

public String getEmail() {

return email;

}

public void setEmail(String email) {

this.email = email;

}

public String getFirstName() {

return firstName;

}

public void setFirstName(String firstName) {

this.firstName = firstName;

}

public String getLastName() {

return lastName;

}

public void setLastName(String lastName) {

this.lastName = lastName;

}

public String getPayerId() {

return payerId;

}

public void setPayerId(String payerId) {

this.payerId = payerId;

}

public ShippingAddress getShippingAddress() {

return shippingAddress;

}

public void setShippingAddress(ShippingAddress shippingAddress) {

this.shippingAddress = shippingAddress;

}

public String getPhone() {

return phone;

}

public void setPhone(String phone) {

this.phone = phone;

}

public String getCountryCode() {

return countryCode;

}

public void setCountryCode(String countryCode) {

this.countryCode = countryCode;

}

@Override

public String toString() {

return "PayerInfo{" +

"email='" + email + '\'' +

", firstName='" + firstName + '\'' +

", lastName='" + lastName + '\'' +

", payerId='" + payerId + '\'' +

", shippingAddress=" + shippingAddress +

", phone='" + phone + '\'' +

", countryCode='" + countryCode + '\'' +

'}';

}

}

public static class ShippingAddress {

private String recipientName;

public String getRecipientName() {

return recipientName;

}

public void setRecipientName(String recipientName) {

this.recipientName = recipientName;

}

@Override

public String toString() {

return "ShippingAddress{" +

"recipientName='" + recipientName + '\'' +

'}';

}

}

public static class ResponseToken {

private String scope;

private String nonce;

private String accessToken;

private String tokenType;

private String appId;

private int expiresIn;

public String getScope() {

return scope;

}

public void setScope(String scope) {

this.scope = scope;

}

public String getNonce() {

return nonce;

}

public void setNonce(String nonce) {

this.nonce = nonce;

}

public String getAccessToken() {

return accessToken;

}

public void setAccessToken(String accessToken) {

this.accessToken = accessToken;

}

public String getTokenType() {

return tokenType;

}

public void setTokenType(String tokenType) {

this.tokenType = tokenType;

}

public String getAppId() {

return appId;

}

public void setAppId(String appId) {

this.appId = appId;

}

public int getExpiresIn() {

return expiresIn;

}

public void setExpiresIn(int expiresIn) {

this.expiresIn = expiresIn;

}

@Override

public String toString() {

return "ResponseToken{" +

"scope='" + scope + '\'' +

", nonce='" + nonce + '\'' +

", accessToken='" + accessToken + '\'' +

", tokenType='" + tokenType + '\'' +

", appId='" + appId + '\'' +

", expiresIn=" + expiresIn +

'}';

}

}

}

最后是工具类PayPalUtils的使用方法,主要分2种,一种是直接判断是否支付成功的isSuccess(),一种是获取客户端生成的订单号(可能包含产品信息等)getOrderNumber(),两者都是传入一个参数,即客户端上传的paymentId,当然也可以根据自己的喜好改动,里边的getResponsePayPayl()方法可以获取返回的所有信息。楼主使用的是getOrderNumber(),另外为了给paypal足够的处理时间,建议如果一次获取不到订单号或者判断支付失败的可进行多次间隔校验。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值