npm package: @netceterapx/click-to-pay-embedded-sdk
Description: Click-to-pay web-SDK for supporting SecureRemoteCommerce on web platforms - embedded
Latest version: 1.0.5

## Component usage

The Netcetera Click-to-Pay SDK component is of type web component.

```html
<click-to-pay locale='en_US'
              isExpanded='true'
              email='myemail@email.com'
              dcfOpeningBehaviour='full'
              startingPosition='button'
              buttonDesign='white'
              cardSelection='single'
              sandbox='false'></click-to-pay>
```

`locale` This prop informs the SRCi component to render in the appropriate language set by the merchant.

`isExpanded` This prop is used to show/hide the SRCi component. It can be used when the SRCi button is clicked to open
the component, or let the merchant control when to show the component.

`email` This prop can contain the currently authenticated profile email address. This allows the login section of the
SRC component to autofill the users email.

`dcfOpeningBehaviour` This prop controls how the SRC component will render the DCF window. Available options are:

- `replace` This will hide the SRC component while the DCF window is active. It will be placed where the SRC component
  is located.
- `full` This will cover the whole page with a backdrop. The DCF window will be placed in the center of the screen.
- `popup` This will open the DCF window in a popup window.

`startingPosition` This prop controls how the SRC UI renders initially. Available options are:

- `button` This will show the EMVCO standardized button initially. The user clicks on the button, and the SRC UI
  displays the content.
- `no-button` This will show the SRC UI content from the start.

`buttonDesign` This prop controls how the EMVCO button renders. Available options are:

- `black` This shows the button with a black background and white Click To Pay logo.
- `white` This shows the button with a white background and black Click To Pay logo.

`cardSelection` This prop controls whether the SRCi component will show the last accessed
credit card, or directly list all credit cards sorted by last access
time. (Default value `single`)

- `single` This shows the screen where only one card is initially shown.
- `multiple` This skips directly to the screen where all cards are listed.

`sandbox` This prop controls the environment which the SRCi component starts. Possible values:
- `false` This starts the SRCi in production mode, using the production SDK's by the chosen credit card brands.
  Note: A production environment must be configured first with the chosen credit card brand (Visa, MS, etc...).
- `true` This starts the SRCi in development mode, using the sandbox version of the chosen credit card brands. As an example,
this can be useful for local development.

Note: The application starts by default in production mode.

`config` This prop is used for initializing the SRC component.

```js

clickToPay.config = {
  mastercard: {
    srcInitiatorId: 'required-src-initiator-id',
    srciDpaId: 'required-src-dpa-id',
    dpaTransactionOptions: {
      dpaLocale: 'required-dpa-locale',
    },
  },
  visa: {
    srcInitiatorId: 'required-src-initiator-id',
    srciDpaId: 'required-src-dpa-id',
    encryptionKey: 'required-encryption-key',
    publicKey: 'required-public-key',
  },
  amex: {
    srcInitiatorId: 'required-src-initiator-id',
    dpaData: {
      dpaPresentationName: 'required-dpa-presentation-name',
      dpaName: 'required-dpa-name',
    },
    dpaTransactionOptions: {
      threeDsPreference: 'required-three-ds-preference',
    },
  },
};
```

If for example you do not support Amex, just by not including the `amex` property will be enough to inform the SRC
component to ignore that vendor.

Note: The SRC component has a detailed error reporting solution. Thus, any values that are missing will be reported with
the full path.

`config.iframe` This prop is used when a custom iframe window is used by the merchant.
This allows the merchant to control the position of the iframe window and also react on
the iframe state changes.

```html
<iframe width='600px' height='800px' id='src-iframe'></iframe>
```

```js
clickToPay.config = {
  iframe: {
    ref: document.querySelector('#src-iframe'),
    handlers: {
      onDcfShow() {
        // handle when DCF is visible and loaded...
      },
      onDcfHide() {
        // handle when DCF window is removed...
      }
    }
  },
}
```

Note: The `config.iframe.ref` property is required when using a custom window.

`autofill` This prop contains user data that is passed to the credit card brand DCF. For example, this can be useful
when the merchant has a logged-in user data which it can pass to the DCF, as to make some form fields already pre-filled.

