Validar una compra con OTP

📘

NOTA:

Antes de continuar recuerda realizar los 3 pasos de Inicio

4. Enviar la tarjeta

Cargar métodos de pago

Luego de establecer la dirección de la orden, obtén los métodos de pago que se encuentran en el panel de administración del comercio, esto devolverá una lista con todos los métodos de pago disponibles para tu comercio.

const getPaymentMethods = await SDK.getPaymentMethods();
// If the payment methods are not configured correctly, this error will appear.
if (getPaymentMethods.error != null) {
  console.log("Error in getPaymentMethods");
  return;
}
// If the payment methods are not configured in the admin this error appears.
if (getPaymentMethods.data?.data.length == 0) {
  console.log("Payment methods not configured");
  return;
}
console.log(getPaymentMethods.data?.data);

El comercio usado de ejemplo tiene dos métodos de pago:

  • Efectivo
  • Tarjeta de crédito con el procesador de pago
{
  data: [
    {
      enabled: true,
      method_type: 'cash',
      processor_name: 'cash',
      specific_fields: null,
      input_schema: [],
      labels: [Object],
      exclude_cvv: false
    },
    {
      enabled: true,
      method_type: 'credit_card',
      processor_name: 'paymentez_credit',
      specific_fields: null,
      input_schema: [Array],
      labels: [Object],
      exclude_cvv: false
    }
  ]
}

Asignar un método de pago

Para el ejemplo se usara el segundo elemento de la lista de los métodos de pago que corresponde a tarjeta de crédito.

const paymentMethod = getPaymentMethods.data?.data[1]!;

Tarjeta de crédito

Si el elemento que se selecciono de la lista de métodos de pago es de tipo CreditCard deberás de enviar el siguiente payload con la información de la tarjeta de crédito.
Puedes encontrar datos de prueba de los procesadores integrados actualmente.

if (paymentMethod.method_type == PaymentMethodTypes.CreditCard) {
   const creditCard: CreditCard = {
     expiry_month: "06",
     expiry_year: "2025",
     card_holder: "Jhon Doe",
     card_holder_dni: "9999999999",
     card_number: "4242424242424242",
     card_cvv: "123",
     address1: "Calle 12 avenida 17",
     zip: "170129",
     city: "Quito",
     state: "Pichincha",
     country: "Ecuador",
     phone: "593999999999",
   };
   orderResp.setCreditCard(creditCard);
  }
 order.setPaymentMethod(paymentMethod);

Después deberás procesar el pago de la orden y verificar con OTP.

5. Verificar pago con OTP

Se enviara un código OTP al usuario y habrá que validarlo de la siguiente manera.

import { ErrorsCode } from "@d-una/checkout-sdk"

// The order is processed 
const { error } = await order.processPayment();

if (error) {
  // The error is verified as follows
  const requireCompleteWithOTP = error.code === ErrorsCode.CompleteOrderWithOTP
  
  if (requireCompleteWithOTP) {
    // Waiting for the user to enter the otp
    const userOTP = "012345";
    await order.verifyPaymentWithOTP(userOTP);
    }
  
  // Do something with the error
  return;
}

❗️

Si la llamada a verifyPaymentWithOTP es _succcesful _esto retornara la orden en la propiedad "order" y la propiedad error no tendrá un valor.

Verificar orden en el panel de administración

Listo. Si seguiste los pasos de manera correcta deberás poder ver la transacción en el panel de admin y tu código deberá verse del siguiente modo:

import { Address, Checkout, Environment, PaymentMethodTypes, CreditCard, ErrorsCode } from "@d-una/checkout-sdk";

