@xceedsrl/adyenjs

1.0.8 • Public • Published

XceedAdyen payments

JS library to provide functionalities and interaction with the Adyen checkout-service

This npm package provides functionalities and interaction with the Payment Micro Service. It’s meant to be used in all the web platforms, currently including the Xceed Widget and the B2C xceed.me.

The package allows a platform to pay through different methods:

  • Credit Card payments
  • 3DSecure1 security payments
  • 3DSecure2 security payments
  • Payments with ticket holders information
  • No payments bookings

It automatically takes care of the redirects and tickets generation, over the errors handling and the buyer information.

Table of contents

Requirements

Installation

npm

To install the library using npm, type on your terminal:

npm install @xceed/adyenjs

yarn

To install the library using yarn, type on your terminal:

yarn add @xceed/adyenjs

bitbucket

Until the library won't be available on the npm registry, install it from the bitbucket repo, type on your terminal:

npm install git+ssh://git@bitbucket.org/Xceed/adyenjs-payments.git#develop

Usage and code sample

Since we want to abstract from the checkout flow the submission action, it's necessary to proceed in steps to generate the dropin:

  1. Create an instance of the XceedClient.
  2. Initialize the instance using the XceedClient.prototype.init method and passing the necessary options.
  3. Using the XceedClient instance, create a new checkout service with th XceedClient.prototype.createCheckout method.
  4. When the checkout service has been created, you can finally generate a new dropin with the XceedClient.prototype.createDropin method.

Now the we have all the needed elements, we can add to our component the XceedDropin in order to render the form.

Let's check an example and later we'll comment it.

Code

import React, { useState, useEffect } from 'react';
import { XceedClient, XceedDropin } from '@xceed/adyenjs';

function MyCheckoutComponent() {
  // ======
  // STEP 1
  // ======
  const [dropin, setDropin] = useState(null);
  const [isDisabled, setIsDisabled] = useState(true);

  // ======
  // STEP 2
  // ======
  const bookingData = {
    rsvp: 216965,
    prid: 11315,
    source: 'widget',
    numTickets: 1,
    price: 20,
    fee: 1.85,
    widgetId: 3,
    eventId: 74889,
    venueName: 'Pacha',
  };

  const ticketHolderFields = [
    { name: 'firstName', displayName: 'First Name', dataType: 'text', required: true },
    { name: 'lastName', displayName: 'Last Name', dataType: 'text', required: true },
    { name: 'phone', displayName: 'Phone', dataType: 'numeric', required: false },
  ];

  // ======
  // STEP 3
  // ======
  useEffect(() => {
    (async () => {
      const xceedClient = new XceedClient();
      await xceedClient.init({ country: 'ES', currency: 'EUR', amount: 10 });
      const checkout = xceedClient.createCheckout({ locale: 'es-ES' });
      const newDropin = xceedClient.createDropin(checkout, { enableStoreDetails: false });
      setDropin(newDropin);
    })();
  }, []);

  // ======
  // STEP 4
  // ======
  function onSuccess(paymentResult) {
    console.log('payment result', paymentResult);
  }

  function onFailure(error) {
    console.log('payment error', error);
  }

  function onPending() {
    console.log('Paying.....');

    return function() {
      console.log('End waiting time!');
    };
  }

  // ======
  // STEP 5
  // ======
  return dropin ? (
    <>
      <XceedDropin
        dropin={dropin}
        setDropin={setDropin}
        bookingData={bookingData}
        payment={{ amount: 10, country: 'ES', currency: 'EUR', storePaymentMethod: false }}
        ticketHolderFields={ticketHolderFields}
        disabler={setIsDisabled}
        onSuccess={onSuccess}
        onFailure={onFailure}
        onPending={onPending}
        lang="es"
      />
      <button disabled={isDisabled} onClick={dropin.submit}>
        Submit now
      </button>
    </>
  ) : null;
}

