授权和捕获PayPal订单

发布于 2025-01-27 06:46:44 字数 7489 浏览 1 评论 0原文

我正在尝试将PayPal Checkout SDK集成到我的应用程序中。

我创建这样的请求:

    protected int doPaypalOrderWithCustomer(PayPalPurchase purchase, Customer customer) throws PayPalException {
        PayPalClient client = new PayPalClient();
        // Creating an order
        HttpResponse<Order> orderResponse = null;
        try{
            orderResponse = client.createCustomerOrder("Order", purchase.getTotalCheckoutCost(), 1, customer);
            String orderId = "";
            log.info("Creating Order...");
            if(orderResponse.statusCode() == 201){
                orderId = orderResponse.result().id();
                log.info("Order ID: " + orderId);
                log.info("Links:");
                for(LinkDescription link : orderResponse.result().links()){
                    log.info(link.rel() + ": " + link.href());
                    if("approve".equalsIgnoreCase(link.rel())){
                        log.info("Request Approved");
                        ServletActionContext.getResponse().sendRedirect(link.href());
                        break;
                    }// end if
                }// end for
            }// end if
            log.info("Created Successfully");
        }catch(Exception e){
            throw new PayPalException("Creating a PayPal order failed. Message is: " + e.getMessage(), e);
        }finally{
            if(null != orderResponse){
                log.info("Order response status code is: " + String.valueOf(orderResponse.statusCode()));
            }else{
                log.info("Order response is null.");
            }// end if/else
        }// end try/catch/finally
        return orderResponse.statusCode();
    }// end doPaypalOrderWithCustomer
       

第二种方法是:

    public HttpResponse<Order> createCustomerOrder(String desc, double cost, int quantity, Customer customer) throws Exception {
        log.debug("Entering createCustomerOrder");
        if(log.isDebugEnabled()){
            log.debug("Method to create order with complete payload");
            log.debug("Entry parameters are: desc=" + String.valueOf(desc) + ", cost=" + String.valueOf(cost) + ", quantity=" + String.valueOf(quantity) + ", Customer=" + String.valueOf(customer));
        }// end if
        double individualCost = cost / quantity;
        NumberFormat format = NumberFormat.getNumberInstance();
        format.setMaximumFractionDigits(2);
        format.setMinimumFractionDigits(2);
        OrdersCreateRequest request = new OrdersCreateRequest();
        request.header("prefer", "return=representation");
        OrderRequest orderRequest = new OrderRequest();
        orderRequest.checkoutPaymentIntent("CAPTURE");
        Payer payer = new Payer();
        payer.email(customer.getEmail());
        PhoneWithType phoneWithType = new PhoneWithType();
        Phone phone = new Phone();
        String phoneNumber = customer.getPhoneNo().replace("(", "");
        phoneNumber = customer.getPhoneNo().replace(")", "");
        phoneNumber = customer.getPhoneNo().replace("-", "");
        phoneNumber = phoneNumber.replaceAll("\\D+", "");
        phone.nationalNumber(phoneNumber);
        phoneWithType.phoneNumber(phone);
        payer.phoneWithType(phoneWithType);
        orderRequest.payer(payer);
        ApplicationContext applicationContext = new ApplicationContext() //
                .brandName("LLC")//
                .landingPage("BILLING")//
                .cancelUrl(bundle.getString("RESPONSE_URL") + "?t=c")//
                .returnUrl(bundle.getString("RESPONSE_URL") + "?t=r")//
                .userAction("PAY_NOW").shippingPreference("NO_SHIPPING");
        log.info("Method call to orderRequest.applicationContext(applicationContext)");
        orderRequest.applicationContext(applicationContext);
        List<PurchaseUnitRequest> purchaseUnitRequests = new ArrayList<>();
        PurchaseUnitRequest purchaseUnitRequest = new PurchaseUnitRequest()//
                .referenceId("PUHF")//
                .description("Digital Content")//
                .customId("CUST-DigitalContent")//
                .softDescriptor("DigitalContent")//
                .amountWithBreakdown(new AmountWithBreakdown()//
                        .currencyCode("USD")//
                        .value(format.format(cost))//
                        .amountBreakdown(new AmountBreakdown()//
                                .itemTotal(new Money()//
                                        .currencyCode("USD")//
                                        .value(format.format(cost)))//
                                .shipping(new Money()//
                                        .currencyCode("USD")//
                                        .value("0.00"))//
                                .handling(new Money()//
                                        .currencyCode("USD")//
                                        .value("0.00"))//
                                .taxTotal(new Money()//
                                        .currencyCode("USD")//
                                        .value("0.00"))//
                                .shippingDiscount(new Money()//
                                        .currencyCode("USD")//
                                        .value("0.00"))))
                .items(new ArrayList<Item>(){
                    private static final long serialVersionUID = 1L;
                    {
                        add(new Item()//
                                .name(desc)//
                                .description(desc)//
                                .sku("sku01").//
                        unitAmount(new Money()//
                                .currencyCode("USD")//
                                .value(format.format(individualCost)))//
                                .tax(new Money()//
                                        .currencyCode("USD")//
                                        .value("0.00"))//
                                .quantity(String.valueOf(quantity))//
                                .category("DIGITAL_GOODS"));
                    }
                });
        purchaseUnitRequests.add(purchaseUnitRequest);
        orderRequest.purchaseUnits(purchaseUnitRequests);
        request.requestBody(orderRequest);
        HttpResponse<Order> response = client().execute(request);
        if(response.statusCode() == 201){
            for(com.paypal.orders.LinkDescription link : response.result().links()){
                log.info(link.rel() + ": " + link.href() + "; Call Type: " + link.method());
            }// end for
            log.info("Total Amount: " + response.result().purchaseUnits().get(0).amountWithBreakdown().currencyCode() + " " + response.result().purchaseUnits().get(0).amountWithBreakdown().value());
            log.info(new JSONObject(new Json().serialize(response.result())).toString(4));
        }// end if
        if(log.isDebugEnabled()){
            log.debug("Return value is: response=" + String.valueOf(response));
        }// end if
        log.debug("Exiting createCustomerOrder");
        return response;
    }// end createCustomerOrder

