Ouvrir le paiement par carte virtuelle Affirm

Aperçu

Starting a payment with Affirm on the web with a virtual card consists of creating a checkout form, tokenizing customer information securely, and generating a virtual card. You can then process the card through your existing payment gateway.

Ce guide vous démontre la manière d'inclure Affirm.js et Affirm Checkout sur votre page web pour créer une carte virtuelle Affirm.


Étapes de mise en œuvre

Étape 1 : Mise en place d'Affirm.js

Include the following script in the head section on every page on your site. This script should always be loaded directly from the Affirm domain.

🚧

Utilisez uniquement les clés API et le domaine Sandbox à des fins de test et de développement

This ensures that you don't accidentally modify your live transactions. Affirm does not generate real virtual cards in the sandbox environment. If applicable, please work with your technical account manager on live testing.

<script>
const _affirm_config = {
		public_api_key: "YOUR_PUBLIC_API_KEY", /* replace with public api key */
		script: "https://cdn1-sandbox.affirm.com/js/v2/affirm.js",
		locale: "en_US",
		country_code: "USA",
	};

(function(m,g,n,d,a,e,h,c){var b=m[n]||{},k=document.createElement(e),p=document.getElementsByTagName(e)[0],l=function(a,b,c){return function(){a[b]._.push([c,arguments])}};b[d]=l(b,d,"set");var f=b[d];b[a]={};b[a]._=[];f._=[];b._=[];b[a][h]=l(b,a,h);b[c]=function(){b._.push([h,arguments])};a=0;for(c="set add save post open empty reset on off trigger ready setProduct".split(" ");a<c.length;a++)f[c[a]]=l(b,d,c[a]);a=0;for(c=["get","token","url","items"];a<c.length;a++)f[c[a]]=function(){};k.async=
  !0;k.src=g[e];p.parentNode.insertBefore(k,p);delete g[e];f(g);m[n]=b})(window,_affirm_config,"affirm","checkout","ui","script","ready","jsReady");
</script>

See supported locale and country codes.

After you add the script above, a defined instance of Affirm is created on your client. You will gain access to methods within the Affirm object to trigger multiple actions.


Step 2: Create the Checkout Object

When a customer chooses Affirm to pay for a purchase, a checkout object containing the order details is created with affirm.checkout.open_vcn() so that Affirm can render the checkout flow. When the customer completes their purchase, you must handle the callbacks or leverage redirects. See below for a sample checkout object:

const checkoutObject = {
  merchant: {
    user_confirmation_url: 'https://merchantsite.com/confirm',
    user_cancel_url: 'https://merchantsite.com/cancel',
    user_confirmation_url_action: 'POST',
    name: 'Your Customer-Facing Merchant Name',
    use_vcn: true,
  },
  shipping: {
    name: {
      first: 'Joe',
      last: 'Doe',
    },
    address: {
      street1: '633 Folsom St',
      street2: 'Floor 7',
      city: 'San Francisco',
      state: 'CA',
      zipcode: '94107',
      country: 'USA',
    },
    phone_number: '4153334567',
    email: '[email protected]',
  },
  billing: {
    name: {
      first: 'Joe',
      last: 'Doe',
    },
    address: {
      street1: '633 Folsom St',
      street2: 'Floor 7',
      city: 'San Francisco',
      state: 'CA',
      zipcode: '94107',
      country: 'USA',
    },
    phone_number: '4153334567',
    email: '[email protected]',
  },
  items: [
    {
      display_name: 'Awesome Pants',
      sku: 'ABC-123',
      unit_price: 10000,
      qty: 3,
      item_image_url: 'http://merchantsite.com/images/awesome-pants.jpg',
      item_url: 'http://merchantsite.com/products/awesome-pants.html',
      categories: [
        ['Apparel', 'Pants'],
        ['Mens', 'Apparel', 'Pants'],
      ],
    },
  ],
  discounts: {
    RETURN5: {
      discount_amount: 500,
      discount_display_name: 'Returning customer 5% discount',
    },
    PRESDAY10: {
      discount_amount: 1000,
      discount_display_name: "President's Day 10% off",
    },
  },
  metadata: {
    shipping_type: 'UPS Ground',
    mode: 'modal',
  },
  order_id: 'JKLMO4321',
  currency: 'USD',
  financing_program: 'zero_pct_promo',
  shipping_amount: 1000,
  tax_amount: 600,
  total: 30100,
};