Steps

  1. Inside our MyCheckoutComponent, we need to declare two states:

    • dropin: it will hold the dropin instance
    • isDisabled: it will hold the status to disable/enable our submit button, it should default to true to get our button disabled in the beginning.
  2. Declare the informations about your booking:

    • rsvp: the selected rsvp id,
    • prid: the promoter id,
    • source: the source platform for this purchase (web|widget),
    • numTickets: bought tickets number
    • price: price for ticket
    • fee: fee for ticket
    • widgetId: id of the club widget (only if from widget source)
    • eventId: id for event rsvp
    • venueName: name of the event venue

    Also, if they are passed, you need to pass the array of ticketHolderFields.

  3. In this step, we run an effect on mount of our component to:

    • Create the xceedClient instance with XceedClient constructor.
    • Await for the async operation of initialisation. This operation takes care of fetching the public key for the service, the available payments methods, and the necessary scripts to create a new checkout. It take options as country and currency, over others available in the Api section.
    • Create a new checkout using the .createCheckout method. It returns a new checkout instance, and accept an object with the locale option for the form internationalization purpose.
    • With the .createDropin method, we create our new dropin, passing the checkout instance as first argument (it's necessary for the dropin creation), and an optional object of options.
    • Finally, we set the dropin state to the newly created dropin instance, ready to be passed to the XceedDropin component.
  4. The XceedDropin component accept many props, some of them related to events to handle successful payments, pending operations, or even failed payments. It's up to the developer decide if pass or not these optional events to handle the interactions with the XceedDropin component. See more about events on the Api section.

  5. In this last step, we are ready to render the component and the external submit button. XceedDropin need at least some required props to properly work:

    • dropin: the dropin state that hold the dropin instance created with the effect on mount.
    • setDropin: the dropin setter, essential for the component to handle internal logic.
    • bookingData: the previously created object with the booking information.
    • payment: the payment object contains information about the total amount to pay, the currency and other options. See more in the Api section.
    • disabler: the isDisabled state setter to internally handle if the form is ready to be submitted.

    About the submit action, any button or element able to trigger an event can use the method dropin.submit coming directly from the dropin instance and updated thanks to internal logic.

    Also, is possible to use the isDisabled state to keep disabled the submit trigger until the form is not validate.

Api

XceedClient

  • XceedClient()

    The XceedClient constructor, it creates an instance to create checkout services and dropins.

  • Xceed.prototype.init([options])

    This async method initialize the instance of XceedClient and create all the necessary resources to create checkout services.

    It takes optional setting passed through an object:

    Option Description Type Required Default
    amount Represents the amount to pay for the current payment. number true 20
    channel The channel used to fetch payment methods, should always be set to "web" for web apps (widget, b2c...). string false "web"
    country The country code where users are paying from. string false "ES"
    currency The currency applied to the payment methods. string true "EUR"
    paymentAccountId The id for any existing payment account, always undefined in the widget platform. string false -
  • Xceed.prototype.createCheckout([options])

    This method create a checkout service, necessary for the creation of a dropin.

    It takes optional setting passed through an object:

    Option Description Type Required Default
    locale Represents the locale code for forms internationalization. String false "es_ES"
  • Xceed.prototype.createDropin(checkoutInstance, [options])

    This method create a dropin instance, necessary for the XceedDropin component rendering.

    It takes a checkout instance as first argument and optional setting passed through an object as second:

    Option Description Type Required Default
    enableStoreDetails Show the checkbox to save used payment methods for a user. Boolean false true
  • Xceed.fetchOriginKey()

    This static method fetch and return a promise with the response of an /origin-key request.

  • Xceed.fetchPaymentMethods([options])

    This static method fetch the available payments methods based on some optons, currently used in the Xceed.prototype.init method.

    It takes optional setting passed through an object:

    Option Description Type Required Default
    amount Represents the amount to pay for the current payment. number true 20
    channel The channel used to fetch payment methods, should always be set to "web" for web apps (widget, b2c...). string false "web"
    country The country code where users are paying from. string false "ES"
    currency The currency applied to the payment methods. string true "EUR"
    paymentAccountId The id for any existing payment account, always undefined in the widget platform. string false -
  • Xceed.addScripts()

    This static method adds and caches to the current document body the necessary scripts to create an Adyen checkout service.

  • Xceed.createBooking(bookingData)

    This static async method attempt a booking and return the booking id in case of success.

    It takes an object as first argument with the required field:

    Option Description Type Required Default
    enableStoreDetails Show the checkbox to save used payment methods for a user. Boolean false true
  • Xceed.generateTicket(form)

    This static async method generate a ticket, used when no payment is required.

    It takes a FormData as first argument with all the ticket buyer and ticket holders info:

    Option Description Type Required Default
    form Ticket buyer/holder info. FormData True -
  • Xceed.pay(type, paymentRequest)

    This static async method send the payment for a booking.

    It takes a payment type endpoing as first argument and an object with the payment request data as second argument. Is recommended to not use this method without any other interface, since it's part of the checkout flow implemented for the XceedDropin component.

    Option Description Type Required Default
    type Payment type endpoint. string true -
    paymentRequest Payment request details. object true -
  • Xceed.submitAdditionalDetails(paymentId, additionalPaymentData)

    This static async method send the payment for a booking.

    It takes a payment id as first argument and an object with the additional payment data as second argument. Is recommended to not use this method without any other interface, since it's part of the checkout flow implemented for the XceedDropin component.

    Option Description Type Required Default
    paymentId Payment id string true -
    additionalPaymentData Additional payment data. object true -

XceedDropin

The XceedDropin component renders different parts of our checkout flow:

  • Ticket Buyer form: always rendered when buying a ticket.
  • Ticket holder form: rendered when a type of rsvp is marked as nominative and the user buys more than one ticket.
  • Dropin payment form: rendered when the user has to pay at the online checkout, this section include all the available payments methods.

The component accepts some properties, some of them required:

Property Description Type Required Default
dropin Dropin instance added to the dropin state. object true -
setDropin Setter for the dropin state. function true -
disabler Disabler function for validation flags. function True -
bookingData Object with booking related information. object true -
payment Object with payment related information. object true -
formFields Form fields with constrains for the ticket buyer. array false []
ticketHolderFields Form fields with constrains for the ticket holders. array false []
lang Form language. string false "en"
onSuccess Function triggered after a successful payment/booking. function false () => {}
onFailure Function triggered after a failed payment/booking. function false () => {}
onPending Function triggered when a payment/booking flow starts. It also accept a clean up function as return value that will be executed when the paymente flow ends. function false () => {}

bookingData

The bookingData property should respect the following shape:

Property Description Type Required
rsvp Rsvp id. number true
prid Promoter id. number true
source Booking source. string true
numTickets Number of tickets. number true
price Price for selected rsvp. number true
fee Fee for selected rsvp. number true
widgetId Id of the origin widget. number false
eventId Id of the current event. number true
venueName Name of the current venue. string true

payment

The payment property should respect the following shape:

Property Description Type Required
amount Amount to pay for the current transaction. number true
country Country where the current transaction is paid. string true
currency Currency for the current transaction. string true
storePaymentMethod Flag to render or not the "Save payment method" checkbox. boolean false

formFields/ticketHolderFields

The formFields/ticketHolderFields property should respect the following shape:

[
	{ name: 'firstName', displayName: 'First Name', dataType: 'text', required: true },
  { name: 'lastName', displayName: 'Last Name', dataType: 'text', required: true },
  ...
]

Implementation details

  • The formFields passed will be merged with a default set of fields which are always included.

Development

For more information about the development flow and how to contribute to this package, you can find all the details in the Xceed AdyenJS Wiki.

Contributors

License

This project is licensed under the MIT License - see the LICENSE.md file for details.

Readme

Keywords

Package Sidebar

Install

npm i @xceedsrl/adyenjs

Weekly Downloads

0

Version

1.0.8

License

MIT

Unpacked Size

61.4 kB

Total Files

4

Last publish

Collaborators

  • xceedsrl