Integrate Przelewy24 using the JavaScript SDK

DocsCurrent

Last updated: Feb 18th, 4:47am

Use the JavaScript SDK to render payment fields and buttons, and process payments with the Orders API.

Buyer experience

Know before you code

  • Make sure the preference for receiving payments in your PayPal business account is set to accept and convert them to the default currency. To verify, in your profile select Account Settings > Payment preferences > Block payments and select Update to mark this preference.
  • This client-side and server-side integration uses the following:
  • Make sure you're subscribed to the following webhook events:
    • CHECKOUT.ORDER.APPROVED - Listen for this webhook and then capture the payment.
    • CHECKOUT.PAYMENT-APPROVAL.REVERSED - This webhook tells you when an approved order is cancelled and refunded because it wasn't captured within the capture window. Let the payer know about the problem and the reversed order.
  • By adding funding sources to your checkout integration, you agree to the  PayPal alternative payment methods agreement. This is in addition to the user agreement applicable to the country in which your business is physically located.

To get started

Run in Postman

Use Postman to explore and test PayPal APIs. Learn more in our Postman guide

Get up and running in GitHub Codespaces

GitHub Codespaces are cloud-based development environments where you can code and test your PayPal integrations. Learn more.

Open in Codespaces
1

Add PayPal Javascript SDK