使用我转发到PayPal的沙箱。我遵循付款的步骤。我知道我必须捕获该订单,但我不知道如何。从PayPal重定向时,我将购买保存到数据库。问题是PayPal正在转发到我的网站,就像付款一样。实际上,贝宝(Paypal)没有任何表示付款的内容。

我目前正在使用Checkout.jar

不使用JavaScript的方法来执行此操作?我不想完成该应用程序的重组。

I am trying to integrate PayPal Checkout SDK into my application.

I create the request like this:

    protected int doPaypalOrderWithCustomer(PayPalPurchase purchase, Customer customer) throws PayPalException {
        PayPalClient client = new PayPalClient();
        // Creating an order
        HttpResponse<Order> orderResponse = null;
        try{
            orderResponse = client.createCustomerOrder("Order", purchase.getTotalCheckoutCost(), 1, customer);
            String orderId = "";
            log.info("Creating Order...");
            if(orderResponse.statusCode() == 201){
                orderId = orderResponse.result().id();
                log.info("Order ID: " + orderId);
                log.info("Links:");
                for(LinkDescription link : orderResponse.result().links()){
                    log.info(link.rel() + ": " + link.href());
                    if("approve".equalsIgnoreCase(link.rel())){
                        log.info("Request Approved");
                        ServletActionContext.getResponse().sendRedirect(link.href());
                        break;
                    }// end if
                }// end for
            }// end if
            log.info("Created Successfully");
        }catch(Exception e){
            throw new PayPalException("Creating a PayPal order failed. Message is: " + e.getMessage(), e);
        }finally{
            if(null != orderResponse){
                log.info("Order response status code is: " + String.valueOf(orderResponse.statusCode()));
            }else{
                log.info("Order response is null.");
            }// end if/else
        }// end try/catch/finally
        return orderResponse.statusCode();
    }// end doPaypalOrderWithCustomer
       

