Vue Storefront is now Alokai! Learn More
Commercetools: Quickstart

Commercetools: Quickstart

Like the Adyen Integration, this guide is framework-agnostic. The examples focus on the integration. Use whatever conventions your framework uses.

Prerequisites

Before you start, make sure you have a project that meets the following requirements:

1

Install

Install packages inside middleware directory.

yarn
yarn add @vue-storefront/sdk @vsf-enterprise/adyen-commercetools-api
# yarn add @vue-storefront/sdk @vsf-enterprise/adyen-sfcc-api

Install packages frontend application directory.

yarn
yarn add @vue-storefront/sdk @vsf-enterprise/adyen-commercetools-sdk
# yarn add @vue-storefront/sdk @vsf-enterprise/adyen-sfcc-sdk

2

Configuration For Commercetools

  1. Add Adyen configuration to your middleware.config.ts
middleware.config.js
// storefront-middleware/middleware.config.ts
import { config as adyenConfig } from "./integrations/adyen";

export const config = {
  integrations: {
    // ...
    adyen: adyenConfig,
  },
};
  1. Add Adyen configuration file
// storefront-middleware/integrations/adyen/config.ts
import { TOnRedirectBack } from "@vsf-enterprise/adyen-commercetools-api";

const onRedirectBack: TOnRedirectBack = async ({ config }, { ct }, cart) => {
  console.log("CUSTOM ON REDITECT BACK");
  const order = await ct.orders.create(cart);
  const url = new URL(
    `/order/success?orderId=${order.id}&redirect_status=succeeded`,
    config.origin,
  );
  return url.toString();
};

export const config = {
  location: "@vsf-enterprise/adyen-commercetools-api/server",
  configuration: {
    ctApi: {
      apiHost: '<CT_HOST_URL>',
      authHost: '<CT_AUTH_URL>',
      projectKey: '<CT_PROJECT_KEY>',
      clientId: '<CT_CLIENT_ID>',
      clientSecret: '<CT_CLIENT_SECRET>',
      scopes: ['manage_payments:<ADYEN_PROJECT_IDENTIFIER>', 'manage_orders:<ADYEN_PROJECT_IDENTIFIER>', 'view_types:<ADYEN_PROJECT_IDENTIFIER>']
    },
    adyenApiKey: '<ADYEN_API_KEY>',
    adyenMerchantAccount: '<ADYEN_MERCHANT_ACCOUNT>',
    adyenEnvironment: "TEST",
    returnUrl: "http://localhost/api/adyen/redirectBack",
    origin: "http://localhost",
    integrationName: "adyen",
    partialPaymentTTL: 60 * 1000,
    onRedirectBack,
  },
};

If your Adyen instance is running in production and taking payments, then you also need to pass buildCustomAdyenClientParameters. It's a function for overwriting object used to instantiate Client from @adyen/api-library. Mostly all you need to is pass what you get and append liveEndpointUrlPrefix as such:

adyen: {
  location: '@vsf-enterprise/adyen-commercetools-api/server',
  configuration: {
    // ...
    buildCustomAdyenClientParameters(params) {
      return {
        ...params,
        liveEndpointUrlPrefix: "YOUR_LIVE_URL_PREFIX"
      }
    }
  }
},

Coming back from redirect based payment method

When user comes back from redirect based payment method they land on our /redirectBack endpoint. There we submits additional information related to performed payment and redirects where onRedirectBack function told us to.

This is the body of default onRedirectBack implementation:

// storefront-middleware/integrations/adyen/config.ts
import type { TOnRedirectBack } from "@vsf-enterprise/adyen-commercetools-api";

const onRedirectBack: TOnRedirectBack = async ({ config }, { ct }, cart) => {
  const order = await ct.orders.create(cart);
  const url = new URL(
    `/order/success?orderId=${order.id}&redirect_status=succeeded`,
    config.origin,
  );
  return url.toString();
};

export const config = {
  location: "@vsf-enterprise/adyen-commercetools-api/server",
  configuration: {
    // ...
    onRedirectBack,
  },
};

Feel free to adjust it and register own implementation using onRedirectBack property in storefront-middleware/integrations/adyen/config.ts.

3

Register SDK module for Adyen commercetools

sdk/sdk.config.ts
// ...
import { adyenCtModule } from '@vsf-enterprise/adyen-commercetools-sdk';

export const { getSdk } = createSdk(
  options,
  ({ buildModule, middlewareModule, middlewareUrl, getRequestHeaders, defaults }) => {
    return {
      // ...
      adyen: buildModule(
        adyenCtModule, {
          apiUrl: `${middlewareUrl}/adyen`,
          adyenClientKey: 'test_******',
          adyenEnvironment: 'test',
        }
      )
    };
  },
);

4

Create Payment Component/Page For Commercetools

Add the payment-element to the template, to achieve this we can create simple component with element inside.

Create client component.

// storefront-unified-nextjs/components/payment.tsx
'use client';

export default function PaymentElement() {
  return <div id="adyen-payment-element" />;
}

This component can be used inside

// storefront-unified-nextjs/app/[locale]/layout.tsx
//..
import PaymentElement from '@/components/payment.tsx';

