Я хочу реализовать эту функцию:
PayPal Checkout
Разрешить выполнение заказа в два или менее шагов
быстрый заказ-завершение
Я пытался:
1.1 Настройка транзакции
1,2 Средства для захвата транзакций
2.1 Настройка транзакции авторизации
2.2 Создать авторизацию
2.3 Получение разрешения
Но все это прямые платежи!
@Service
public class AuthorizationService {
@Autowired
private PayPalClient payPalClient;
//2. Set up your server to receive a call from the client
/**
*Method to create order
*
*@param debug true = print response data
*@return HttpResponse<Order> response received from API
*@throws IOException Exceptions from API if any
*/
public com.alibaba.fastjson.JSONObject createOrder(boolean debug) throws IOException {
OrdersCreateRequest request = new OrdersCreateRequest();
request.prefer("return=representation");
request.requestBody(buildCreateOrderRequestBody());
//3. Call PayPal to set up the transaction
HttpResponse<Order> response = payPalClient.client().execute(request);
if (debug) {
if (response.statusCode() == 201) {
System.out.println("Status Code: " + response.statusCode());
System.out.println("Status: " + response.result().status());
System.out.println("Order ID: " + response.result().id());
System.out.println("Intent: " + response.result().intent());
System.out.println("Links: ");
for (LinkDescription link : response.result().links()) {
System.out.println("\t" + link.rel() + ": " + link.href() + "\tCall Type: " + link.method());
}
System.out.println("Total Amount: " + response.result().purchaseUnits().get(0).amount().currencyCode()
+ " " + response.result().purchaseUnits().get(0).amount().value());
}
}
Order order = response.result();
JSONObject json = new JSONObject(new Json().serialize(order));
com.alibaba.fastjson.JSONObject result = com.alibaba.fastjson.JSONObject.parseObject(json.toString(4));
return result;
}
/**
*Method to generate sample create order body with AUTHORIZE intent
*
*@return OrderRequest with created order request
*/
private OrderRequest buildCreateOrderRequestBody() {
OrderRequest orderRequest = new OrderRequest();
orderRequest.intent("AUTHORIZE");
ApplicationContext applicationContext = new ApplicationContext().brandName("EXAMPLE INC").landingPage("BILLING")
.shippingPreference("SET_PROVIDED_ADDRESS");
orderRequest.applicationContext(applicationContext);
List<PurchaseUnitRequest> purchaseUnitRequests = new ArrayList<PurchaseUnitRequest>();
PurchaseUnitRequest purchaseUnitRequest = new PurchaseUnitRequest().referenceId("PUHF")
.description("Sporting Goods").customId("CUST-HighFashions").softDescriptor("HighFashions")
.amount(new AmountWithBreakdown().currencyCode("USD").value("230.00")
.breakdown(new AmountBreakdown().itemTotal(new Money().currencyCode("USD").value("180.00"))
.shipping(new Money().currencyCode("USD").value("30.00"))
.handling(new Money().currencyCode("USD").value("10.00"))
.taxTotal(new Money().currencyCode("USD").value("20.00"))
.shippingDiscount(new Money().currencyCode("USD").value("10.00"))))
.items(new ArrayList<Item>() {
{
add(new Item().name("T-shirt").description("Green XL").sku("sku01")
.unitAmount(new Money().currencyCode("USD").value("90.00"))
.tax(new Money().currencyCode("USD").value("10.00")).quantity("1")
.category("PHYSICAL_GOODS"));
add(new Item().name("Shoes").description("Running, Size 10.5").sku("sku02")
.unitAmount(new Money().currencyCode("USD").value("45.00"))
.tax(new Money().currencyCode("USD").value("5.00")).quantity("2")
.category("PHYSICAL_GOODS"));
}
})
.shipping(new ShippingDetails().name(new Name().fullName("John Doe"))
.addressPortable(new AddressPortable().addressLine1("123 Townsend St").addressLine2("Floor 6")
.adminArea2("San Francisco").adminArea1("CA").postalCode("94107").countryCode("US")));
purchaseUnitRequests.add(purchaseUnitRequest);
orderRequest.purchaseUnits(purchaseUnitRequests);
return orderRequest;
}
//2. Set up your server to receive a call from the client
/**
*Method to authorize order after creation
*
*@param orderId Valid Approved Order ID from createOrder response
*@param debug true = print response data
*@return HttpResponse<Order> response received from API
*@throws IOException Exceptions from API if any
*/
public com.alibaba.fastjson.JSONObject authorizeOrder(String orderId, boolean debug) throws IOException {
OrdersAuthorizeRequest request = new OrdersAuthorizeRequest(orderId);
request.requestBody(buildAuthorizeOrderRequestBody());
// 3. Call PayPal to authorization an order
HttpResponse<Order> response = payPalClient.client().execute(request);
// 4. Save the authorization ID to your database. Implement logic to save the authorization to your database for future reference.
if (debug) {
System.out.println("Authorization Ids:");
response.result().purchaseUnits()
.forEach(purchaseUnit -> purchaseUnit.payments()
.authorizations().stream()
.map(authorization -> authorization.id())
.forEach(System.out::println));
System.out.println("Link Descriptions: ");
for (LinkDescription link : response.result().links()) {
System.out.println("\t" + link.rel() + ": " + link.href());
}
System.out.println("Full response body:");
System.out.println(new JSONObject(new Json().serialize(response.result())).toString(4));
}
Order order = response.result();
JSONObject json = new JSONObject(new Json().serialize(order));
com.alibaba.fastjson.JSONObject result = com.alibaba.fastjson.JSONObject.parseObject(json.toString(4));
return result;
}
/**
*Building empty request body.
*
*@return OrderActionRequest with empty body
*/
private OrderActionRequest buildAuthorizeOrderRequestBody() {
return new OrderActionRequest();
}
//2. Set up your server to receive a call from the client
/**
* Method to patch order
*
* @throws IOException Exceptions from API, if any
*/
public com.alibaba.fastjson.JSONObject patchOrder(String orderId) throws IOException {
OrdersPatchRequest request = new OrdersPatchRequest(orderId);
request.requestBody(buildRequestBody());
payPalClient.client().execute(request);
OrdersGetRequest getRequest = new OrdersGetRequest(orderId);
//3. Call PayPal to patch the transaction
HttpResponse<Order> response = payPalClient.client().execute(getRequest);
System.out.println("After Patch:");
System.out.println("Order ID: " + response.result().id());
System.out.println("Intent: " + response.result().intent());
System.out.println("Links: ");
for (LinkDescription link : response.result().links()) {
System.out.println("\t" + link.rel() + ": " + link.href() + "\tCall Type: " + link.method());
}
System.out.println("Gross Amount: " + response.result().purchaseUnits().get(0).amount().currencyCode() + " "
+ response.result().purchaseUnits().get(0).amount().value());
System.out.println("Full response body:");
System.out.println(new JSONObject(new Json().serialize(response.result())).toString(4));
Order order = response.result();
JSONObject json = new JSONObject(new Json().serialize(order));
com.alibaba.fastjson.JSONObject result = com.alibaba.fastjson.JSONObject.parseObject(json.toString(4));
return result;
}
/**
* Method to create body for patching the order.
*
* @return List<Patch> list of patches to be made
* @throws IOException
*/
private List<Patch> buildRequestBody() throws IOException {
List<Patch> patches = new ArrayList<>();
// patches.add(new Patch().op("replace").path("/intent").value("CAPTURE"));
patches.add(new Patch().op("replace").path("/purchase_units/@reference_id=='PUHF'/amount")
.value(new AmountWithBreakdown().currencyCode("USD").value("250.00")
.breakdown(new AmountBreakdown().itemTotal(new Money().currencyCode("USD").value("180.00"))
.shipping(new Money().currencyCode("USD").value("50.00"))
.handling(new Money().currencyCode("USD").value("10.00"))
.taxTotal(new Money().currencyCode("USD").value("20.00"))
.shippingDiscount(new Money().currencyCode("USD").value("10.00")))));
return patches;
}
}
Я хочу:
Логин PayPal
Выберите адрес доставки
Вернуться на мой веб-сайт и вернуть адрес доставки пользователя
Рассчитать стоимость доставки на основе адреса доставки
Обновить сумму платежа
Оплата