The second method is:

    public HttpResponse<Order> createCustomerOrder(String desc, double cost, int quantity, Customer customer) throws Exception {
        log.debug("Entering createCustomerOrder");
        if(log.isDebugEnabled()){
            log.debug("Method to create order with complete payload");
            log.debug("Entry parameters are: desc=" + String.valueOf(desc) + ", cost=" + String.valueOf(cost) + ", quantity=" + String.valueOf(quantity) + ", Customer=" + String.valueOf(customer));
        }// end if
        double individualCost = cost / quantity;
        NumberFormat format = NumberFormat.getNumberInstance();
        format.setMaximumFractionDigits(2);
        format.setMinimumFractionDigits(2);
        OrdersCreateRequest request = new OrdersCreateRequest();
        request.header("prefer", "return=representation");
        OrderRequest orderRequest = new OrderRequest();
        orderRequest.checkoutPaymentIntent("CAPTURE");
        Payer payer = new Payer();
        payer.email(customer.getEmail());
        PhoneWithType phoneWithType = new PhoneWithType();
        Phone phone = new Phone();
        String phoneNumber = customer.getPhoneNo().replace("(", "");
        phoneNumber = customer.getPhoneNo().replace(")", "");
        phoneNumber = customer.getPhoneNo().replace("-", "");
        phoneNumber = phoneNumber.replaceAll("\\D+", "");
        phone.nationalNumber(phoneNumber);
        phoneWithType.phoneNumber(phone);
        payer.phoneWithType(phoneWithType);
        orderRequest.payer(payer);
        ApplicationContext applicationContext = new ApplicationContext() //
                .brandName("LLC")//
                .landingPage("BILLING")//
                .cancelUrl(bundle.getString("RESPONSE_URL") + "?t=c")//
                .returnUrl(bundle.getString("RESPONSE_URL") + "?t=r")//
                .userAction("PAY_NOW").shippingPreference("NO_SHIPPING");
        log.info("Method call to orderRequest.applicationContext(applicationContext)");
        orderRequest.applicationContext(applicationContext);
        List<PurchaseUnitRequest> purchaseUnitRequests = new ArrayList<>();
        PurchaseUnitRequest purchaseUnitRequest = new PurchaseUnitRequest()//
                .referenceId("PUHF")//
                .description("Digital Content")//
                .customId("CUST-DigitalContent")//
                .softDescriptor("DigitalContent")//
                .amountWithBreakdown(new AmountWithBreakdown()//
                        .currencyCode("USD")//
                        .value(format.format(cost))//
                        .amountBreakdown(new AmountBreakdown()//
                                .itemTotal(new Money()//
                                        .currencyCode("USD")//
                                        .value(format.format(cost)))//
                                .shipping(new Money()//
                                        .currencyCode("USD")//
                                        .value("0.00"))//
                                .handling(new Money()//
                                        .currencyCode("USD")//
                                        .value("0.00"))//
                                .taxTotal(new Money()//
                                        .currencyCode("USD")//
                                        .value("0.00"))//
                                .shippingDiscount(new Money()//
                                        .currencyCode("USD")//
                                        .value("0.00"))))
                .items(new ArrayList<Item>(){
                    private static final long serialVersionUID = 1L;
                    {
                        add(new Item()//
                                .name(desc)//
                                .description(desc)//
                                .sku("sku01").//
                        unitAmount(new Money()//
                                .currencyCode("USD")//
                                .value(format.format(individualCost)))//
                                .tax(new Money()//
                                        .currencyCode("USD")//
                                        .value("0.00"))//
                                .quantity(String.valueOf(quantity))//
                                .category("DIGITAL_GOODS"));
                    }
                });
        purchaseUnitRequests.add(purchaseUnitRequest);
        orderRequest.purchaseUnits(purchaseUnitRequests);
        request.requestBody(orderRequest);
        HttpResponse<Order> response = client().execute(request);
        if(response.statusCode() == 201){
            for(com.paypal.orders.LinkDescription link : response.result().links()){
                log.info(link.rel() + ": " + link.href() + "; Call Type: " + link.method());
            }// end for
            log.info("Total Amount: " + response.result().purchaseUnits().get(0).amountWithBreakdown().currencyCode() + " " + response.result().purchaseUnits().get(0).amountWithBreakdown().value());
            log.info(new JSONObject(new Json().serialize(response.result())).toString(4));
        }// end if
        if(log.isDebugEnabled()){
            log.debug("Return value is: response=" + String.valueOf(response));
        }// end if
        log.debug("Exiting createCustomerOrder");
        return response;
    }// end createCustomerOrder

Using the sandbox I am forwarded to PayPal. I follow the steps to PAY for the purchase. I know I have to CAPTURE the order but I can't figure out how. Upon redirect from PAYPAL I am saving the purchase to the database. The problem is PAYPAL is forwarding to my site like the payment was made. When in fact there is nothing in PAYPAL indicating a payment.

I am currently using the checkout.jar

Is there a way to do this without using javascript? I don't want to have to complete restructure the application.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

雪落纷纷 2025-02-03 06:46:44

付款未在PayPal完成。对于重定向集成,返回您的网站后,您需要捕获订单并显示结果(成功/谢谢您,或者失败/重试)。 URL将包含用于捕获的必要ID。


当前集成不使用任何重定向。根本。 (API响应使用这样的集成模式对旧网站的RETRITRECT URL)