```js
 clickToPay.autofill = {
  fullName: "John Doe",
  firstName: "John",
  lastName: "Doe",
  emailAddress: "john-doe@company.com",
  billingAddress: {
    countryCode: "US",
    name: "John",
    line1: "29501 PACIFIC FEDERAL WAY WA 98003-3869 USA",
    city: "Washington",
  },
};
```

Note: Some fields might be ignored / not used, by a particular credit card brand DCF.

### Dynamically update the SRCi component

The SRCi component able to react to any changes of its props. That means the merchant can programmatically set/update
its props, and the component will update itself accordingly.

```js
document.addEventListener('DOMContentLoaded', function() {
  
  let clickToPay = document.querySelector('click-to-pay');

  clickToPay.setAttribute('isExpanded', 'false');

  clickToPay.config = {
    // ...
  }

  clickToPay.addEventListener('postInitialization', (e) => {
    // handle post init. events.
  });

  clickToPay.addEventListener('paymentSuccess', (e) => {
    // handle success...
  });
  clickToPay.addEventListener('paymentError', (e) => {
    // handle error...
  });

  clickToPay.addEventListener('generalEvents', (e) => {
    // handle events that might be important to listen on...
  });

  clickToPay.addEventListener('performanceUpdate', (e) => {
    // handle performance entry update
  });
});
```

`document.addEventListener('DOMContentLoaded', function() {...});` It's recommended to initialize/update any properties after the component is fully initialized.

`let clickToPay = document.querySelector('click-to-pay');` The merchant can get a reference to the SRCi component.

`clickToPay.setAttribute('isExpanded', 'false');` Then, the merchant is able to modify any prop for the component, when
that happens the component reacts.

` clickToPay.addEventListener('postInitialization', (e) => {});` The SRCi will fire a post initialization event after the component initializes.
It can inform of the following cases: (Payload found inside “detail” property).

1.	CONSUMER_RECOGNIZED: if the consumer is recognized, profile is fetched, and the component displays the card list.
2.	CONSUMER_ID_KNOWN: if the email provided during the initialization results in a profile on any of the SRC-Systems.
3.	CONSUMER_NOT_FOUND: if consumer is not recognized, and the email provided (if provided) does not result in positive lookup from any of the SRC-Systems.


` clickToPay.addEventListener('paymentSuccess', (e) => {});` The SRCi component will fire a success event when the card
has been selected from the user. The response will contain the data for the user card needed to complete a transaction.

`clickToPay.addEventListener('paymentError', (e) => {});` The SRCi component will fire a error event whenever there is a
problem that is not able to recover from. For example: The vendor SDK servers are down. Or something unexpected
happened.

`clickToPay.addEventListener('generalEvents', (e) => {});` The SRCi component will fire an event when important steps/actions
happened inside the component, triggered by the user or the component itself. Example: The user chose to cancel the open DCF window.

`clickToPay.addEventListener('performanceUpdate', (e) => {});` The SRCi component will fire an event when a new SDK performance entry
has been measured. Example: Mastercard/Visa/Amex SDK init or get profile method finished, and the time for its
execution has been measured.

`clickToPay.addEventListener('userActionUpdate', (e) => {});` The SRCi component will fire an event when a new user action 
has been performed. Example: User clicked on an input field/button, started typing text or selected a card.

```ts
 enum GeneralEvents {
  ON_DCF_CANCEL
}
```

<h3 id='headless-doc'> Headless </h3>

The SRC component can start in a "headless" mode. That means there will be no UI rendered on the screen,
which is left on the merchant, rather it exposes the `checkout` method directly.
Thus, the merchant can control the UI flow and leave the checkout process to
the SRC component to handle.

Note: The SRCi components still needs to be initialized by placing the HTML code.
You can hide the UI with the `isExpanded` and `startingPosition` props.

```html
<click-to-pay isExpanded='false'
              startingPosition='no-button'></click-to-pay>
```

```js
document.addEventListener('DOMContentLoaded', function() {
  
  let clickToPay = document.querySelector('click-to-pay');
  
  clickToPay.config = {
    // ...
  }

  // merchant creates the form. In this example we have a checkout submit button.
  let checkoutButton = document.querySelector('#checkout-button');
  
  // .then().catch() are also compatible.
  checkoutButton.onclick = async function() {
    try {
      let response = await clickToPay.checkout({
        card: {
          primaryAccountNumber: '1212121212121212',
          panExpirationMonth: '7', // '07' is also allowed.
          panExpirationYear: '2030', // must be 4 digits.
          cardSecurityCode: '123', // must be 3 or 4 digits.
        },
      });
      // handle the response.
    } catch (e) {
      // handle the error.
    }
  };
});
```

