Commercetools
Learn how to get started with our integration for commercetools.
Information
This guide assumes that you have already created a commercetools project. If you would like to test this integration, please contact partnerships.
Commercetools is an e-commerce platform that offers true cloud-native, headless commerce integration capabilities. The plugin makes it easier for those already using commercetools to integrate with Checkout.com's payment solutions.
Our integration has two parts:
- Configure our API Client in the commercetools Merchant Center.
- Set up the frontend, which involves integrating Frames for card payments and our Klarna SDK for Klarna payments.
Before you start
Create a test account
If you haven't already, create a test Checkout.com account.
Get your API keys
To set up our commercetools API Client, you'll need your public and secret API keys, which are generated automatically upon account creation.
- Log in to your test account on the Hub sandbox.
- In the left menu, go to Settings > Channels, and make a note of your secret and public API keys.
Configure webhooks
Information
Webhooks are notifications that we send when an event occurs on your account. For example, when a payment is captured. These are used by commercetools to update the status of an order. Read more about webhooks.
- Scroll down to the Webhooks section of the page and select New webhook.
- Enter the following URLs:
Webhook URL | Events |
---|---|
|
|
|
|
- Select API - v2.
- Select Create webhook.
Note
Correctly configuring your webhooks is important; if they're incorrectly formatted, our API Client will not work.
How webhooks interact with commercetools
When a webhook is triggered on our side, our integration is creating or updating a transaction in commercetools to reflect the change.
These transactions are attached to a payment, and there may be multiple transactions attached to a single payment. This is all done automatically, and you don't have to do anything other than setting up the webhooks and configuring the API client.
You can see these interactions in your commercetools Merchant Center by going to Order list > Order and selecting the Payment tab.
Webhook | Transaction created or updated? | Transaction name | New status of the transaction (if needed) |
---|---|---|---|
| Created | Authorization | Success |
| Created | Authorization | Failure |
| Created | Authorization | Pending |
| Created or updated | Charge | Success |
| Created | Charge | Pending |
| Created | Charge | Failure |
| Created or updated | Refund | Success |
| Created | Refund | Pending |
| Created or updated | Refund | Failure |
| Created | Authorization canceled | Success |
| Created | Authorization canceled | Failure |
| Created or Updated | Authorization | Failure |
| Created or Updated | Authorization | Failure |
Information
We do not automatically update the order or payment status. This allows you to build your own order flow.
Configure API Client
Follow the steps below to create and configure the Checkout.com API Client on your commercetools site.
- Log in to the commercetools Merchant Center, go to Settings > Developer Settings and select Create API Client.
- Enter a name for this new API Client (e.g., cko-payment-integration).
- Select the following scopes:
- Manage: Orders
- Manage: Payments
- Select Create API Client.
- Copy the following details from the window displayed, and reach out to our Support team at support@checkout.com to assist you with onboarding:
- project_key
- client_id
- secret
- API URL
- Auth URL
Information
You must save this information, as it is only displayed once.
- Using commercetools' IMPEX, set
Types
asendpoint
, andcreate
ascommand
. Then copy and paste in the following JSON files to install them (make sure you're in the right project when doing this):
1{2 "key": "ctp-cko-integration-interaction",3 "name": {4 "en": "Checkout.com Interaction"5 },6 "resourceTypeIds": ["payment-interface-interaction"],7 "fieldDefinitions": [8 {9 "name": "responseCode",10 "label": {11 "en": "Response Code"12 },13 "required": true,14 "type": {15 "name": "String"16 },17 "inputHint": "SingleLine"18 },19 {20 "name": "responseSummary",21 "label": {22 "en": "Response Summary"23 },24 "required": true,25 "type": {26 "name": "String"27 },28 "inputHint": "SingleLine"29 },30 {31 "name": "id",32 "label": {33 "en": "Action Id"34 },35 "required": true,36 "type": {37 "name": "String"38 },39 "inputHint": "SingleLine"40 }41 ]42}
1{2 "key": "ctp-cko-integration-payment",3 "name": { "en": "Saved Payment Instrument" },4 "description": { "en": "Stores customer saved payments" },5 "resourceTypeIds": ["payment"],6 "fieldDefinitions": [7 {8 "name": "paymentInstrumentId",9 "type": { "name": "String" },10 "required": false,11 "label": { "en": "Payment Instrument" },12 "inputHint": "SingleLine"13 }14 ]15}
Set up the frontend
Next, set up the frontend part of our commercetools integration.
- Integrate Frames to accept card payments.
- Add our Klarna SDK (follow steps 2 and 3 on that page; we'll take care of the rest) to support Klarna payments.
If you are planning to accept SEPA payments, before any payment can occur, your customer must authorize the payment by accepting the terms of the mandate. By accepting, they are authorizing you to collect the specified amount from their bank account using SEPA Direct Debit. See Issue the mandate for more information
1// create context2const createContext = async ({ public_key, reference }) => {3 const data = await fetch(`https://commercetools.integration.checkout.com/api/contexts`, {4 method: 'post',5 headers: {6 'content-type': 'application/json',7 authorization: public_key8 },9 body: JSON.stringify({ reference })10 }).then(res => res.json())11 return data12}13
14// create payment15const createPayment = async args => {16 const { token, public_key, context_id, success_url, failure_url, save_payment_instrument } = args17 const data = await fetch(`https://commercetools.integration.checkout.com/api/payments`, {18 method: 'post',19 headers: {20 'content-type': 'application/json',21 authorization: public_key22 },23 body: JSON.stringify({24 type: 'token',25 token,26 context_id,27 '3ds': args['3ds'],28 success_url,29 failure_url,30 save_payment_instrument31 })32 })33 const body = await data.json()34 return {35 success: data.status >= 200,36 redirectUrl: body.redirect_url37 }38}39
40// Credit card Frames initialization41Frames.init({42 publicKey: config.cko.publicKey,43 cardValidationChanged: function () {44 console.log('CARD_VALIDATION_CHANGED: %o', event)45 payButton.disabled = !Frames.isCardValid()46 },47 cardTokenized: async data => {48 console.log('CARD_TOKENIZATION: %o', data)49 const paymentSuccess = await createContext({50 public_key: config.cko.publicKey,51 reference: order ? order.id : cart.id52 }).then(context =>53 createPayment({54 public_key: config.cko.publicKey,55 token: data.token,56 context_id: context.id,57 save_payment_instrument: true, // only works for if users is registered58 '3ds': {enabled: true | false}, // ability to send 3ds flag for a request (ideally configured through Hub, use only for testing)59 success_url: `https://example.com/3ds-success.html`, // ability to configure 3ds redirect60 failure_url: `https://example.com/3ds-error.html` // ability to configure 3ds redirect61 })62 )63
64 if (!paymentSuccess) {65 return console.error('Create payment error', payment)66 }67
68 const order = await createOrder()69
70 if (!order) {71 console.error('Create order error', order)72 return73 }74
75 window.location.href = `/confirmation.html?orderId=${order.id}`76 },77 cardTokenizationFailed: function (data) {78 console.log('CARD_TOKENIZATION_FAILED: %o', data)79 }80})81
82Frames.addEventHandler(Frames.Events.FRAME_ACTIVATED, () => window.dispatchEvent(paymentFormRendered))83
84form.addEventListener('submit', async event => {85 event.preventDefault()86 Frames.submitCard()87})88
89// klarna90const paymentSuccess = await createContext({91 public_key: config.cko.publicKey,92 reference: order ? order.id : cart.id93}).then(context => {94 const reference = order.id : cart.id95
96 const apm = context.apms.find(a => a.name === 'klarna')97 const container = document.getElementById('payment-klarna')98 const buyWithKlarna = document.getElementById('payment-method-klarna')99 // button is disabled by default100 const payWithKlarna = document.getElementById('pay-klarna')101
102 buyWithKlarna.addEventListener(103 'click',104 () => {105 Klarna.Payments.authorize(106 // options107 {108 instance_id: context.id // Same as instance_id set in Klarna.Payments.load().109 },110 // data111 {},112 // callback113 response => {114 console.log('klarna payments authorize', response)115 buyWithKlarna.classList.add('hidden')116 payWithKlarna.classList.remove('hidden')117 // show button to pay with klarna now118 payWithKlarna.addEventListener('click', async () =>119 // pay120 createPayment({ type: apm.name, token: response.authorization_token, contextId: context.id })121 )122 }123 )124 },125 false126 )127
128 Klarna.Payments.init({129 client_token: apm.metadata.details.client_token130 })131
132 Klarna.Payments.load(133 // show the klarna component134 {135 container: '#klarna_container',136 payment_method_categories: apm.metadata.details.payment_method_category.map(cat => cat.identifier),137 instance_id: context.id138 },139 // use data from session140 apm.metadata.session,141 // callback142 function (response) {143 console.log('klarna payments load', response)144 // ...145 }146 )147})
Make a payment
Now that you've set up the integration, you're ready to make a payment. You can make a payment in two steps:
- Create context
- Request payment
Create context
First, create a payment context. This returns the available payment options to the customer, and gives you a context_id
, with which you can then request a payment.
Expand the table below to see how our properties map to commercetools' properties.
Note, the reference property in commercetools refers to the cart or order ID.
Checkout.com | commercetools | Notes |
---|---|---|
required |
| You will get an error if |
required | n/a | Set to zero because commercetools applies discounts across line items. |
required |
| You will get an error if |
required |
| |
required |
| You will get an error if |
optional |
| |
optional |
| |
optional |
| |
optional |
| |
optional |
| |
required |
| |
optional |
| |
optional |
| |
optional |
| |
optional |
| |
optional |
| |
optional |
| |
required |
| |
optional | n/a | Not set if |
required |
| |
optional |
| |
required |
| Uses the language of the order country if present. Defaults to English if no country is included. |
required |
| |
required |
| |
required |
| You will get an error if |
required | ( | The value is calculated from the difference between the total gross (includes discount) and the item total price (excludes discount). |
Tip
We recommend that you create a context when your payment options page loads, and reload it if the customer makes a change to their basket or details.
Endpoint
https://commercetools.integration.checkout.com/api/contexts
Header parameters
Header | Value |
---|---|
required |
|
required |
|
Body parameters
Field name | Description |
---|---|
string required | The commercetools cart or order ID. |
string optional | The customer's email.
|
Request payment
Creating the context above will give you a context_id
. Use this to request a payment with the following endpoint.
The commercetools integration currently supports the following payment methods:
- Card
- iDEAL
- Sofort
- Klarna
- PayPal
Endpoint
https://commercetools.integration.checkout.com/api/payments
Header parameters
Header | Value |
---|---|
required |
|
required |
|
Body parameters
Field name | Description |
---|---|
string required | The type of payment method. Set this to |
string required | The ID of the payment context created above. |
string required | The Checkout.com token. |
string optional | The three-digit (or four digits for Amex) card verification value/code. |
boolean optional | Allows you to save the payment method for future use. |
object optional | Allows you to select whether the transaction should be 3D Secure authenticated. |
boolean required | Required if the |
string optional | Indicates the preference for whether or not a 3DS challenge should be performed. The customer’s bank has the final say on whether or not the customer receives the challenge. Default: Possible values:
For more information about SCA, please refer to the SCA compliance guide. |
string optional | A reference you can use to later identify the payment. This populates the reference field in the Hub
|
string optional | The URL to which the customer will be redirected if the payment is successful. |
string optional | The URL to which the customer will be redirected if the payment fails. |
Manage saved payment instruments
The following endpoints allow you to retrieve a customer's saved payment instruments or delete them.
Retrieve saved payment instruments
Use this endpoint to return a list of a customer's saved payment instruments.
Endpoint
https://commercetools.integration.checkout.com/api/merchants/{public_key}/customers/{customer_id}
Header and path parameters
Header | Value |
---|---|
required |
|
required |
|
Path | Description |
---|---|
required | Your Checkout.com public key. You can find this in the Hub. |
required | The customer's commercetools ID. |
Delete a saved payment instrument
Use the endpoint below to delete a customer's saved payment instrument.
Endpoint
https://commercetools.integration.checkout.com/api/merchants/{public_key}/customers/{customer_id}/payment-instruments/{payment_instrument_id}
Header and path parameters
Header | Value |
---|---|
required |
|
required |
|
Path | Description |
---|---|
required | Your Checkout.com public key. You can find this in the Hub. |
required | The customer's commercetools ID. |
required | The unique identifier of the saved payment instrument. |
Postman collection
For more testing, commercetools have created a Postman collection.