改为,分别在服务器上为创建订单和捕获订单API创建两个路由。捕获路由必须将ID作为输入(路径或身体参数),因此它知道要捕获哪个。这两种路线应仅返回/输出JSON数据,没有HTML或文本。

将这两条路线与以下批准流相结合: https:https://developervevelaper.paypal.paypal。 com/demo/beckout/#/tatter/server

The payment does not complete at PayPal. For redirect integrations, after the return to your site you need to capture the order and show the result (success/thank you, or failure/try again). The URL will contain the necessary IDs for capture.


Current integrations don't use any redirects. At all. (API responses have redirect URLs for old websites using such an integration pattern)

Instead, create two routes on your server for the create order and capture order APIs, respectively. The capture route must take an id as input (path or body parameter), so it knows which to capture. Both routes should return/output only JSON data, no HTML or text.

Pair those two routes with the following approval flow: https://developer.paypal.com/demo/checkout/#/pattern/server

一笔一画续写前缘 2025-02-03 06:46:44

经过数周的反复试验,我终于获得了JS免费的PayPal实施。
完成PayPal交易所需的3个步骤。

步骤1。创建顺序。此步骤将将客户带到PayPal网站。

类变量:私有PayPalclient客户端= new PayPalclient();私有paypalhttpclient hclient = new PaypalHttpClient(client.getEnvironment());

protected int doPaypalOrderWithCustomer(PayPalPurchase purchase, Customer customer) throws PayPalException {
    log.info("ENVIRONMENT: " + String.valueOf(client.getEnvironment()));
    orderResponse = null;
    try{
        orderId = "";
        // Creating an order payload
        OrdersCreateRequest request = new OrdersCreateRequest();
        // Build PayPal Request Body
        request = client.createCustomerOrder("Company Order", purchase.getTotalCheckoutCost(), 1, customer);
        // Create Order
        orderResponse = hClient.execute(request);
        log.info("Creating Order...");
        if(orderResponse.statusCode() == 201){
        log.info("Order with Complete Payload: ");
        log.info("Status Code: " + orderResponse.statusCode());
        log.info("Status: " + orderResponse.result().status());
        log.info("Order ID: " + orderResponse.result().id());
        log.info("Intent: " + orderResponse.result().checkoutPaymentIntent());
        log.info("Links: ");
        for(LinkDescription link : orderResponse.result().links()){
            log.info("\t" + link.rel() + ": " + link.href() + "\tCall Type: " + link.method());
        }// end for
        log.info("Total Amount: " + orderResponse.result().purchaseUnits().get(0).amountWithBreakdown().currencyCode() + " " + orderResponse.result().purchaseUnits().get(0).amountWithBreakdown().value());
        log.info("Full response body:");
        log.info("Authorized Successfully\n");
        orderId = orderResponse.result().id();
        log.info("PURCHASE UNIT ORDER ID: " + orderId);
        for(LinkDescription link : orderResponse.result().links()){
            String check = link.rel();
            log.info(link.rel() + ": " + link.href());
            if(check.equalsIgnoreCase("approve")){
            log.info("Request Approved");
            ServletActionContext.getResponse().sendRedirect(link.href());
            break;
            }else{
            log.info("CURRENT LINK: " + link.rel() + " NOT APPROVED");
            }// end if
        }// end for
        sessionMap.put("orderId", orderId);
        }// end if
        log.info("Created Successfully");
    }catch(Exception e){
        throw new PayPalException("Creating a PayPal order failed. Message is: " + e.getMessage(), e);
    }finally{
        if(null != orderResponse){
        log.info("Order response status code is: " + String.valueOf(orderResponse.statusCode()));
        }else{
        log.info("Order response is null.");
        }// end if/else
    }// end try/catch/finally

    return orderResponse.statusCode();
}// end doPaypalOrderWithCustomer