Add or update the JavaScript SDK script on your web page.

    1<script src="https://www.paypal.com/sdk/js?client-id=YOUR_CLIENT_ID&components=buttons,payment-fields,marks,funding-eligibility&enable-funding=p24&currency=EUR"></script>

    This table lists the parameters you pass to the JavaScript SDK.

    Query param Default Description
    client-id none Your PayPal REST client ID. This identifies your PayPal account and determines where transactions are paid.
    components buttons A comma-separated list of components to enable. The buttons, payment-fields, marks, and funding-eligibility components are required for payment fields components.
    enable-funding none The enabled payment methods to show in buttons and marks.

    Note: By default, PayPal JavaScript SDK provides smart logic to display only appropriate marks and buttons for the current buyer. This optional parameter bypasses the buyer country check for desired payment methods.

    For example: src="https://www.paypal.com/sdk/js?client-id=YOUR_CLIENT_ID&enable-funding=venmo"
    currency USD This is the currency for the payment. This value needs to match the currency used when creating the order.
    locale automatic The locale renders components. By default PayPal detects the correct locale for the buyer based on their geolocation and browser preferences. It is recommended to pass this parameter with a supported locale if you need the PayPal buttons to render in the same language as the rest of your site.
    intent capture The intent for the transaction. This determines whether the funds are captured immediately while the buyer is present on the page.
    commit true This indicates that the final amount won't change after the buyer returns to your site from PayPal.
    vault false Whether the payment information in the transaction will be saved. Save your customers' payment information for billing agreements, subscriptions, or recurring payments. Marking this parameter false shows all funding sources, including payment methods that can't be saved.

    See additional, optional parameters.

    2

    Render payment mark

    You can use a mark integration for payment fields components to present the payment method options to the buyer as radio buttons.

    image

      1paypal.Marks({
      2 fundingSource: paypal.FUNDING.P24
      3}).render('#p24-mark')
      3

      Render payment fields

      Use payment fields to collect payment information from buyers. Fields dynamically render based on the selected funding source and you can customize the fields to align with your brand.

      You can choose from the following checkout flows:

      Single page

      For Przelewy24, payment fields collect first name, last name, and email.

      If there are validation errors in the input fields, they'll show on the click of the button.

        1paypal.PaymentFields({
        2 fundingSource: paypal.FUNDING.P24,
        3 /* style object (optional) */
        4 style: {
        5 /* customize field attributes (optional) */
        6 variables: {},
        7 /* set custom rules to apply to fields classes (optional) */
        8 rules: {},
        9 },
        10 fields: {
        11 /* fields prefill info (optional) */
        12 name: {
        13 value: "John Doe",
        14 },
        15 email: {
        16 value: "jdoe@example.com",
        17 },
        18 }
        19})
        20.render("#p24-container");

        For style parameters, please reference this style page: Custom style for payment fields

        Multi page

        A multi-page checkout flow spreads the checkout steps into two or more pages. This experience is applicable when an order details page needs to be shown to the buyer before an order is placed

        First page of the checkout flow

        This example renders the mark and payment fields, but not the payment button, on your checkout page.

        Multipage,Flow,Page,1
        1. Payment mark
        2. Payment fields
        1paypal.Marks({
        2 fundingSource: paypal.FUNDING.P24
        3}).render('#p24-mark')

        Second page of the checkout flow

        Based on the payment method selected on the first page, this example renders only the payment button along with the order details on the page. To complete checkout, the buyer clicks the payment button, authorizes, and confirms payment. You get the code to render the payment button in step 4.

        Multipage,Flow,Page,2

        For style parameters, please reference this style page: Custom style for payment fields


        4

        Render payment button

          1paypal.Buttons({
          2 fundingSource: paypal.FUNDING.P24,
          3 style: {
          4 label: "pay",
          5 },
          6 createOrder() {
          7 return fetch("/my-server/create-paypal-order", {
          8 method: "POST",
          9 headers: {
          10 "Content-Type": "application/json",
          11 },
          12 // use the "body" param to optionally pass additional order information
          13 // like product skus and quantities
          14 body: JSON.stringify({
          15 cart: [
          16 {
          17 sku: "YOUR_PRODUCT_STOCK_KEEPING_UNIT",
          18 quantity: "YOUR_PRODUCT_QUANTITY",
          19 },
          20 ],
          21 }),
          22 })
          23 .then((response) => response.json())
          24 .then((order) => order.id);
          25 },
          26 onApprove(data) {
          27 return fetch("/my-server/capture-paypal-order", {
          28 method: "POST",
          29 headers: {
          30 "Content-Type": "application/json",
          31 },
          32 body: JSON.stringify({
          33 orderID: data.orderID
          34 })
          35 })
          36 .then((response) => response.json())
          37 .then((orderData) => {
          38 // Successful capture! For dev/demo purposes:
          39 console.log('Capture result', orderData, JSON.stringify(orderData, null, 2));
          40 const transaction = orderData.purchase_units[0].payments.captures[0];
          41 console.log('Transaction Status:', transaction.status);
          42 console.log('Transaction ID:', transaction.id);
          43 // When ready to go live, remove the alert and show a success message within this page. For example:
          44 // const element = document.getElementById('paypal-button-container');
          45 // element.innerHTML = '<h3>Thank you for your payment!</h3>';
          46 // Or go to another URL: window.location.href = 'thank_you.html';
          47 });
          48 },
          49 onCancel(data, actions) {
          50 console.log(`Order Canceled - ID: ${data.orderID}`);
          51 },
          52 onError(err) {
          53 console.error(err);
          54 }
          55}).render("#p24-btn");
          • createOrder

            Implement the createOrder function to allow the JavaScript SDK to submit buyer information and set up the transaction on the click of the button.

            Use your server-side Create order call to set up the details of a one-time transaction including the amount, line item detail, and more. If order creation fails, the Orders API can return an error in the console.

            After order creation, orders are confirmed with buyer-selected payment source. If the order cannot be processed with the selected payment source, the relevant errors are returned in the console.
          • onCancel
            Implement the optional onCancel() function to show a cancellation page or return to the shopping cart.
          • onError
            Implement the optional onError() function to handle errors and display generic error message or page to the buyers. This error handler is a catch-all. Errors at this point are not expected to be handled beyond showing a generic error message or page.
          5

          Capture the transaction

          Implement the onApprove function, which is called after the buyer approves the transaction.

          Captures the funds from the transaction and shows a message to the buyer to let them know the transaction is successful. The method is called after the buyer approves the transaction on paypal.com.

          Because this is a client-side call, PayPal calls the Orders API on your behalf, so you don't need to provide the headers and body.

          capture() - Promise returning the order details.

            1paypal.Buttons({
            2 fundingSource: paypal.FUNDING.P24,
            3 createOrder() {
            4 return fetch("/my-server/create-paypal-order", {
            5 method: "POST",
            6 headers: {
            7 "Content-Type": "application/json",
            8 },
            9 // use the "body" param to optionally pass additional order information
            10 // like product skus and quantities
            11 body: JSON.stringify({
            12 cart: [
            13 {
            14 sku: "YOUR_PRODUCT_STOCK_KEEPING_UNIT",
            15 quantity: "YOUR_PRODUCT_QUANTITY",
            16 },
            17 ],
            18 }),
            19 })
            20 .then((response) => response.json())
            21 .then((order) => order.id);
            22 },
            23 onApprove(data) {
            24 return fetch("/my-server/capture-paypal-order", {
            25 method: "POST",
            26 headers: {
            27 "Content-Type": "application/json",
            28 },
            29 body: JSON.stringify({
            30 orderID: data.orderID
            31 })
            32 })
            33 .then((response) => response.json())
            34 .then((orderData) => {
            35 // Successful capture! For dev/demo purposes:
            36 console.log('Capture result', orderData, JSON.stringify(orderData, null, 2));
            37 const transaction = orderData.purchase_units[0].payments.captures[0];
            38 console.log('Transaction Status:', transaction.status);
            39 console.log('Transaction ID:', transaction.id);
            40 // When ready to go live, remove the alert and show a success message within this page. For example:
            41 // const element = document.getElementById('paypal-button-container');
            42 // element.innerHTML = '<h3>Thank you for your payment!</h3>';
            43 // Or go to another URL: window.location.href = 'thank_you.html';
            44 });
            45 }
            46}).render('#p24-button-container');
            47//This function displays payment buttons on your web page.

            For the capture call details and example responses, see Capture payment for order in the Orders API reference.

            If order capture fails, the Orders API can return an error in the console.

            6

            Handle webhook events

            A webhook handler is a script you create on your server that completes specific actions on webhooks that hit your listener URL.

            • We recommend subscribing to the CHECKOUT.ORDER.APPROVED webhook event in case a customer accidentally closes the browser and exits the checkout process after approving the transaction through their APM but before finalizing the transaction on your site.
            • We also recommend subscribing to the CHECKOUT.ORDER.DECLINED webhook event to receive notifications of any other failure scenarios. This webhook event passes a failure reason code and error message to indicate what caused the error.
            • Listen for the CHECKOUT.PAYMENT-APPROVAL.REVERSED webhook as an indication that an approved order wasn't captured within the capture window resulting in a cancellation of the order and a refund the buyer's account. Then notify your buyer of the problem and the reversed order.
            • PAYMENT.CAPTURE.PENDINGPAYMENT.CAPTURE.COMPLETED, and PAYMENT.CAPTURE.DENIED webhooks indicate capture status.

            See Subscribe to checkout webhooks for more information.

            Here are some additional resources as you create webhook handler code:

            Sample integration

            See a sample Przelewy24 integration in the PayPal GitHub repository.

            If you accept cookies, we’ll use them to improve and customize your experience and enable our partners to show you personalized PayPal ads when you visit other sites. Manage cookies and learn more