Secure Fields (Payment)

This page outlines the step-by-step process to enable the Secure Fields checkout functionalities in your system.

Step 1: Include the library in your project

The first step is to make sure to include the Yuno SDK file in your webpage before closing the <body> tag. See the example below:

<script src="https://sdk-web.y.uno/v1/static/js/main.min.js"></script>

Typescript library

If you are using Typescript, Yuno provides a library that you can use to see all available methods available in the Yuno Web SDK. Access the Complementary Features page to learn how to use it in your project.

Step 2: Initialize secure fields with the public key

In your JavaScript application, create an instance of the Yuno class by providing a valid PUBLIC_API_KEY. Check the Get your API credentials guide.

Like the example below, use the initialized class that is attributed to the yunoconstant.

const yuno = Yuno.initialize(PUBLIC_API_KEY)

Step 3: Start the checkout process

You will start the checkout process. To do it, use the secureFields function and provide the necessary configuration parameters.

The essential parameters are the countryCode, which determines the country for which the payment process is configured, and checkoutSession, which refers to the current payment's checkout session. The next code block presents an example of the parameter configuration.

The following table lists all required parameters and their descriptions.

ParameterDescription
countryCodeThis parameter determines the country for which the payment process is being configured. The complete list of supported countries and their country code is available on the Country coverage page.
checkoutSessionRefers to the current payment's checkout session.
Example: '438413b7-4921-41e4-b8f3-28a5a0141638'
installmentsEnableThis parameter is optional and is set false by default. If set True, the installments set for the account will be shown as a secure field.
  const secureFields = yuno.secureFields({
    /**
     * The complete list of country codes is available on https://docs.y.uno/docs/country-coverage-yuno-sdk
     */
    countryCode: country,
     /**
     * Should be added her or in the token generation
     * @optional
     */
    checkoutSession,
    installmentEnable: false,
  })

Customer and merchant-initiated transactions

Payments can be initiated by the customer (CIT) or by the merchant (MIT). You find more information about their characteristics in Stored credentials.

The step-by-step presented on this page refers to a customer-initiated transaction without the recurrence option. Typically, it's used in one-time online purchases, in-store purchases, ATM withdrawals, etc.

To learn how to use the Secure Fields to perform MIT operations, access the Merchant-initiated transactions page.

Step 4: Mount the Secure Fields

After defining the parameters, you will define, configure, and mount the Secure Fields. For each Secure Field, you need to define the name and options when creating it with the secureFields.create function.

The table below presents all configurations available:

ParametersDescription
nameThe available names for field names are cvv, pan, or expiration.
options.placeholderDefault placeholder for the field.
options.stylesAdditional CSS styles for the current field.
options.labelField visible label.
options.showErrorDefines if errors will be shown. Available options are true and false.
options.onChangeAn auxiliary function that can be configured and will run when the field content changes. Indicates if the fields have errors or additional data.
options.onBlurAn auxiliary function that can be configured and will run when blurring from the input.
options.validateOnBlurChange the validation behavior, improving the user experience by providing validation feedback after the field loses focus. It is an optional parameter that is false as default.
options.onFocusAn auxiliary function that can be configured and will run when focussing on the input.
options.onRenderedSecureFieldAn auxiliary function that can be configured and will run when the element finishes rendering.
options.errorMessageThis allows for the definition of the field's error message.