public OrdersCreateRequest createCustomerOrder(String desc, double cost, int quantity, Customer customer) throws Exception {
        log.debug("Entering createCustomerOrder");
        if(log.isDebugEnabled()){
            log.debug("Method to create order with complete payload");
            log.debug("Entry parameters are: desc=" + String.valueOf(desc) + ", cost=" + String.valueOf(cost) + ", quantity=" + String.valueOf(quantity) + ", Customer=" + String.valueOf(customer));
        }// end if
        double individualCost = cost / quantity;
        NumberFormat format = NumberFormat.getNumberInstance();
        format.setMaximumFractionDigits(2);
        format.setMinimumFractionDigits(2);
        OrdersCreateRequest request = new OrdersCreateRequest();
        request.header("prefer", "return=representation");
        OrderRequest orderRequest = new OrderRequest();
        orderRequest.checkoutPaymentIntent("AUTHORIZE");// This must be AUTHORIZE for the 3 step process
        Payer payer = new Payer();
        payer.email(customer.getEmail());
        PhoneWithType phoneWithType = new PhoneWithType();
        Phone phone = new Phone();
        String phoneNumber = customer.getPhoneNo().replace("(", "");
        phoneNumber = customer.getPhoneNo().replace(")", "");
        phoneNumber = customer.getPhoneNo().replace("-", "");
        phoneNumber = phoneNumber.replaceAll("\\D+", "");
        phone.nationalNumber(phoneNumber);
        phoneWithType.phoneNumber(phone);
        payer.phoneWithType(phoneWithType);
        orderRequest.payer(payer);
        ApplicationContext applicationContext = new ApplicationContext() //
                .brandName("Company, LLC")//
                .landingPage("BILLING")//
                .cancelUrl(bundle.getString("RESPONSE_URL") + "?t=c")//
                .returnUrl(bundle.getString("RESPONSE_URL") + "?t=r")//
                .userAction("CONTINUE").shippingPreference("NO_SHIPPING");
        orderRequest.applicationContext(applicationContext);
        List<PurchaseUnitRequest> purchaseUnitRequests = new ArrayList<>();
        PurchaseUnitRequest purchaseUnitRequest = new PurchaseUnitRequest()//
                .referenceId("PUHF")//
                .description("Digital Content")//
                .customId("CUST-DigitalContent")//
                .softDescriptor("DigitalContent")//
                .amountWithBreakdown(new AmountWithBreakdown()//
                        .currencyCode("USD")//
                        .value(format.format(cost))//
                        .amountBreakdown(new AmountBreakdown()//
                                .itemTotal(new Money()//
                                        .currencyCode("USD")//
                                        .value(format.format(cost)))//
                                .shipping(new Money()//
                                        .currencyCode("USD")//
                                        .value("0.00"))//
                                .handling(new Money()//
                                        .currencyCode("USD")//
                                        .value("0.00"))//
                                .taxTotal(new Money()//
                                        .currencyCode("USD")//
                                        .value("0.00"))//
                                .shippingDiscount(new Money()//
                                        .currencyCode("USD")//
                                        .value("0.00"))))
                .items(new ArrayList<Item>(){
                    private static final long serialVersionUID = 1L;
                    {
                        add(new Item()//
                                .name(desc)//
                                .description(desc)//
                                .sku("sku01").//
                        unitAmount(new Money()//
                                .currencyCode("USD")//
                                .value(format.format(individualCost)))//
                                .tax(new Money()//
                                        .currencyCode("USD")//
                                        .value("0.00"))//
                                .quantity(String.valueOf(quantity))//
                                .category("DIGITAL_GOODS"));
                    }
                }).shippingDetail(new ShippingDetail()//
                        .name(new Name()//
                                .fullName(customer.getFirstNm() + " " + customer.getLastNm()))//
                        .addressPortable(new AddressPortable()//
                                .addressLine1(customer.getAddress())//
                                .addressLine2(customer.getAddress2())//
                                .adminArea1(customer.getState())//
                                .adminArea2(customer.getCity())//
                                .postalCode(customer.getZipCode())//
                                .countryCode("US")));
        purchaseUnitRequests.add(purchaseUnitRequest);
        orderRequest.purchaseUnits(purchaseUnitRequests);
        request.requestBody(orderRequest);
        HttpResponse<Order> response = client().execute(request);
        if(response.statusCode() == 201){
            for(com.paypal.orders.LinkDescription link : response.result().links()){
                log.info(link.rel() + ": " + link.href() + "; Call Type: " + link.method());
            }// end for
            log.info("Total Amount: " + response.result().purchaseUnits().get(0).amountWithBreakdown().currencyCode() + " " + response.result().purchaseUnits().get(0).amountWithBreakdown().value());
            log.info(new JSONObject(new Json().serialize(response.result())).toString(4));
        }// end if
        if(log.isDebugEnabled()){
            log.debug("Return value is: response=" + String.valueOf(request));
        }// end if
        log.debug("Exiting createCustomerOrder");
        return request;
    }// end createCustomerOrder

步骤2:我们批准订单并从PayPal获得授权订单ID。

