Examples

PayPal

Plants
& More

This example demonstrates a payment form using the PayPal payment method, where the customer authorizes the payment by signing in to their PayPal account.

The PayPal button is rendered by shift4.js, so the only library your page needs to load is shift4.js itself. You do not need to obtain or configure any PayPal credentials.

Payment flow technical overview

The full transaction involves a few straightforward steps:

  • The website loads shift4.js [1] and initializes it with the merchant public key [2].
  • The website calls createPayPalButton with the amount and currency [3]. Shift4.js requests a client token from the Shift4 API, loads the PayPal SDK and renders the PayPal button.
  • The customer clicks the button and approves the payment in the PayPal window.
  • Shift4.js returns a payment method nonce, together with the payer ID and device data, to the onApprove callback.
  • The website sends those values to the backend [4].
  • The backend uses Shift4 API to create a Payment Method, and then a Charge using the returned Payment Method ID.

@RestController
@RequestMapping("/ajax/examples/charge-with-paypal")
class ExamplesAjaxChargeWithPayPalController {

    @PostMapping("/payment")
    Map<String, String> chargeWithPayPalPayment(@RequestBody PayPalExampleRequest request, HttpServletRequest httpRequest) {
        try (Shift4Gateway shift4Gateway = createShift4Gateway()) {

            PaymentMethodRequest paymentMethodRequest = new PaymentMethodRequest((String) null)
                    .set("type", "paypal")
                    .set("fraudCheckData", new FraudCheckDataRequest()
                        .setIpAddress(RequestUtils.getIp(httpRequest))
                        .setUserAgent(RequestUtils.getUserAgent(httpRequest)))
                    .set("payPal", Map.of(
                        "nonce", request.nonce,
                        "payerId", request.payerId,
                        "deviceData", request.deviceData
                    ));
            PaymentMethod paymentMethod = shift4Gateway.createPaymentMethod(paymentMethodRequest);

            ChargeRequest chargeRequest = new ChargeRequest(2499, "USD")
                    .paymentMethod(new PaymentMethodRequest(paymentMethod.getId()));
            Charge charge = shift4Gateway.createCharge(chargeRequest);

            return singletonMap("chargeId", charge.getId());

        } catch (Shift4Exception e) {
            throw new BadRequestException(e.getMessage());
        }
    }

    static class PayPalExampleRequest {
        String nonce;
        String payerId;
        String deviceData;
    }
}