Node.js SDK
Introduction
To understand how to use this SDK it is best to read the following documentation:
- Server Introduction
First read the Server Introduction to familiarize yourself with the various concepts. - Server API Reference
This Server SDK wraps the Server API and (amongst other things) exposes the responses of the webservice calls as JavaScript objects. Understanding the Server API will help you understanding these SDK objects as well. - This current document will help you understand the global flow when interacting with the Worldline platform using the Node.js SDK.
The Node.js SDK helps you to communicate with the Server API. More specifically, it offers a fluent Node.js API that provides access to all the functionality of the RESTful Server API. Below, we discuss the following topics in detail.
- Initialization of the SDK
- Payments
- File Service support
- Idempotent requests
- Errors
- Logging
- Advanced use: Customization of the communication
- Webhooks
The source code of the SDK and an example app are available on Github . There you can find installation instructions.
The API documentation of the latest version of the SDK is available here . For a specific major version, replace latest with <major>.x. Note that this is only available for versions 5.x and later. For version 4.x use this URL instead.
Initialization of the Node.js SDK
All JavaScript code snippets presented in the API reference assume you have initialized the Node.js SDK before using them in your Development Environment. This section details the initialization of the Node.js SDK.
Initializing is simple, and requires only one key task: use our connect-sdk-nodejs package to create an instance of Client, which contains the actual methods to communicate with the Server API.
The Client needs the following input
- The host, scheme and port to which you connect. See API endpoints for the possible hosts.
- The secretApiKey and apiKeyId. The secretApiKey is a key that is used to authenticate your API requests, and apiKeyId identifies that key (as you can have multiple active keys). Both of these can be obtained from the Account Setup tab of the Configuration Center, and are available only if you are administrator.
- The name of the integrator, e.g. your company name.
- Optional logging properties.
import * as connectSdk from "connect-sdk-nodejs";
const client = connectSdk.init({
host: "[hostname.of.the.api]",
scheme: "https",
port: 443,
enableLogging: true, // defaults to false
logger: logger, // if undefined console.log will be used
apiKeyId: "[your-api-key-id]",
secretApiKey: "[your-secret-api-key]",
integrator: "[your-company-name]"
});
If a proxy should be used, the input should additionally contain a proxy property:
const client = connectSdk.init({
host: "[hostname.of.the.api]",
scheme: "https",
port: 443,
enableLogging: true, // defaults to false
logger: logger, // if undefined console.log will be used
apiKeyId: "[your-api-key-id]",
secretApiKey: "[your-secret-api-key]",
integrator: "[your-company-name]",
proxy: {
host: "[hostname.of.the.proxy]",
scheme: "http",
port: 3128,
credentials: "[username.for.the.proxy]:[password.for.the.proxy]"
}
});
Only the nested host property is required; the scheme and port properties default to http and 3128 respectively, and the credentials property can be omitted if no proxy authentication is needed.
Payments
As a merchant, your core interaction with Worldline typically starts when your customer clicks the checkout button in your application. The payment process usually has the following steps:
- Payment Product selection
- Setting of available information needed for selected payment product (e.g. amount of the order)
- Collection of missing customer information needed for selected payment product (e.g. creditcard number)
- Submitting the payment request to the Worldline platform
- Handling the response to the payment request (e.g. payment unsuccessful)
The Worldline platform offers three ways of handling this payment process:
- Use a hosted payment through the MyCheckout hosted payment pages.
In this case, you redirect the customer to our hosted payment pages. For you as a merchant, this is the easiest option as the Worldline platform can handle payment product selection and is responsible for the collection of sensitive data like a creditcard number. Through our Configuration Center, you still have a lot of control over the look and feel of the checkout. - Use a Client SDK to build a payment flow for a native app or a JavaScript application.
In this case, your server requests the creation of a client session. This returns a session id with which your client application can communicate with the Worldline platform directly. Your client collects and then encrypts the required customer information. It then sends this encrypted information to your server, where you add all other relevant information and submit a payment request to the Worldline platform. - Use a Server SDK to build a payment flow hosted on your server.
In this case, you can use the Server SDK to obtain the payment products that are applicable to the payment, to obtain the fields that need to be collected from the customer for a selected payment product, and to submit the payment request itself.
In the next couple of paragraphs, we discuss each of these options in more detail.
Use a hosted payment through the MyCheckout hosted payment pages (RPP)
The high-level flow of a hosted payment is described below, followed by a more detailed look at each of the steps.
- At this point, your customer has provided all relevant information regarding the order, e.g. a shopping cart of items and a shipping address.
- See the section on initialization. Use connect-sdk-nodejs to create an instance of connectSdk if you hadn't done so yet, and set the metadata that you've collected about the client of the customer.
- Create a CreateHostedCheckoutRequest body and populate at least its Order. See the relevant section of the full API reference for more details. You can specify an optional returnUrl, which is used to redirect your customer back to your website in step 9.
- The create hosted checkout SDK call returns a CreateHostedCheckoutResponse response. Store the hostedCheckoutId and RETURNMAC it contains, as well as any other relevant order information. You will need these when your customer returns from our hosted payment pages, or when the customer fails to return in a reasonable amount of time. Now take response.partialRedirectUrl and prepend "https://yoursubdomain" to it to create hostedCheckoutUrl, where yoursubdomain is an RPP subdomain you requested. You can find your subdomains in the Configuration Center's Payment Page Setup tab, under the Subdomain settings of your merchant. If you are logged in as an adminstrator, you can request a subdomain here as well.
- After completing the interactive payment process in the RPP, your customer is redirected back to the url you provided in step 3 as body.hostedCheckoutSpecificInput.returnUrl. The hostedCheckoutId and RETURNMAC you stored in step 5 are added to this URL as query parameters. Specifying a returnUrl is optional, however. As a result, your customer is only redirected back if you've provided a URL in step 3.
- If you cannot identify the customer based on e.g. the HTTP session, you can use the hostedCheckoutId for this purpose. If you do, you must check that the hostedCheckoutId and RETURNMAC from the returnUrl match those that you stored in step 3. Note that the RETURNMAC is used as a shared secret between the Worldline platform and your system that is specific for this hosted checkout.
- Retrieve the results of the customer's interaction with the Worldline platform.
- Check the GetHostedCheckoutResponse response returned in step 13. If response.status equals PAYMENT_CREATED, then the customer attempted a payment, the details of which can be found in response.createdPaymentOutput. Depending on the payment product chosen and the status of the payment you can "deliver the goods" immediately, or set up a regular poll of the created payment to wait for the status. Such a poll is done using the SDK call client.v1.payments.get(merchantId, paymentId), where paymentId is in the response of client.v1.payments.create(merchantId, createPaymentStub, paymentContext). For details on the various payment products and their statuses, see Payment Products.
Additionally, it may be the case that the customer does not return in time (or at all), for example because the browser is closed or because you didn't provide a returnUrl. In this case, you need to retrieve the status of the hosted checkout (step 12) before the hosted checkout times out, which happens after 2 hours, and follow step 14 as well.
Use a Client SDK to build a payment flow for a native app or a JavaScript application
The high-level flow of a payment performed with a native app or a JavaScript application is described below, followed by a more detailed look at each of the steps. First, we discuss the flow for payment products that do not require a redirect to a payment method hosted by a third party. Afterwards, the flow for payment methods that require a redirect is described.
Although this flow uses the Client SDK, we won't go into the details of this SDK here. A detailed description is given in the documentation of the Client SDK.
- At this point, your customer has provided all relevant information regarding the order, e.g. a shopping cart of items and a shipping address.
- The app sends the metadata about the client of the customer and the order information to your server.
- See the section on initialization. Use connect-sdk-nodejs to create an instance of connectSdk if you hadn't done so yet, and set the metadata about the client of the customer provided in the previous step.
- Create a SessionRequest body and request a new session. By creating a session, you allow your consumer to communicate with our Client API via your app. See the relevant section of the full API reference for more details. Requesting a new session results in a SessionResponse response, which contains a clientSessionId, customerId, and a region. Store the relevant information to be able to link the order and customer to the payment.
- Send the clientSessionId, customerId, and region to the app. The Client SDK needs this information to interact with the Client API. As mentioned above, the documentation of the Client SDK provides additional details.
- Once the interactive payment process is finished, the app has to send the encodedClientMetaInfo, encryptedFields, and paymentProductId to your server. The encryptedFields contains confidential information about the payment request. Do not store it anywhere. Use the paymentProductId to determine which additional fields you need to provide in the payment request. Some of these fields may come from your app, so you can decide to send additional app-specific data to your server. For payments that require a redirect to a third party, for example, you could send a return URL as app-specific data. Note that for this flow, we assume that we're dealing with a payment that doesn't require a redirect.
- Create a CreatePaymentRequest body. Populate its encryptedCustomerInput with the encryptedFields obtained from the app. Also populate its Order. You may also want to populate the fraudFields and the relevant PaymentMethodSpecificInput. To this end, you can map the paymentProductId obtained from the app to its payment method. For example, for a card payment, you can populate cardPaymentMethodSpecificInput to e.g. set a customerReference or indicate that the payment is the first of a recurring sequence.
- Use the body you just created to perform a create payment request. See the relevant section of the full API reference for more details. The create payment SDK call returns a CreatePaymentResponse response. The status of the payment is accessible via response.payment.status. Depending on the payment product chosen and the status of the payment you can "deliver the goods" immediately, or set up a regular poll of the created payment to wait for the status. Such a poll is done using the SDK call client.v1.payments.get(merchantId, paymentId), where paymentId is in the response of client.v1.payments.create(merchantId, createPaymentStub, paymentContext). For details on the various payment products and their statuses, see Payment Products.
The high-level flow of a payment performed with a native app or a JavaScript application is a little different if a redirect is involved. We only describe the steps that differ from the flow without a redirect.
- The payment process shown in the diagram above involves a redirect of your customer. For this example, we assume that the app decides which returnUrl should be used, which is sent as part of the app-specific data. Your customer is redirected to this URL (i.e., is send back to your app) after completing the payment process. The paymentProductId can be used to determine whether we're dealing with a payment that involves a redirect.
- Create a CreatePaymentRequest body and populate its encryptedCustomerInput and its Order. Additionally, populate its redirectPaymentMethodSpecificInput by providing at least the desired returnUrl. See the relevant section of the full API reference for more details.
- The create payment SDK call returns a CreatePaymentResponse response. For payments involving a redirect, response.merchantAction.redirectData.redirectURL defines the URL to which the customer should be redirected to complete the payment. You need to store the value ofresponse.merchantAction.redirectData.RETURNMAC because it should be compared with theRETURNMAC returned by the app at a later stage. Additionally, you need to store the value ofresponse.payment.id. This paymentId is needed to check the status of the payment after the redirect.
- Send the redirectUrl to your app so that it can redirect the customer to the payment page hosted by the third party.
- After the payment process is completed, your customer is redirected to the returnUrl specified previously. In the flow shown in the figure above, we assume that this URL brings the customer back to the app.
- The app should retrieve the RETURNMAC from the returnUrl and send it to your server.
- You can use the RETURNMAC to identify the customer by comparing it with the one stored previously, and to validate that the customer was redirected to you by our systems.
- Use the paymentId stored previously to check the status of the payment. See the relevant section of the full API reference for more details. The retrieve payment SDK call returns a PaymentResponse response. The status of the payment is accessible via response.payment.status. Use this status to handle the order appropriately, as described above.
Use a Server SDK to build a payment flow hosted on your server
The high-level flow of a payment performed from pages hosted on your server is described below, followed by a more detailed look at each of the steps. First, we describe the flow for payment products that do not require a redirect to a payment method hosted by a third party. Afterwards, the flow for payment methods that require a redirect is described.
- At this point, your customer has provided all relevant information regarding the order, e.g. a shopping cart of items and a shipping address.
- See the section on initialization. Use connect-sdk-nodejs to create an instance of connectSdk if you hadn't done so yet, and set the metadata that you've collected about the client of the customer.
- Create FindParams queryParams and request a list of relevant payment products. See the relevant section of the full API reference for more details.
- Show the relevant payment products to the customer such that he or she can select one.
- The customer selects one of available the payment products.
- Once the customer has decided which payment product should be used, you request the fields of this payment product. See the relevant section of the full API reference for more details.
- Based on the information retrieved in the previous step, you render a form that the customer can use to enter all relevant information for the selected payment product.
- The customer submits the form.
- Create a CreatePaymentRequest body, populate its Order and other properties depending on the selected payment product, and submit it. See the relevant section of the full API reference for more details. Do not store the information provided by the customer. The paymentProductId can be used to determine whether this payment involves a redirect to a third party. For this flow, we assume that we're dealing with a payment that doesn't require a redirect.
- The create payment SDK call returns a CreatePaymentResponse response. The status of the payment is accessible via response.payment.status. Depending on the payment product chosen and the status of the payment you can "deliver the goods" immediately, or set up a regular poll of the created payment to wait for the status. Such a poll is done using the SDK call client.v1.payments.get(merchantId, paymentId), where paymentId is in the response of client.v1.payments.create(merchantId, createPaymentStub, paymentContext). For details on the various payment products and their statuses, see Payment Products.
The high-level flow of a payment performed from pages on your server is a little different if a redirect is involved. We only describe the steps that differ from the flow without a redirect.
- We assume that we're dealing with a payment that involves a redirect. As mentioned above, this can be determined using the paymentProductId. Create a CreatePaymentRequest body and populate at least its Order. Additionally, populate its redirectPaymentMethodSpecificInput by providing at least the desired returnUrl. The returnUrl defines the location to which the customer should be redirected after completing the payment process. See the relevant section of the full API reference for more details.
- The create payment SDK call returns a CreatePaymentResponse response. For payments involving a redirect, response.merchantAction.redirectData.redirectURL defines the URL to which the customer should be redirected to complete the payment. You need to store the value ofresponse.merchantAction.redirectData.RETURNMAC because it should be compared with theRETURNMAC returned by the third party at a later stage. Additionally, you need to store the value ofresponsepayment().id. This paymentId is needed to check the status of the payment after the redirect.
- Redirect the customer to the redirectUrl.
- After the payment process is completed, your customer is redirected to the returnUrl specified previously. In the flow shown in the figure above, we assume that this URL brings the customer back to your server.
- Retrieve the RETURNMAC provided by the third party from the returnUrl. You can use the RETURNMAC to identify the customer by comparing it with the one stored previously, and to validate that the customer was redirected to you by our systems.
- Use the paymentId stored previously to check the status of the payment. See the relevant section of the full API reference for more details. The retrieve payment SDK call returns a PaymentResponse response. The status of the payment is accessible via response.payment.status. Use this status to handle the order appropriately, as described above.
File Service support
Uploading files
To upload a file, you need to add the file as an object with the following properties:
- fileName: the name of the file (without any path).
- content: the content of the file, as a Readable Stream , Buffer or string.
- contentType: the content type, e.g. application/pdf. Please check the API references for the allowed formats. You can find an incomplete list of content types (also called MIME types) here .
Downloading files
Downloading files is very similar to other calls. The only difference is in the response - for downloaded files, the body property of the response is a Readable Stream , and the response contains an extra file property, which is an object with the following properties:
- contentType: the file's content type.
- contentLength: the file's content length, if available.
- filename: the filename as retrieved from the Content-Disposition, if available.
To read from the response body, you should either listen to its data and end events, or use its pipe method to send the file content to a Writable Stream .
If the File Service returns an error response, the response body will be an object representing this object instead of a readable stream, and the file property will not be set. Always check the value of the isSuccess property and/or the presence of the file property before attempting to read from the response body.
Idempotent requests
To execute a request as an idempotent request, you can call the same method as for a non-idempotent request, but with an extra paymentContext argument with its idempotence property set. This will make sure the SDK will send an X-GCS-Idempotence-Key header with the idempotence key as its value.
If a subsequent request is sent with the same idempotence key, the response will contain an X-GCS-Idempotence-Request-Timestamp header, and the SDK will set the requestTimestamp property of the idempotence object of the PaymentContext argument so it's available in the response. If the first request has not finished yet, the RESTful Server API will return a 409 status code.
For example:
paymentContext.idempotence = {
key: "[idempotence-key]"
};
const sdkResponse = await client.v1.payments.create(merchantId, createPaymentStub, paymentContext);
render(res, sdkResponse);
if (paymentContext.idempotence.requestTimestamp) {
// this call is made with idempotence annd is still being handled
console.log("idempotence timestamp", paymentContext.idempotence.requestTimestamp)
};
Errors
Payment errors
If a payment attempt is declined by the RESTful Server API, the response's isSuccess property will be false. The body contains a reference to the payment result which can be inspected to find the reason why the payment attempt was declined. This payment result can also be used to later retrieve the payment attempt again.
For example:
function render(res, response) {
if (!response.isSuccess) {
console.log(response, response.body);
const status = error.status;
const body = error.body;
res.status(status).json(body).end();
}
}
Error overview
The following table is a summary that shows when each of these errors will be returned:
HTTP status code | Meaning | Description |
---|---|---|
200 | Successful | Your request was processed correctly |
201 | Created | Your request was processed correctly and a new resource was created. The URI of this created resource is returned in the Location header of the response. |
204 | No Content | Your request was processed correctly |
various; CreatePaymentResult is present in the response | Payment Rejected | Your request was rejected either by the Worldline platform or one of our downstream partners/acquirers. |
various; PayoutResult is present in the response | Payout Rejected | Your request was rejected either by the Worldline platform or one of our downstream partners/acquirers. |
various; RefundResult is present in the response | Refund Rejected | Your request was rejected either by the Worldline platform or one of our downstream partners/acquirers. |
400 | Bad Request | Your request is not correct and can't be processed. Please correct the mistake and try again. |
403 | Not Authorized | You're trying to do something that is not allowed or that you're not authorized to do. |
404 | Not Found | The object you were trying to access could not be found on the server. |
409 | Conflict | Your idempotent request resulted in a conflict. The first request has not finished yet. |
409 | Conflict | Your request resulted in a conflict. Either you submitted a duplicate request or you're trying to create something with a duplicate key. |
410 | Gone | The object that you are trying to reach has been removed. |
500 | Internal Server Error | Something went wrong on the Worldline platform. |
502 | Bad Gateway | The Worldline platform was unable to process a message from a downstream partner/acquirer. |
503 | Service Unavailable | The service that you're trying to reach is temporary unavailable. Please try again later. |
other | Unexpected error | An unexpected error has occurred |
Logging
The Node.js SDK supports logging of requests, responses and errors of the API communication.
In order to start using the logging feature, an implementation of the Logger interface should be provided. The example app provides an example implementations for logging.
Logging can be enabled by setting the enableLogging property when initializing a Client object, and providing the logger as an argument logger. Alternatively, it can be enabled on an existing Client by calling client.context.setEnableLogging(true).
When logged messages contain sensitive data, this data is obfuscated.
Advanced use: Customization of the communication
A Client uses an http.Agent to communicate with the RESTful Server API. By default Node.js will provide the http.Agent. If needed you can provide your own instance instead. For instance, https-proxy-agent can be used to provide proxying using the HTTP CONNECT method :
import { HttpsProxyAgent } from "https-proxy-agent";
const client = connectSdk.init({
host: "[hostname.of.the.api]",
scheme: "https",
port: 443,
enableLogging: true, // defaults to false
logger: logger, // if undefined console.log will be used
apiKeyId: "[your-api-key-id]",
secretApiKey: "[your-secret-api-key]",
integrator: "[your-company-name]",
connectionOptions: {
agent: new HttpsProxyAgent("[url.of.the.proxy]")
}
});
Webhooks
The part of the SDK that handles the webhooks support is called the webhooks helper. It transparently handles both validation of signatures against the event bodies sent by the webhooks system (including finding the secret key for key ids), and unmarshalling of these bodies to objects. This allows you to focus on the essentials, and not the additional overhead.
Providing secret keys
Secret keys are provided using a function that takes two arguments:
- The key id to return the secret key for.
- A callback function that either takes an error as its first argument, or the secret key for the given key id as its second argument (in which case the first argument must be null).
The Node.js SDK provides one implementation for this function: webhooks.inMemorySecretKeyStore.getSecretKey. This will retrieve secret keys from an in-memory key store. Keys can be added or removed using the following functions:
- webhooks.inMemorySecretKeyStore.storeSecretKey(keyId, secretKey) to store a secret key for a key id.
- webhooks.inMemorySecretKeyStore.removeSecretKey(keyId) to remove the stored secret key for a key id.
- webhooks.inMemorySecretKeyStore.clear() to remove all stored secret keys.
If more advanced storage is required, e.g. using a database or file system, then you should write your own implementation.
Initialization of the webhooks helper
Include and initialize the webhooks helper as follows:
const webhooks = connectSdk.webhooks;
// replace webhooks.inMemorySecretKeyStore.getSecretKey with your own function if needed
const helper = webhooks.v1.init({
getSecretKey: webhooks.inMemorySecretKeyStore.getSecretKey
});
Use the webhooks helper
From an entrypoint that you should write yourself, call the unmarshal method of the webhooks helper. It takes the following arguments:
- The body, as a string or Buffer. This should be the raw body as received from the webhooks system.
- An object containing the request headers as received from the webhooks system. The keys should be the header names.
If the body is modified, even in the slightest way like replacing line breaks or adding a trailing line break, signature validation will fail.
In code:
try {
const event = helper.unmarshal(body, requestHeaders);
// process the event
} catch (error) {
// something went wrong in validating the signature or unmarshalling the event
}