Skip to content

PAYONE-GmbH/PCP-client-javascript-SDK

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

PAYONE Commerce Platform Client JavaScript SDK

Quality Gate Status Coverage npm npm downloads

Welcome to the PAYONE Commerce Platform Client JavaScript SDK for the PAYONE Commerce Platform. This SDK provides everything a client needs to easily complete payments using Credit or Debit Card, PAYONE Buy Now Pay Later (BNPL) and Apple Pay.

Table of Contents

Features

  • Credit Card Tokenizer: Securely tokenize credit and debit card information.
  • Fingerprinting Tokenizer: Generate unique tokens for device fingerprinting.
  • Apple Pay Session Integration: Seamlessly integrate Apple Pay into your payment workflow.

Installation

To install the PAYONE Commerce Platform Client JavaScript SDK, you can use either npm, yarn, or pnpm. Choose the command that corresponds to your package manager:

Using npm:

npm install pcp-client-javascript-sdk

Using yarn:

yarn add pcp-client-javascript-sdk

Using pnpm:

pnpm add pcp-client-javascript-sdk

back to top

Usage

Credit Card Tokenizer

The Credit Card Tokenizer now uses the new PAYONE Hosted Tokenization SDK. It securely collects and processes credit or debit card information in a PCI DSS-compliant way, returning a token for use in your server-side payment process.

To integrate the Credit Card Tokenizer feature into your application, follow these steps:

1. Add the Payment IFrame and Submit Button to your HTML

<div id="payment-IFrame"></div>
<button id="submit">Submit</button>

2. Import the Tokenizer and Types from the SDK

import { Config, PCPCreditCardTokenizer } from 'pcp-client-javascript-sdk';

3. Configure the Tokenizer

const config: Config = {
  iframe: {
    iframeWrapperId: 'payment-IFrame',
    height: 400,
    width: 400,
  },
  uiConfig: {
    formBgColor: '#64bbb7',
    fieldBgColor: 'wheat',
    fieldBorder: '1px solid #b33cd8',
    fieldOutline: '#101010 solid 5px',
    fieldLabelColor: '#d3d83c',
    fieldPlaceholderColor: 'blue',
    fieldTextColor: 'crimson',
    fieldErrorCodeColor: 'green',
  },
  locale: 'de_DE',
  submitButton: {
    selector: '#submit',
  },
  tokenizationSuccessCallback: (statusCode, token, cardDetails) => {
    console.log('Tokenized card successfully');
    console.log('Status:', statusCode);
    console.log('Token:', token);
    console.log('Card Details:', cardDetails);
  },
  tokenizationFailureCallback: (statusCode, errorResponse) => {
    console.error('Tokenization of card failed');
    console.error('Status:', statusCode);
    console.error('Error:', errorResponse.error);
  },
  environment: 'test', // Use 'live' for production
};

4. Fetch the JWT Token from your Backend

const fetchJwtToken = async (): Promise<string> => {
  // Fetch the JWT from your backend (CommercePlatform-API)
  return '<Token to be retrieved from the CommercePlatform-API>';
};

5. Initialize the Tokenizer

const init = async () => {
  const jwtToken = await fetchJwtToken();
  await PCPCreditCardTokenizer.create(config, jwtToken);
};

init();

6. Customization and Callbacks

  • iframe: Configure the container and size for the payment iframe.
  • uiConfig: Customize the look and feel of the form fields.
  • locale: Set the language/locale for the form.
  • submitButton: Provide a selector or element for the submit button.
  • tokenizationSuccessCallback: Handle the token and card details on success.
  • tokenizationFailureCallback: Handle errors on failure.

7. PCI DSS & Security

  • The SDK uses a JWT from your backend for secure initialization.
  • All card data is handled inside the iframe and never touches your application code.

8. Migration Note

If you previously used the classic PAYONE Hosted IFrames, update your integration to use the new Hosted Tokenization SDK as shown above. The old fields, defaultStyle, and related config are no longer used.

For more details, see the demo project.

back to top


Fingerprinting Tokenizer

To detect and prevent fraud at an early stage for the secured payment methods, the Fingerprinting Tokenizer is an essential component for handling PAYONE Buy Now, Pay Later (BNPL) payment methods on the PAYONE Commerce Platform. During the checkout process, it securely collects three different IDs to generate a snippetToken in the format <partner_id>_<merchant_id>_<session_id>. This token must be sent from your server via the API parameter paymentMethodSpecificInput.customerDevice.deviceToken. Without this token, the server cannot perform the transaction. The tokenizer sends these IDs via a code snippet to Payla for later server-to-Payla authorization, ensuring the necessary device information is captured to facilitate secure and accurate payment processing.