export default async function RootLayout({ children, params: { locale } }: RootLayoutProps) {
  // ..

  return (
    <html lang={locale}>
      <head>
        <link href="res.cloudinary.com" rel="preconnect" />
      </head>
      <body className={classNames(fontHeadings.variable, fontBody.variable, 'font-body')}>
        // ..
        <PaymentElement/>
      </body>
    </html>
  );
}

Prepare logic responsible for handling payment, and call it:

function mapPaymentMethodsResponse(getPaymentMethodsResponse: GetPaymentMethodsResponse) {
  return {
    paymentMethods: getPaymentMethodsResponse.paymentMethods,
    ...(getPaymentMethodsResponse.storedPaymentMethods
      ? {
          storedPaymentMethods: getPaymentMethodsResponse.storedPaymentMethods,
        }
      : {}),
  };
}

async function createAdyenDropin({ shopperLocale }) {
  let getPaymentMethodsResponse = await sdk.adyen.getPaymentMethods({ shopperLocale });
  let balanceCheckResponse: BalanceCheckResponse | null;
  async function handleResult(
    checkout: { update: Function },
    result: MakePaymentResponse | SubmitDetailsResponse,
    dropin: { unmount: Function; handleAction: Function },
  ) {
    if (['Refused', 'Cancelled', 'Error'].includes(result.resultCode!)) {
      // Handling negative result codes and unmounting the Adyen Drop-in
      // To allow the user to try again by recreating session and component
      dropin.unmount();
      // Show some meaningful error message
      return await createAdyenDropin();
    } else if ('action' in result && result.action) {
      // @ts-ignore: next-line
      return dropin.handleAction(result.action);
    } else if (result.order && result.order?.remainingAmount?.value && result.order?.remainingAmount?.value > 0) {
      getPaymentMethodsResponse = await sdk.adyen.getPaymentMethods({ shopperLocale });

      checkout.update({
        paymentMethodsResponse: mapPaymentMethodsResponse(getPaymentMethodsResponse),
        order: getPaymentMethodsResponse.order,
        amount: result.order.remainingAmount,
      });
      return result;
    } else {
      // Here put a code to place an order and redirect to success page.
      console.log({...data})
      return result;
    }
  }

  function createOnOrderCancel(checkout: { update: Function }) {
    return async function onOrderCancel(order: CancelOrderParams) {
      await sdk.adyen.cancelOrder(order);
      getPaymentMethodsResponse = await sdk.adyen.getPaymentMethods({ shopperLocale });
      checkout.update({
        paymentMethodsResponse: mapPaymentMethodsResponse(getPaymentMethodsResponse),
        amount: {
          value: getPaymentMethodsResponse.payment.amountPlanned.centAmount,
          currency: getPaymentMethodsResponse.payment.amountPlanned.currencyCode,
        },
        order: undefined,
      });
    };
  }

  const { checkout } = await sdk.adyen.mountPaymentElement({
    getPaymentMethodsResponse,
    locale: 'en-US',
    order: getPaymentMethodsResponse.order,
    paymentDOMElement: '#adyen-payment-element',
    adyenConfiguration: {
      paymentMethodsConfiguration: {
        card: {
          enableStoreDetails: true
        },
        giftcard: {
          async onBalanceCheck(resolve, reject, data) {
            balanceCheckResponse = await sdk.adyen.balanceCheck({
              ...data,
              paymentId: getPaymentMethodsResponse.payment.id,
            });
            resolve(balanceCheckResponse);
          },
          async onOrderRequest(resolve, reject, data) {
            sdk.adyen
              .createOrder({
                ...data,
                paymentId: getPaymentMethodsResponse.payment.id,
              })
              .then(resolve)
              .catch(reject);
          },
          async onOrderCancel(order) {
            const onOrderCancel = createOnOrderCancel(checkout);
            await onOrderCancel(order);
          },
        },
      },
      async onSubmit(state, dropin) {
        const result = await sdk.adyen.makePayment({
          paymentId: getPaymentMethodsResponse.payment.id,
          componentData: state.data,
          ...(balanceCheckResponse?.resultCode === 'NotEnoughBalance'
            ? {
                balance: balanceCheckResponse.balance,
              }
            : {}),
        });
        balanceCheckResponse = null;
        await handleResult(checkout, result, dropin);
      },
      async onAdditionalDetails(state, dropin) {
        const result = await sdk.adyen.submitDetails({
          paymentId: getPaymentMethodsResponse.payment.id,
          componentData: state.data,
        });
        await handleResult(checkout, result, dropin);
      },
    },
    dropinConfiguration: {
      showRemovePaymentMethodButton: true,
      async onOrderCancel(order) {
        const onOrderCancel = createOnOrderCancel(checkout);
        await onOrderCancel(order);
      },
      async onDisableStoredPaymentMethod(recurringDetailReference, resolve, reject) {
        sdk.adyen.removeCard({ recurringDetailReference }).then(resolve).catch(reject);
      },
    },
  });
}