public String approve() throws Exception {
        log.debug("Entering approve method.");
        log.trace("This method is used to approce purchases Post PayPal redirect.");
        log.info("Authorizing Order...");
        HttpServletRequest request = ServletActionContext.getRequest();
        String cancel = request.getParameter("t");
        log.info("Parameter being returned from PayPal: " + String.valueOf(cancel));
        if(cancel.equalsIgnoreCase("c")){
            payPalCancel = true;
            if(null != sessionMap.get("purchase")){
                sessionMap.remove("purchase");
            }// end if
            if(null != sessionMap.get("cartCount")){
                sessionMap.put("cartCount", 0);
            }// end if
            setCartCount(0);
            if(null != sessionMap.get("images")){
                sessionMap.remove("images");
            }// end if
            setPayPalCancel(true);
            return INPUT;
        }else{
            if(null != sessionMap.get("orderId")){
                orderId = (String) sessionMap.get("orderId");
            }// end if
            log.info("Order ID: " + String.valueOf(orderId));
            OrdersAuthorizeRequest orderAuthorizeRequest = new OrdersAuthorizeRequest(orderId);
            orderAuthorizeRequest.requestBody(new OrderRequest());
            orderResponse = hClient.execute(orderAuthorizeRequest);
            if(orderResponse.statusCode() == 201){
                authOrderId = orderResponse.result().purchaseUnits().get(0).payments().authorizations().get(0).id();
                log.info("AUTHORIZED ORDER ID: " + authOrderId);
            }// end if
            sessionMap.put("authOrderId", authOrderId);
            log.debug("Exiting approve");
        }// end if/else
        return SUCCESS;
}// end approve

步骤3:作为开发人员,我们必须捕获该批准的订单。这是最后一步。

public String capture() throws Exception {
    log.debug("Entering capture method.");
    log.trace("This method is used to save capture Payment.");
    // Capturing authorized order
    if(null != sessionMap.get("authOrderId")){
        authOrderId = (String) sessionMap.get("authOrderId");
    }// end if
    log.info("Authorized Order ID: " + String.valueOf(authOrderId));
    log.info("Capturing Order...");
    setCaptured(true);
    HttpResponse<Capture> captureOrderResponse = new CaptureOrder().captureOrder(authOrderId, true);
    if(captureOrderResponse.statusCode() == 201){
        log.info("Captured Successfully");
        log.info("Status Code: " + captureOrderResponse.statusCode());
        log.info("Status: " + captureOrderResponse.result().status());
        log.info("Capture ID: " + captureOrderResponse.result().id());
        log.info("Links: ");
        for(com.paypal.payments.LinkDescription link : captureOrderResponse.result().links()){
        log.info("\t" + link.rel() + ": " + link.href() + "\tCall Type: " + link.method());
        }// end for
    }// end if
    log.debug("Exiting capture");
    return SUCCESS;
}// end capture

感谢所有帮助的人。我是新手,可能做错了,但我终于能够使它工作。

After several weeks of trial and error, I finally got the js free PayPal implementation working.
There are 3 steps necessary to complete a PayPal Transaction.

Step 1. Create The Order. This step will take the customer to the PayPal site.

Class Variables: private PayPalClient client = new PayPalClient(); private PayPalHttpClient hClient = new PayPalHttpClient(client.getEnvironment());

protected int doPaypalOrderWithCustomer(PayPalPurchase purchase, Customer customer) throws PayPalException {
    log.info("ENVIRONMENT: " + String.valueOf(client.getEnvironment()));
    orderResponse = null;
    try{
        orderId = "";
        // Creating an order payload
        OrdersCreateRequest request = new OrdersCreateRequest();
        // Build PayPal Request Body
        request = client.createCustomerOrder("Company Order", purchase.getTotalCheckoutCost(), 1, customer);
        // Create Order
        orderResponse = hClient.execute(request);
        log.info("Creating Order...");
        if(orderResponse.statusCode() == 201){
        log.info("Order with Complete Payload: ");
        log.info("Status Code: " + orderResponse.statusCode());
        log.info("Status: " + orderResponse.result().status());
        log.info("Order ID: " + orderResponse.result().id());
        log.info("Intent: " + orderResponse.result().checkoutPaymentIntent());
        log.info("Links: ");
        for(LinkDescription link : orderResponse.result().links()){
            log.info("\t" + link.rel() + ": " + link.href() + "\tCall Type: " + link.method());
        }// end for
        log.info("Total Amount: " + orderResponse.result().purchaseUnits().get(0).amountWithBreakdown().currencyCode() + " " + orderResponse.result().purchaseUnits().get(0).amountWithBreakdown().value());
        log.info("Full response body:");
        log.info("Authorized Successfully\n");
        orderId = orderResponse.result().id();
        log.info("PURCHASE UNIT ORDER ID: " + orderId);
        for(LinkDescription link : orderResponse.result().links()){
            String check = link.rel();
            log.info(link.rel() + ": " + link.href());
            if(check.equalsIgnoreCase("approve")){
            log.info("Request Approved");
            ServletActionContext.getResponse().sendRedirect(link.href());
            break;
            }else{
            log.info("CURRENT LINK: " + link.rel() + " NOT APPROVED");
            }// end if
        }// end for
        sessionMap.put("orderId", orderId);
        }// end if
        log.info("Created Successfully");
    }catch(Exception e){
        throw new PayPalException("Creating a PayPal order failed. Message is: " + e.getMessage(), e);
    }finally{
        if(null != orderResponse){
        log.info("Order response status code is: " + String.valueOf(orderResponse.statusCode()));
        }else{
        log.info("Order response is null.");
        }// end if/else
    }// end try/catch/finally

    return orderResponse.statusCode();
}// end doPaypalOrderWithCustomer