To integrate the Fingerprinting Tokenizer feature into your application, follow these steps:

1. Import Tokenizer from the SDK:

import { PCPFingerprintingTokenizer } from 'pcp-client-javascript-sdk';

2. Setup Selector for Script and Link Tag:

  • Ensure you have a selector for the script and link tag. You can use a specific element or simply use the body as the selector:
    <div id="fingerprintContainer"></div>
  • Alternatively, you can use the body selector:
    <body></body>

3. Create a New Fingerprinting Tokenizer Instance:

  • Initialize a new FingerprintingTokenizer instance by invoking the static create method with the appropriate parameters, including a unique session ID for each checkout experience. If you don't have a session ID, you can generate one using a GUIDv4 function or let the SDK generate it automatically:

    const selector = '#fingerprintContainer'; // or 'body'
    const environment = 't'; // 't' for test, 'p' for production
    const paylaPartnerId = 'your-payla-partner-id';
    const partnerMerchantId = 'your-partner-merchant-id';
    const sessionId = yourUniqueSessionId || generateGUIDv4() || undefined; // Optional: You can pass a unique session ID or let the SDK generate one
    
    const paylaScriptId = 'your-payla-script-id'; // Optional: The ID for the Payla script element. Default is "paylaDcs"
    const paylaStylesheetId = 'your-payla-stylesheet-id'; // Optional: The ID for the Payla stylesheet element. Default is "paylaDcsStylesheet"
    
    const fingerprintingTokenizer = await PCPFingerprintingTokenizer.create(
      selector,
      environment,
      paylaPartnerId,
      partnerMerchantId,
      sessionId,
      paylaScriptId,
      paylaStylesheetId,
    );

4. Get Snippet Token:

  • Once the scripts are loaded, you can obtain the snippet token required for the special payment process by calling:
    const token = fingerprintingTokenizer.getSnippetToken();
  • This snippet token is automatically generated when the PCPFingerprintingTokenizer instance is created and is also stored by Payla for payment verification. You need to send this snippet token to your server so that it can be included in the payment request. Add the token to the property paymentMethodSpecificInput.customerDevice.deviceToken.

5. (Optional) Get Unique SessionID:

  • If you need to retrieve the unique session ID that was used or generated during the creation of the PCPFingerprintingTokenizer instance, you can do so by calling the getUniqueId method:
    const sessionID = fingerprintingTokenizer.getUniqueId();

For further information see: https://docs.payone.com/pcp/commerce-platform-payment-methods/payone-bnpl/payone-secured-invoice

back to top


Apple Pay Session Integration

This section guides you through integrating Apple Pay into your web application using the pcp-client-javascript-sdk. The integration involves configuring the Apple Pay button and handling the Apple Pay session.

1. Setup Your Server and Environment

2. Setup Selector for Apple Pay Button

  • Ensure you have a selector for the apple pay button element:
    <div id="apple-pay-button"></div>

3. Import PCPApplePaySession and Types from the SDK

import {
  ApplePayButton,
  encodeToBase64,
  PCPApplePaySession,
  PCPApplePaySessionConfig,
} from 'pcp-client-javascript-sdk';

4. Session Configuration Object

The PCPApplePaySessionConfig interface extends ApplePayJS.ApplePayPaymentRequest and includes additional properties required for managing the Apple Pay session.

Additional PCPApplePaySessionConfig Properties

Property Type Description
applePayVersion number The version of Apple Pay on the Web that your website supports. See version history.
validateMerchantURL string The URL your server must use to validate itself and obtain a merchant session object.
processPaymentURL string The URL your server must use to process the payment.
applePayButtonId string (optional) The ID for the Apple Pay button element. Default is "apple-pay-button-script".
paymentMethodSelectedCallback (paymentMethod: ApplePayJS.ApplePayPaymentMethod) => Promise<ApplePayJS.ApplePayPaymentMethodUpdate> (optional) Callback function called when the user selects a new payment method.
couponCodeChangedCallback (couponCode: string) => Promise<ApplePayJS.ApplePayCouponCodeUpdate> (optional) Callback function called when the user enters or updates a coupon code.
shippingMethodSelectedCallback (shippingMethod: ApplePayJS.ApplePayShippingMethod) => Promise<ApplePayJS.ApplePayShippingMethodUpdate> (optional) Callback function called when the user selects a shipping method.
shippingContactAddressSelectedCallback (shippingContact: ApplePayJS.ApplePayPaymentContact) => Promise<ApplePayJS.ApplePayShippingContactUpdate> (optional) Callback function called when the user selects a shipping contact in the payment sheet.
cancelCallback () => void (optional) Callback function called when the payment UI is dismissed.
errorCallback (type: ErrorType, error: Error) => void (optional) Callback function called when an error occurs.
Example Session Configuration Object:
import {
  PCPApplePaySessionConfig,
  encodeToBase64,
} from 'pcp-client-javascript-sdk';