async function Init() {
  const SDK = await Checkout.init({
    env: Environment.Staging,
    apiKey: "Tu api Key pública"
  });

  const { data, error } = await SDK.getOrderTokenized("Token de la orden");
  if (error) {
    console.warn(error.error);
    return;
  }
  const order = data!;
  order.setGuestEmail("[email protected]");
  const address: Address = {
    first_name: "Jhon",
    last_name: "Doe",
    phone: "+51943844652",
    identity_document: "123456789",
    lat: -0.190974,
    lng: -78.496911,
    address1: "Av. América 56, Quito 170129, Ecuador",
    address2: "Av. América 56, Quito 170129, Ecuador",
    city: "Quito",
    zipcode: "170129",
    state_name: "Pichincha",
    state_code: "EC",
    country: "Ecuador",
    address_type: "home",
    additional_description: "Cachan de la florita",
    is_default_address: true,
    is_last_address: false,
  };
    // If the order is of type pickup
  await order.setBillingAddress(address);

  // If the order is of type delivery
  // await order.setShippingRate(address);
  const getPaymentMethods = await SDK.getPaymentMethods();
  if (getPaymentMethods.error) {
    console.warn(getPaymentMethods.error!.error);
    return;
  }

  if (getPaymentMethods.data?.data.length == 0) {
    console.warn("Métodos de pago no configurados");
    return;
  }

  const paymentMethod = getPaymentMethods.data?.data[1]!;

  // If the item in the list of payment methods is CreditCard
  if (paymentMethod.method_type == PaymentMethodTypes.CreditCard) {
   const creditCard: CreditCard = {
      expiry_month: "06",
      expiry_year: "2025",
      card_holder: "Jhon Doe",
      card_holder_dni: "9999999999",
      card_number: "4242424242424242",
      card_cvv: "123",
      address1: "Calle 12 avenida 17",
      zip: "170129",
      city: "Quito",
      state: "Pichincha",
      country: "Ecuador",
      phone: "593999999999",
    };
    order.setCreditCard(creditCard);
  }
  // If the item in the list of payment methods is Cash
  // if (paymentMethod.method_type == PaymentMethodTypes.Cash) {
  //   Este método es opcional 
  //   order.setCashChange(50);
  // }
  order.setPaymentMethod(paymentMethod);
   // The order is processed 
  const { error } = await order.processPayment();

  if (error) {
    // The error is verified as follows
    const requireCompleteWithOTP = error.code === ErrorsCode.CompleteOrderWithOTP

    if (requireCompleteWithOTP) {
      // Waiting for the user to enter the otp
      const userOTP = "012345";
      await order.verifyPaymentWithOTP(userOTP);
    }

    // Do something with the error
    return;
  }
}

Init();
import { Address, Checkout, Environment, PaymentMethodTypes, CreditCard, OtpType, ErrorsCode } from "@d-una/checkout-sdk";

async function Init() {
  const SDK = await Checkout.init({
    env: Environment.Staging,
    apiKey: "Tu api Key pública"
  });

  const { data, error } = await SDK.getOrderTokenized("Token de la orden");
  if (error) {
    console.warn(error.error);
    return;
  }

  const order = data!;

  const userExist = await SDK.userExist("[email protected]")
  if(userExist.data?.success){
    // Una vez nos llegue el OTP a nuestro correo debemos comentar o eliminar esta linea 
    // await SDK.sendOtpToEmail('[email protected]'); 
    // return;
    const userToken = await SDK.loginWithOtp('[email protected]', '123456', OtpType.Email);
    if (userToken.error){
      console.warn(userToken.error!.error);
      return;
    }
    console.log(userToken.data);
  }
  else{
    console.warn(userExist.error!.error);
    return;
  }

  const address: Address = {
    id: 1,
    user_id: "COD_DATABASE_MERCHANT",
    first_name: "Jhon",
    last_name: "Doe",
    phone: "+51943844652",
    identity_document: "123456789",
    lat: -0.190974,
    lng: -78.496911,
    address1: "Av. América 56, Quito 170129, Ecuador",
    address2: "Av. América 56, Quito 170129, Ecuador",
    city: "Quito",
    zipcode: "170129",
    state_name: "Pichincha",
    state_code: "EC",
    country: "Ecuador",
    address_type: "home",
    additional_description: "Cachan de la florita",
    is_default_address: true,
    is_last_address: false,
    is_billing_address: true,
    created_at: new Date(),
    updated_at: new Date(),
  };

  await order.setBillingAddress(address);

  // Si la orden es de tipo delivery
  // await order.setShippingRate(address);
  const getPaymentMethods = await SDK.getPaymentMethods();
  if (getPaymentMethods.error) {
    console.warn(getPaymentMethods.error!.error);
    return;
  }

  if (getPaymentMethods.data?.data.length == 0) {
    console.warn("Métodos de pago no configurados");
    return;
  }

  const paymentMethod = getPaymentMethods.data?.data[1]!;

  if (paymentMethod.method_type == PaymentMethodTypes.CreditCard) {
    const creditCard: CreditCard = {
      expiry_month: "03",
      expiry_year: "2025",
      card_holder: "Guest",
      card_holder_dni: "488888888",
      card_number: "xxxxxxxx",
      card_cvv: "123",
      address1: "xxxx",
      zip: "1417",
      city: "xxx",
      state: "xxx",
      country: "xxx",
      phone: "+51943844652",
    };
    order.setCreditCard(creditCard);
  }
  // Si el elemento de la lista de métodos de pago es Efectivo
  // if (paymentMethod.method_type == PaymentMethodTypes.Cash) {
  //   Este método es opcional 
  //   order.setCashChange(50);
  // }
  order.setPaymentMethod(paymentMethod);

  // se procesa la orden 
  const { error } = await order.processPayment();

  if (error) {
    // se verifica que el error sea el siguiente
    const requireCompleteWithOTP = error.code === ErrorsCode.CompleteOrderWithOTP

    if (requireCompleteWithOTP) {
      // esperar que el usuario ingrese el otp
      const userOTP = "012345";
      await order.verifyPaymentWithOTP(userOTP);
    }

    // do something with the error
    return;
  }
}

Init();

Did this page help you?