The response of the `checkout` method is forwarded from the SRC vendor to the merchant.

Example response:
```json
{
    "userAction": "COMPLETE",
    "checkoutResponseSignature": "eyJraWQiOiJTRTZOOE...",
    "creditCardBrand": "Visa",
    "performance":{"correlationId":{"visa":"5ee5add0-bbdd-6094-55bd-16c4c7bda302","mc":"34f4a04b.8add86db-c257-4f8c-808a-b51a4a07e444","amex":""},"referenceTimestamp":"2022-12-18T20:15:50.036Z","totalLoadingTime":3731,"recognitionState":"CONSUMER_NOT_FOUND","sdkPerformance":{"visa":[{"methodName":"init","duration":1428,"startDelta":0},{"methodName":"isRecognized","duration":1297,"startDelta":3690},{"methodName":"identityLookup","duration":1218,"startDelta":18833},{"methodName":"getSrcProfile","duration":2548,"startDelta":41254},{"methodName":"unbindAppInstance","duration":24,"startDelta":52816}]}},
    "userActions": [{"type":"click","target":"email","startDelta":1215},{"type":"text_type","target":"email","startDelta":1743},{"type":"click","target":"continue","startDelta":9258},{"type":"click","target":"otp","startDelta":18889.000000000004},{"type":"text_type","target":"otp","startDelta":43660},{"type":"click","target":"continue","startDelta":44120},{"type":"click","target":"continue","startDelta":50200}]
}
```

The `checkout` response includes a performance object that contains information about the duration of the 
performed SDK methods during the user interaction, and the point of time in which they started executing.
Apart from the performance object, it also contains an array of user actions that the user performed, and
the point of time in which the user performed the actions.

Performance object parameters:\
`correlationId`: The correlation ID used for the transaction.\
`referenceTimestamp`: The time when the click to pay component finished loading.\
`totalLoadingTime`: The total loading time of the click to pay component.\
`recognitionState`: The recognition state of the user.\
`sdkPerformance`: The SDK performance entries.

SDK performance object parameters:\
`methodName`: The name of the SDK method.\
`duration`: The duration of the method execution.\
`startDelta`: The number of milliseconds when the method started executing after the start of the init method execution.

User Action object parameters:\
`type`: The type of user action. Example: click, text_type, select.\
`target`: The target on which the user action is performed. Example: email, otp.\
`startDelta`: The point of time when the user action got executed after the loading of the click to pay component finished. Measured in milliseconds.

#### Error response

The SRC component validates the provided input for the checkout method. In case there is
a validation error, the following response can be returned.

```ts
enum CreditCardValidationErrorType {
  CREDIT_CARD_NUMBER_REQUIRED,
  CREDIT_CARD_CVV_REQUIRED,
  CREDIT_CARD_EXPIRATION_YEAR_REQUIRED,
  CREDIT_CARD_EXPIRATION_MONTH_REQUIRED,
  CREDIT_CARD_NUMBER_INVALID,
  CREDIT_CARD_NUMBER_UNSUPPORTED,
  CREDIT_CARD_CVV_INVALID,
  CREDIT_CARD_EXPIRED,
}

interface CreditCardValidation {
  type: CreditCardValidationErrorType;
}
```

Inside the error part (`catch (e)...`) as an example the response can be:

```js
{
  type: 'CREDIT_CARD_NUMBER_REQUIRED'
}
```

### Styling

There are multiple class names, and an id spread throughout the components of the SRCi.
These can be used as hooks to override / add styling as necessary.

`click-to-pay` This id is the top most HTML element which the SRCi mounts on.

`click-to-pay--main` This class wraps the main attribute. It's a container that wraps all sub-components and also contains the DCF window if chosen to do so.

`click-to-pay--spinner-container` This class wraps the spinner. This can be used to manipulate the spinner as to fit your specific styling requirements.

`click-to-pay--component-container` This class wraps every component that is currently active.