const applePaySessionConfig: PCPApplePaySessionConfig = {
  applePayVersion: 3,
  countryCode: 'DE',
  currencyCode: 'EUR',
  merchantCapabilities: ['supports3DS'], // mandatory
  supportedNetworks: ['visa', 'masterCard', 'amex', 'girocard'],
  total: {
    label: 'Demo',
    type: 'final',
    amount: '200.99',
  },
  requiredBillingContactFields: ['postalAddress', 'name', 'email'],
  requiredShippingContactFields: ['postalAddress', 'name', 'email'],
  shippingMethods: [
    {
      label: 'Standard Shipping',
      amount: '5.00',
      detail: 'Arrives in 5-7 days',
      identifier: 'standard',
    },
    {
      label: 'Express Shipping',
      amount: '10.00',
      detail: 'Arrives in 2-3 days',
      identifier: 'express',
    },
  ],
  validateMerchantURL: 'https://your-merchant.url/validate-merchant',
  processPaymentURL: 'https://your-merchant.url/process-payment',
  // A Base64-encoded string used to contain your application-specific data. (See: https://developer.apple.com/documentation/apple_pay_on_the_web/applepayrequest/2951834-applicationdata)
  applicationData: encodeToBase64(
    JSON.stringify({
      foo: 'bar',
    }),
  ),
  paymentMethodSelectedCallback: async (paymentMethod) => {
    console.log('paymentMethodSelectedCallback', paymentMethod);
    return {
      newTotal: applePaySessionConfig.total,
    };
  },
  couponCodeChangedCallback: async (couponCode) => {
    console.log('couponCodeChangedCallback', couponCode);
    return {
      newTotal: applePaySessionConfig.total,
    };
  },
  shippingMethodSelectedCallback: async (shippingMethod) => {
    console.log('shippingMethodSelectedCallback', shippingMethod);
    return {
      newTotal: applePaySessionConfig.total,
    };
  },
  shippingContactAddressSelectedCallback: async (shippingContact) => {
    console.log('shippingContactAddressSelectedCallback', shippingContact);
    return {
      newTotal: applePaySessionConfig.total,
    };
  },
  cancelCallback: () => {
    console.log('cancelCallback');
  },
  errorCallback: (type, error) => {
    console.error('Apple Pay Error:', type, error);
  },
};

5. Apple Pay Button Configuration

You need to configure the appearance and behavior of the Apple Pay button. The ApplePayButtonConfig interface allows you to specify the style, type, and locale of the button, as well as additional CSS styles.

ApplePayButtonConfig Properties

Property Type Description
buttonstyle 'black' | 'white' | 'white-outline' The appearance of the Apple Pay button. See button styles.
type Various types The kind of Apple Pay button. See button types.
locale string The language and region used for the displayed Apple Pay button. See button locales.
style object Additional CSS styles to apply to the Apple Pay button.
Example Apple Pay Button Configuration:
import { ApplePayButton } from 'pcp-client-javascript-sdk';

const applePayButton: ApplePayButton = {
  selector: '#apple-pay-button',
  config: {
    buttonstyle: 'black',
    type: 'plain',
    locale: 'de-DE',
    style: {
      width: '100%',
      height: '50px',
      borderRadius: '10px',
    },
  },
};

6. Integrating the Apple Pay Session

To integrate the Apple Pay session, you need to create an instance of the session using the PCPApplePaySession.create method. This method takes the session configuration and the button configuration as parameters.

Example:

import {
  ApplePayButton,
  PCPApplePaySession,
  PCPApplePaySessionConfig,
} from 'pcp-client-javascript-sdk';

const applePaySessionConfig: PCPApplePaySessionConfig = {...};
const applePayButton: ApplePayButton = {...};