public OrdersCreateRequest createCustomerOrder(String desc, double cost, int quantity, Customer customer) throws Exception {
        log.debug("Entering createCustomerOrder");
        if(log.isDebugEnabled()){
            log.debug("Method to create order with complete payload");
            log.debug("Entry parameters are: desc=" + String.valueOf(desc) + ", cost=" + String.valueOf(cost) + ", quantity=" + String.valueOf(quantity) + ", Customer=" + String.valueOf(customer));
        }// end if
        double individualCost = cost / quantity;
        NumberFormat format = NumberFormat.getNumberInstance();
        format.setMaximumFractionDigits(2);
        format.setMinimumFractionDigits(2);
        OrdersCreateRequest request = new OrdersCreateRequest();
        request.header("prefer", "return=representation");
        OrderRequest orderRequest = new OrderRequest();
        orderRequest.checkoutPaymentIntent("AUTHORIZE");// This must be AUTHORIZE for the 3 step process
        Payer payer = new Payer();
        payer.email(customer.getEmail());
        PhoneWithType phoneWithType = new PhoneWithType();
        Phone phone = new Phone();
        String phoneNumber = customer.getPhoneNo().replace("(", "");
        phoneNumber = customer.getPhoneNo().replace(")", "");
        phoneNumber = customer.getPhoneNo().replace("-", "");
        phoneNumber = phoneNumber.replaceAll("\\D+", "");
        phone.nationalNumber(phoneNumber);
        phoneWithType.phoneNumber(phone);
        payer.phoneWithType(phoneWithType);
        orderRequest.payer(payer);
        ApplicationContext applicationContext = new ApplicationContext() //
                .brandName("Company, LLC")//
                .landingPage("BILLING")//
                .cancelUrl(bundle.getString("RESPONSE_URL") + "?t=c")//
                .returnUrl(bundle.getString("RESPONSE_URL") + "?t=r")//
                .userAction("CONTINUE").shippingPreference("NO_SHIPPING");
        orderRequest.applicationContext(applicationContext);
        List<PurchaseUnitRequest> purchaseUnitRequests = new ArrayList<>();
        PurchaseUnitRequest purchaseUnitRequest = new PurchaseUnitRequest()//
                .referenceId("PUHF")//
                .description("Digital Content")//
                .customId("CUST-DigitalContent")//
                .softDescriptor("DigitalContent")//
                .amountWithBreakdown(new AmountWithBreakdown()//
                        .currencyCode("USD")//
                        .value(format.format(cost))//
                        .amountBreakdown(new AmountBreakdown()//
                                .itemTotal(new Money()//
                                        .currencyCode("USD")//
                                        .value(format.format(cost)))//
                                .shipping(new Money()//
                                        .currencyCode("USD")//
                                        .value("0.00"))//
                                .handling(new Money()//
                                        .currencyCode("USD")//
                                        .value("0.00"))//
                                .taxTotal(new Money()//
                                        .currencyCode("USD")//
                                        .value("0.00"))//
                                .shippingDiscount(new Money()//
                                        .currencyCode("USD")//
                                        .value("0.00"))))
                .items(new ArrayList<Item>(){
                    private static final long serialVersionUID = 1L;
                    {
                        add(new Item()//
                                .name(desc)//
                                .description(desc)//
                                .sku("sku01").//
                        unitAmount(new Money()//
                                .currencyCode("USD")//
                                .value(format.format(individualCost)))//
                                .tax(new Money()//
                                        .currencyCode("USD")//
                                        .value("0.00"))//
                                .quantity(String.valueOf(quantity))//
                                .category("DIGITAL_GOODS"));
                    }
                }).shippingDetail(new ShippingDetail()//
                        .name(new Name()//
                                .fullName(customer.getFirstNm() + " " + customer.getLastNm()))//
                        .addressPortable(new AddressPortable()//
                                .addressLine1(customer.getAddress())//
                                .addressLine2(customer.getAddress2())//
                                .adminArea1(customer.getState())//
                                .adminArea2(customer.getCity())//
                                .postalCode(customer.getZipCode())//
                                .countryCode("US")));
        purchaseUnitRequests.add(purchaseUnitRequest);
        orderRequest.purchaseUnits(purchaseUnitRequests);
        request.requestBody(orderRequest);
        HttpResponse<Order> response = client().execute(request);
        if(response.statusCode() == 201){
            for(com.paypal.orders.LinkDescription link : response.result().links()){
                log.info(link.rel() + ": " + link.href() + "; Call Type: " + link.method());
            }// end for
            log.info("Total Amount: " + response.result().purchaseUnits().get(0).amountWithBreakdown().currencyCode() + " " + response.result().purchaseUnits().get(0).amountWithBreakdown().value());
            log.info(new JSONObject(new Json().serialize(response.result())).toString(4));
        }// end if
        if(log.isDebugEnabled()){
            log.debug("Return value is: response=" + String.valueOf(request));
        }// end if
        log.debug("Exiting createCustomerOrder");
        return request;
    }// end createCustomerOrder