affirm.checkout.open_vcn(checkoutObject)

For additional information, see Checkout Object or the Checkout Object recipe linked below.


Arguments de méthode

MéthodeType de donnéesDescription
checkoutObject requiredobjetL'objet contenant les données du paiement du client. Voir les détails.

🚧

Note:

  • Our virtual card product only supports modal mode. The Affirm checkout opens in a modal that floats on top of your checkout page. This is indicated in the checkout object when setting the mode parameter to modal.
  • Définissez le paramètre use_vcn sur true pour que les détails de la carte soient générés à l'origine du prêt.
  • affirm.checkout() valide les données requises dans l'objet checkout.

Step 3: Launch Checkout and Handle Callbacks

After you create the checkout object, you can launch the Affirm checkout modal using the affirm.checkout.open_vcn() function. When the customer confirms their Affirm loan, we send a javascript callback on success or on error, depending on the outcome. In the event of a successful checkout, you can retrieve the card details and the checkout_id from the callback.

🚧

Note:

If you don't want to retrieve the card details from the client-side, we can pass them back via the server-side only using our Read Card API (for PCI reasons). Contact Merchant Help for further information.

Retours

Returns callbacks that resolve in a:

  • card_checkout: un objet de carte a bien été créé.
  • error_response: Une erreur s'est produite. Inclut le checkout_id de la tentative et le reason pour laquelle elle a échoué.
  • checkout_validation_error: Une erreur de validation s'est produite avec la requête de paiement envoyée.
affirm.checkout.open_vcn({
      success: function(card_checkout) {
         console.log(card_checkout);
      },
      error: function(error_response) {
        console.log(error_response);
      },
      onValidationError: function(checkout_validation_error) {
      console.log(checkout_validation_error)
    }
 });

Récupération des détails complets de la carte via un success callback

{
    billing_address: {
        city: "San Francisco",
        line1: "650 California St.",
        line2: "12th Floor",
 		state: "CA",
        zipcode: "94108"
    },
   callback_id: "b67350e8-ad14-4844-8230-adc6e5f3e490",
   cardholder_name: "AffirmInc John Doe",
   charge_ari: "GDC3-MKAG",
   checkout_token: "RTKS63U383SZ9GY7",
   created: "2023-05-18T16:10:57.300017",
   cvv: "123",
   expiration: "0122",
   id: "RTKS63U383SZ9GY7",
   number: "4111111111111111"

Rappel de succès alternatif : Omettez les détails de la carte et récupérez le checkout_token du côté client, et obtenez les détails de la carte via votre serveur

{
  callback_id: "b67350e8-ad14-4844-8230-adc6e5f3e490",
  charge_ari: "GDC3-MKAG",
  checkout_token: "RTKS63U383SZ9GY7",
  created: "2023-05-18T16:10:57.300017",
  id: "RTKS63U383SZ9GY7"
}

Step 4: Card Management

When you receive the card details from the checkout response or Read Card API, you can submit authorizations, captures, and refunds to the virtual card using your existing payment rails.


FAQ

🚩

Resolving "affirm.checkout.open_vcn is not a function" Error in VCN Integration

Q: How do I fix the error "affirm.checkout.open_vcn is not a function" when using Affirm's checkout methods?

R : Cette erreur se produit généralement lorsque le script Affirm n'a pas été entièrement chargé avant que les méthodes caisse et open_vcn ne soient appelées. Pour résoudre ce problème, intégrez les appels aux méthodes Affirm Checkout et open_vcn dans la méthode affirm.ui.ready. Vous trouverez ci-dessous une solution qui a aidé de nombreux commerçants :

affirm.ui.ready(function() {
  affirm.checkout(checkoutObj);
  affirm.checkout.open_vcn({
      success: function(card_checkout) {
          //On successful loan confirmation Affirm will trigger this function
          //This function will be used to pass CC number to your CC processor
          //You will need to handle redirecting to a success page here as well
          console.log(card_checkout);
      },
      error: function(error_response) {
          //On Cancel or decline Affirm will trigger the following function
          //You will need to handle redirecting to an error page here
          console.log(error_response);
      }
  });
});

In this solution, the success function is used for processing successful loan confirmations, including passing credit card details to your processor and redirecting to a success page. The error function handles cancellations or declines by redirecting to an error page. This workaround ensures that Affirm's methods are only called after the script is fully loaded, effectively preventing the error.