await PCPApplePaySession.create(applePaySessionConfig, applePayButton);

For further information see: https://docs.payone.com/payment-methods/apple-pay

back to top


Google Pay Integration

The PAYONE Commerce Platform Client JavaScript SDK provides a demonstration project for Google Pay integration. The integration uses the official Google Pay Button libraries which are available for various frameworks:

Choose the appropriate library based on your framework:

Web Components

npm install @google-pay/button-element

React

npm install @google-pay/button-react

Angular

npm install @google-pay/button-angular

Our demo implementation uses the Web Component version (@google-pay/button-element), but you can adapt the code to use any of the framework-specific versions. The configuration options and payment request structure remain the same across all versions.

Setup Google Pay Integration (Web Component Example)

1. Install Dependencies
npm install @google-pay/button-element
2. Create a Web Component

Create a custom web component that encapsulates the Google Pay button:

import GooglePayButton from '@google-pay/button-element';

class MyGooglePayButton extends HTMLElement {
  constructor() {
    super();

    const shadow = this.attachShadow({ mode: 'open' });
    const button = new GooglePayButton();

    // Configure the button
    button.environment = 'TEST'; // Use 'PRODUCTION' for live environment
    button.buttonLocale = 'de';
    button.buttonType = 'pay';

    // Configure the payment request
    button.paymentRequest = {
      apiVersion: 2,
      apiVersionMinor: 0,
      allowedPaymentMethods: [
        {
          type: 'CARD',
          parameters: {
            allowedAuthMethods: ['PAN_ONLY', 'CRYPTOGRAM_3DS'],
            allowedCardNetworks: ['MASTERCARD', 'VISA'],
            billingAddressParameters: {
              format: 'FULL',
            },
          },
          tokenizationSpecification: {
            type: 'PAYMENT_GATEWAY',
            parameters: {
              gateway: 'payonegmbh',
              gatewayMerchantId: 'your-merchant-id',
            },
          },
        },
      ],
      merchantInfo: {
        merchantId: 'your-merchant-id',
        merchantName: 'Your Merchant Name',
      },
      transactionInfo: {
        totalPriceStatus: 'FINAL',
        totalPriceLabel: 'Total',
        totalPrice: '100.00',
        currencyCode: 'EUR',
        countryCode: 'DE',
      },
      // Optional: Configure shipping options
      shippingAddressRequired: true,
      shippingOptionRequired: true,
      shippingOptionParameters: {
        shippingOptions: [
          {
            id: 'standard',
            label: 'Standard Shipping',
            description: 'Arrives in 5-7 days',
          },
          {
            id: 'express',
            label: 'Express Shipping',
            description: 'Arrives in 2-3 days',
          },
        ],
        defaultSelectedOptionId: 'standard',
      },
    };

    // Handle the payment data
    button.onLoadPaymentData = (
      paymentData: google.payments.api.PaymentData,
    ) => {
      console.log('Payment Data:', paymentData);
      // This is where you would typically send the payment data to your server for processing
    };

    shadow.appendChild(button);
  }
}

customElements.define('my-google-pay-button', MyGooglePayButton);
3. Add the Component to your HTML
<my-google-pay-button></my-google-pay-button>

Button Configuration Options

Property Type Description
environment 'TEST' | 'PRODUCTION' The Google Pay environment to use
buttonLocale string The language for the button (e.g., 'de', 'en')
buttonType string The type of button ('pay', 'buy', etc.)
buttonColor 'default' | 'black' | 'white' The color scheme of the button
buttonSizeMode 'static' | 'fill' How the button should be sized

For more information about customizing the Google Pay Button, refer to:

For more information about Google Pay integration, refer to:

back to top


PAYONE Commerce Platform Compliant Interfaces

In addition to the Client-SDK, we also provide multiple Server-SDKs. If you want to directly expose PAYONE Commerce Platform compliant objects from your client, you can find all the necessary interfaces within the interfaces folder.

Example:

import type { CreateCheckoutRequest } from 'pcp-client-javascript-sdk';

const createCheckoutRequest: CreateCheckoutRequest = {...}

back to top


Demonstration Projects

You can find demonstration projects for each feature in the corresponding directories:

Building the SDK

Before running a demo project, you need to build the SDK in the root folder. This is necessary because the dist folder that gets created during the build process is targeted by the dependency with file:.. that is referenced in the credit card tokenizer and fingerprinting tokenizer demo projects.

To build the SDK, run the following command in the root folder:

npm run build