Once you have set the parameter, you will render the created Secure Field with the render function by selecting an HTML element using a valid CSS selector (#, ., [data-*]).

The following code block presents an example of the parameter configuration for three Secure Fields, and as they are mounted, the fields are presented to the user.

/**
   * interface SecureField {
   *  render(elementSelector: string): void
   * 
   *  clearValue(): void
   * 
   *  setError(errorMessage: string): void
   * 
   *  updateProps(args: Record<string, unknown>): void
   * 
   *  focus(): void
   * 
   *  validate(): void
   * 
   *  unmountSync(): Promise<void>
   * }
   */  
const secureNumber = secureFields.create({
     /**
     * name can be 'cvv' | 'pan' | 'expiration'
    */
    name: 'pan',
    options: {
      placeholder: '0000 0000 0000 0000',
      /**
       * you can edit card form styles
       * only you should write css then it will be injected into the iframe
       * example 
       * `@import url('https://fonts.googleapis.com/css2?family=Luckiest+Guy&display=swap');
       *  .Yuno-text-field__content.focus label.Yuno-text-field__label {
       *    color: red;
       *    font-family: 'Luckiest Guy' !important;
       *   }`
       */
      styles: ``,
      label: 'Card Number',
      showError: true,
      errorMessage: "Custom Error",
      validateOnBlur: false,
      // Indicates if the field has an error
      onChange: ({ error,data }) => {
      /**
       * in data.installments you could receive an installments plan list information 
       regarding the installments plan set for your account and chosen by the customer
    		[{
            installmentId: string;
            installment: number;
            amount: {
                currency: string;
                value: string;
                total_value: string;
            } | undefined;
        }]
       */
        /**
       * in data.cardIIN you can receive card_data
    		[{
            "id": "436c457c-1234-4e5e-b51d-1814e67d696a",
            "iin": "411111",
            "scheme": "VISA",
            "issuer_name": "JPMORGAN CHASE BANK N A",
            "issuer_code": null,
            "brand": "VISA",
            "type": "CREDIT",
            "category": "CREDIT",
            "country_code": "US",
            "country_name": "United States of America",
            "website": "https://www.chase.com",
            "phone": {
                "country_code": null,
                "number": "+ (1) 212-270-6000"
            },
            "address": {
                "address_line_1": null,
                "address_line_2": null,
                "city": null,
                "country": null,
                "state": null,
                "zip_code": null
            }
        }]
       */
       /**
       * in data.isCardIINLoading you can receive a true or false indicating if the card iin search is being excecuted.
       */
       /**
       * in data.isInstallmentLoading you can receive a true or false indicating if the installments search is being excecuted.
       */
        if (error) {
          console.log('error_pan')
        } else {
          console.log('not_error_pan')
        }
      },
      // Trigger when blurring from input
      onBlur() {
        console.log('blur_pan')
      },
      // Trigger when focussing on input
      onFocus: () => {
        console.log('focus_pan')
      },
      // Trigger when input has finished rendering 
      onRenderedSecureField: ()=> {
        console.log('render completed')
      }
    },
  })

	// Renders into specified element
  secureNumber.render('#pan')

  const secureExpiration = secureFields.create({
    /**
     * Fields name, can be 'cvv' | 'pan' | 'expiration'
     */
    name: 'expiration',
    // All options are optional
    options: {
      placeholder: 'MM / YY',
      /**
       * you can edit card form styles
       * only you should write css then it will be injected into the iframe
       * example 
       * `@import url('https://fonts.googleapis.com/css2?family=Luckiest+Guy&display=swap');
       *  .Yuno-text-field__content.focus label.Yuno-text-field__label {
       *    color: red;
       *    font-family: 'Luckiest Guy' !important;
       *   }`
       */
      styles: ``,
      label: 'Card Expiration',
      showError: true,
      errorMessage: "Custom Error",
      // Indicates if the fields has error
      onChange: ({ error }) => {
        if (error) {
          console.log('error_expiration')
        } else {
          console.log('not_error_expiration')
        }
      },
      // Trigger when blurring from input
      onBlur() {
        console.log('blur_expiration')
      },
      // Trigger when focussing on input
      onFocus: () => {
        console.log('focus_expiration')
      },
      // Trigger when input has finished rendering 
      onRenderedSecureField: ()=> {
        console.log('render completed')
      }
    },
  })

  // Renders into specified element
  secureExpiration.render('#expiration')


  const secureCvv = secureFields.create({
    name: 'cvv',
    options: {
      placeholder: 'CVV',
      /**
       * you can edit card form styles
       * only you should write css then it will be injected into the iframe
       * example 
       * `@import url('https://fonts.googleapis.com/css2?family=Luckiest+Guy&display=swap');
       *  .Yuno-text-field__content.focus label.Yuno-text-field__label {
       *    color: red;
       *    font-family: 'Luckiest Guy' !important;
       *   }`
       */
      styles: ``,
      label: 'CVV',
      showError: true,
      errorMessage: "Custom Error",
      // Indicates if the fields has error
      onChange: ({ error }) => {
        if (error) {
          console.log('error_cvv')
        } else {
          console.log('not_error_cvv')
        }
      },
      // Trigger when blurring from input
      onBlur() {
        console.log('blur_cvv')
      },
      // Trigger when focussing on input
      onFocus: () => {
        console.log('focus_cvv')
      },
      // Trigger when input has finished rendering 
      onRenderedSecureField: ()=> {
        console.log('render completed')
      }
    },
  })

  // Renders into specified element
  secureCvv.render('#cvv')

Below, you find a GIF showing how you can configure the Secure Fields.

Step 5: Generate an OTT (one-time token)

With all user information in hand, you can start the payment. First, you need to create a One-Time Token using the function secureFields.generateToken. As it is an asynchronous function, you can use try/catch to ensure you will correctly handle triggered errors. Below is an example of creating an OTT using vaultedToken information.

Benefits of using a vaulted token

When you use a vaulted token with the SDK, all the fraud information from the providers you configured in your card routing is collected and attached to the OTT. In addition, you can add installment information and a security code if the provider requires it.

// Create One Time Token
// This will trigger an error if there are missing data
// You can catch it using a try/catch
const oneTimeToken = await secureFields.generateToken({
  // Optional: This parameter is used to indicate that a different checkout session is desired, 
  //rather than the one initially generated.
  //A use case is for the persistence of card data after a payment error.
  checkoutSession: '{{the checkout session id}}',
  // Required: You can create an input to get this formation
  cardHolderName: 'John Deer',
  // Optional: You can create an input to get this formation
  saveCard: true,
  /**
   * @optional
   * Send this value if you already have a registered or enrolled payment method.
   * Other fields like card and customer are optional unless your provider requires them.
   */
  vaultedToken: "aad8578e-ac2f-40a0-8065-25b5957f6555",
  // Optional: only neccessary if an installments plan is created for the account
  installment: {
            id: string,
            value: number,
            amount: {
                currency: string,
                value: string,
                total_value: string,
            },
        },
  // Check your card processor to know if you need to send 
  // customer information
  // full object here https://docs.y.uno/reference/the-customer-object
  customer: {
    document: {
      document_number: '1090209924',
      document_type: 'CC',
    },
  },
  // This is useful for dual cards where the same card can be either used as credit or debit
  cardType: 'DEBIT' or 'CREDIT'
})

You can also use secureFields.generateTokenWithInformation to receive any additional info the customer gives at checkout, such as installments or document type/number.

// Create One Time Token
// This will trigger an error if there are missing data
// You can catch it using a try/catch
const oneTimeTokenWithInformation = await secureFields.generateTokenWithInformation({ 
  // Optional: This parameter is used to indicate that a different checkout session is desired, 
  //rather than the one initially generated.
  //A use case is for the persistence of card data after a payment error.
  checkoutSession: '{{the checkout session id}}',
  // Required: You can create an input to get this formation
  cardHolderName: 'John Deer',
  // Optional: You can create an input to get this formation
  saveCard: true,
  /**
   * @optional
   * Send this value if you already have a registered or enrolled payment method.
   * Other fields like card and customer are optional unless your provider requires them.
   */
  vaultedToken: "aad8578e-ac2f-40a0-8065-25b5957f6555",
  // Optional: only neccessary if an installments plan is created for the account
  installment: {
            id: string,
            value: number,
            amount: {
                currency: string,
                value: string,
                total_value: string,
            },
        },
  // Check your card processor to know if you need to send 
  // customer information
  // full object here https://docs.y.uno/reference/the-customer-object
  customer: {
    document: {
      document_number: '1090209924',
      document_type: 'CC',
    },
  },
  // This is useful for dual cards where the same card can be either used as credit or debit
  cardType: 'DEBIT' or 'CREDIT'
})

Step 6: Create the Payment

After receiving the One Time Token, you can create the payment using one of the two following options:

Both options require you to provide the oneTimeToken and the checkoutSession. As creating the payment may raise errors, Yuno recommends you use a try/catch function here.

After, you can check the payment status using the yuno.mountStatusPaymentfunction. The following example uses the createPayment function to create the payment and the mountStatusPayment to display the payment status:

// Create your payment, you should implement this function
await createPayment({ oneTimeToken, checkoutSession })

// Check payment status
yuno.mountStatusPayment({
  checkoutSession: checkoutSession,
  /**
   * Country can be one of CO, BR, CL, PE, EC, UR, MX
   */
  /**
     * Should be added her or in the token generation
     * @optional
     */
  countryCode: 'CO',
  /**
   * Language can be one of es, en, pt
   */
  language: 'en',
  /**
   * @param {'READY_TO_PAY' | 'CREATED' | 'SUCCEEDED' | 'REJECTED' | 'CANCELLED' | 'ERROR' | 'DECLINED' | 'PENDING' | 'EXPIRED' | 'VERIFIED' | 'REFUNDED'} data
   */
  yunoPaymentResult(data) {
    console.log('yunoPaymentResult', data)
  },
})

Demo App

In addition to the code examples provided, you can access the Demo App for a complete implementation of Yuno SDKs or go directly to the HTML and JavaScript checkout demos available on GitHub.

What's next?

Learn how to execute MIT using the Secure Fields, or for additional configurations from the Secure Fields SDK, access complementary features. You can also access other functions available on the Yuno Web SDK: