如何使用 PayPal 的 SDK(Java 或 JavaScript)实现两步或更少步完成订单?

Posted

技术标签:

【中文标题】如何使用 PayPal 的 SDK(Java 或 JavaScript)实现两步或更少步完成订单?【英文标题】:How to use PayPal's SDK(Java or JavaScript) to achieve Allow for Order Completion in Two or Fewer Steps? 【发布时间】:2019-11-19 21:45:43 【问题描述】:

我想实现这个功能:

贝宝结账

允许在两个或更少的步骤中完成订单

quick-order-completion

我试过了:

1.1Set up a Transaction

1.2Capture Transaction Funds

2.1Set up an Authorization Transaction

2.2Create an Authorization

2.3Capture an Authorization

但都是直接付款!

@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;
    


我想要:

    登录贝宝

    选择送货地址

    返回我的网站并返回用户的收货地址

    根据送货地址计算运费

    更新付款金额

    支付

【问题讨论】:

【参考方案1】:

我找到了:https://www.paypalobjects.com/webstatic/en_HK/developer/docs/pdf/hostedsolution_hk.pdf

使用NVP/SOAP Express Checkout

【讨论】:

【参考方案2】:

上一张图片失败,再次发送。

【讨论】:

【参考方案3】:

使用本文档中的方法(Show a Confirmation Page)来实现。 https://developer.paypal.com/docs/checkout/integration-features/confirmation-page/

【讨论】:

以上是关于如何使用 PayPal 的 SDK(Java 或 JavaScript)实现两步或更少步完成订单?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 android 中实现 Paypal Native Checkout SDK?

如何通过 REST SDK 获取已执行 PayPal 付款的销售 ID

如何包含或引导 paypal-core-sdk php

使用 PayPal REST SDK 和 PayPal-Python-SDK 时未发送或接收资金

使用 Paypal API / SDK,我将如何检查某个订阅 ID? C#

无需 PayPal 帐户或信用卡的 PayPal Android SDK 付款