// Call it client-side, e.g. in Nuxt it would be inside onMounted
const shopperLocale = 'en-US'; // https://docs.adyen.com/api-explorer/Checkout/71/post/paymentMethods#request-shopperLocale
await createAdyenDropin({ shopperLocale });

This snippet has placeholder to inject logic responsible for placing an order. You can find it easily by looking for the following string and replacing it with your code for placing an order. // Here put a code to place an order and redirect to success page.

If you are using redirect-based payments, there is an additional step required.

React in strict mode in development calls useEffect(fn, []); twice. This can break Adyen Drop-in. Please make sure you call createAdyenDropin only once.

Make sure you passed shopperLocale to the createAdyenDropin function in order to have Adyen Drop-in in expected language.

5

Extend commercetools cart/order type

In commercetools, a cart and an order share a single type because at some point cart is transformed to the order. The name of the shared type is order. We are going to extend this shared type because...

Adyen creates a wrapper for payment partials. To make it accessible after refresh of website or outside of user's session, we had to store it somewhere. Our pick is an extended commercetools' order type.

Fortunately, you do not need to create every cart using this type, we will convert type of the cart when it's necessary (making partial payment).

In order to register extended order type:

  1. Open API Playground,
  2. Make sure you've selected your desired project in the select input placed inside the page's header,
  3. Set:
  • Endpoint as Types,
  • Command as Create,
  • Payload as:
{
  "key": "ctcart-adyen-integration",
  "name": {
    "en": "commercetools Adyen integration cart custom type to support partial payments"
  },
  "resourceTypeIds": ["order"],
  "fieldDefinitions": [
    {
      "name": "adyenOrderData",
      "label": {
        "en": "adyenOrderData"
      },
      "type": {
        "name": "String"
      },
      "inputHint": "SingleLine",
      "required": false
    },
    {
      "name": "adyenOrderPspReference",
      "label": {
        "en": "adyenOrderPspReference"
      },
      "type": {
        "name": "String"
      },
      "inputHint": "SingleLine",
      "required": false
    },
    {
      "name": "adyenOrderRemainingAmountValue",
      "label": {
        "en": "adyenOrderRemainingAmountValue"
      },
      "type": {
        "name": "Number"
      },
      "inputHint": "SingleLine",
      "required": false
    },
    {
      "name": "adyenOrderRemainingAmountCurrency",
      "label": {
        "en": "adyenOrderRemainingAmountCurrency"
      },
      "type": {
        "name": "String"
      },
      "inputHint": "SingleLine",
      "required": false
    }
  ]
}
  1. Click Go!!! button.

Did you already extended commercetools' order type?

It is possible that your application is already extending order type and you cannot stop using it. In that case, we recommend adding fields from our type and add them to your custom type. Then in middleware config add type's key as a value of customOrderType optional property.

adyen: {
  location: '@vsf-enterprise/adyen-commercetools-api/server',
  configuration: {
    // ...
    customOrderType: 'keyOfMyCustomType'
  }
},

Validation

The integration will check on start up of middleware server if type exists and it has fields used by integration. If validation fails then it stops the middleware from running at all to prevent runtime payment-related critical errors.

6

Setup webhook

Unfinished partial payments expire after some time. To elegantly handle it, we need to setup webhook to shoot in adyen integration's endpoint prepared for it.

Start from registering new webhook in Adyen's dashboard. URL should be equal:

https://my-alokai-frontend.local/api/adyen/webhookCancelOrder

Where adyen is equal a value of integrationName property from middleware config.

Method - JSON.
Encryption protocol - TLSv1.3.
Events - select only ORDER_CANCEL.
Additional settings - select only Include a success boolean for the payments listed in an ORDER_CLOSED event.

Save configuration.

Verifying HMAC signature

In order to prevent fraud requests to the endpoint, it is recommended to enable verifying HMAC signature. To do that, edit created webhook in Adyen's dashboard, Generate a new HMAC key, save configuration and copy generated key, as we will need it soon.

Then adjust a middleware config:

// ...
adyen: {
  location: '@vsf-enterprise/adyen-commercetools-api/server',
  configuration: {
    // ...
    enableHmacSignature: true,
    secretHmacKey: '<PASTE_HMAC_KEY_COPIED_FROM_ADYEN_DASHBOARD>'
  }
},
// ...

7

Setup commercetools-payment-to-order-processor

Some payment methods, like Klarna, certain 3DS authenticated cards, and Sofort, are redirect-based. This means there's a chance the user might lose connection or accidentally close the tab after payment but before returning to the return url. In such scenarios, a payment is successful, but no order is placed.

To address this issue, use the commercetools-payment-to-order-processor provided by commercetools. This service checks for the aforementioned situations at set intervals. If it identifies any matches, it will call a URL you specify, with the cartId attached as a query parameter. You must then set up an endpoint to create an order and provide the appropriate HTTP response. To understand this further, review the documentation in their repository.

Consider enhancing our middleware by adding an endpoint to create orders. Alternatively, you could design a straightforward Node.js service and deploy it as an auxiliary application in our cloud. Choose whichever approach you prefer, but ensure the endpoint is shielded from unauthorized access.

8

Enjoy your new Adyen integration!