Step 2: We Approve the order and get an authorized order id from PayPal.

public String approve() throws Exception {
        log.debug("Entering approve method.");
        log.trace("This method is used to approce purchases Post PayPal redirect.");
        log.info("Authorizing Order...");
        HttpServletRequest request = ServletActionContext.getRequest();
        String cancel = request.getParameter("t");
        log.info("Parameter being returned from PayPal: " + String.valueOf(cancel));
        if(cancel.equalsIgnoreCase("c")){
            payPalCancel = true;
            if(null != sessionMap.get("purchase")){
                sessionMap.remove("purchase");
            }// end if
            if(null != sessionMap.get("cartCount")){
                sessionMap.put("cartCount", 0);
            }// end if
            setCartCount(0);
            if(null != sessionMap.get("images")){
                sessionMap.remove("images");
            }// end if
            setPayPalCancel(true);
            return INPUT;
        }else{
            if(null != sessionMap.get("orderId")){
                orderId = (String) sessionMap.get("orderId");
            }// end if
            log.info("Order ID: " + String.valueOf(orderId));
            OrdersAuthorizeRequest orderAuthorizeRequest = new OrdersAuthorizeRequest(orderId);
            orderAuthorizeRequest.requestBody(new OrderRequest());
            orderResponse = hClient.execute(orderAuthorizeRequest);
            if(orderResponse.statusCode() == 201){
                authOrderId = orderResponse.result().purchaseUnits().get(0).payments().authorizations().get(0).id();
                log.info("AUTHORIZED ORDER ID: " + authOrderId);
            }// end if
            sessionMap.put("authOrderId", authOrderId);
            log.debug("Exiting approve");
        }// end if/else
        return SUCCESS;
}// end approve

Step 3: As the developer we must Capture that approved order. This is the final step.

public String capture() throws Exception {
    log.debug("Entering capture method.");
    log.trace("This method is used to save capture Payment.");
    // Capturing authorized order
    if(null != sessionMap.get("authOrderId")){
        authOrderId = (String) sessionMap.get("authOrderId");
    }// end if
    log.info("Authorized Order ID: " + String.valueOf(authOrderId));
    log.info("Capturing Order...");
    setCaptured(true);
    HttpResponse<Capture> captureOrderResponse = new CaptureOrder().captureOrder(authOrderId, true);
    if(captureOrderResponse.statusCode() == 201){
        log.info("Captured Successfully");
        log.info("Status Code: " + captureOrderResponse.statusCode());
        log.info("Status: " + captureOrderResponse.result().status());
        log.info("Capture ID: " + captureOrderResponse.result().id());
        log.info("Links: ");
        for(com.paypal.payments.LinkDescription link : captureOrderResponse.result().links()){
        log.info("\t" + link.rel() + ": " + link.href() + "\tCall Type: " + link.method());
        }// end for
    }// end if
    log.debug("Exiting capture");
    return SUCCESS;
}// end capture

Thanks to everyone who helped. I'm new at this and may have done somethings wrong, but I was finally able to get it to work.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文