This command compiles the SDK and creates the dist folder, making it available for the demo projects to use.

Environment Variables

All the demos are using .env files for passing in sensitive information such as Keys, Identifier, URLs, and other configuration details. If you want to try out these demos, you must add an .env (or .env.local) file according to the given .env.example with your own credentials.

VITE_ Prefix

Each demo app uses Vite as the build tool. Vite exposes environment variables on the special import.meta.env object, which are statically replaced at build time. This ensures that the configuration is securely managed and tailored for different environments (development, production, etc.).

Environment variables with the VITE_ prefix are exposed to your client-side code. This is a security measure to prevent accidental exposure of sensitive data. Vite will only expose variables prefixed with VITE_, which ensures that server-only variables are not included in the client bundle.

Example .env file for the apple pay demo:

# client demo environment variables
VITE_APPLE_PAY_VALIDATE_MERCHANT_URL=https://your-merchant-domain.de/validate-merchant
VITE_APPLE_PAY_PROCESS_PAYMENT_URL=https://your-merchant-domain.de/process-payment
# server demo environment variables
APPLE_PAY_MERCHANT_IDENTIFIER=merchant.de.your.project
MERCHANT_DOMAIN_WITHOUT_PROTOCOL_OR_WWW=your-merchant-domain.de

back to top

Contributing

See CONTRIBUTING.md

back to top

Releasing the library

Preparing the Release

  • Checkout develop branch
  • Create release branch (release/0.1.0)
git checkout -b release/0.1.0
  • Apply versioning
npm version major|minor|patch

Changelog Generation with Conventional Changelog

The changelog gets generated automatically when the npm version gets bumped via npm version major|minor|patch within the version.sh script.

  1. Conventional Commit Messages:

    • Ensure all commit messages follow the conventional commit format, which helps in automatic changelog generation.
    • Commit messages should be in the format: type(scope): subject.
  2. Enforcing Commit Messages:

    • We enforce conventional commit messages using Lefthook with commitlint.
    • This setup ensures that all commit messages are validated before they are committed.

Merging the Release Branch

  • Create PR on develop branch
  • Merge develop in master branch

GitHub Action for Release

After successfully merging all changes to the master branch, an admin can trigger a GitHub Action to finalize and publish the release. This action ensures that the release process is automated, consistent, and deploys the new release from the master branch.

Triggering the GitHub Action:

  • Only admins can trigger the release action.
  • Ensure that all changes are committed to the master branch.
  • Navigate to the Actions tab on your GitHub repository and manually trigger the release action for the master branch.

Optional: Creating a GitHub Release

Once the release has been published to npm, developers can start using the latest version of the SDK. However, if you want to make the release more visible and include detailed release notes, you can optionally create a GitHub release.

  1. Navigate to the Releases Page: Go to the "Releases" section of your repository on GitHub.
  2. Draft a New Release: Click "Draft a new release".
  3. Tag the Release: Select the version tag that corresponds to the version you just published on npm (e.g., v0.1.0).
  4. Release Title: Add a descriptive title for the release (e.g., v0.1.0 - Initial Release).
  5. Auto-Generated Release Notes: GitHub can automatically generate release notes based on merged pull requests and commit history. You can review these notes, adjust the content, and highlight important changes.
  6. Publish the Release: Once you're satisfied with the release notes, click "Publish release".

Creating a GitHub release is optional, but it can provide additional context and visibility for your users. For detailed guidance, refer to the GitHub documentation on managing releases.

By following these steps, you can efficiently manage and streamline the release process for the PAYONE Commerce Platform Client JavaScript SDK, ensuring that the new release is published from the master branch while maintaining consistency and reliability.

back to top

Minimum Supported Browser Versions

The PAYONE Commerce Platform Client JavaScript SDK targets ES6 (ECMAScript 2015) and supports the following minimum browser versions:

Browser Minimum Supported Version
Google Chrome 51+
Mozilla Firefox 54+
Microsoft Edge 15+
Safari 10.1+
Opera 38+
iOS Safari 10.3+
Samsung Internet 5.0+
Android Browser 127+
Opera Mobile 80+
Chrome for Android 127+
Firefox for Android 127+

These versions ensure compatibility with ES6 features such as arrow functions, classes, template literals, and more.

For optimal performance and access to the latest features, we recommend using the most recent versions of your preferred browser.

back to top

License

This project is licensed under the MIT License. For more details, see the LICENSE file.

back to top

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors 2

  •  
  •