Dynamic Forms

Integrating with Switch

Dynamic Forms uses a JavaScript Client-Side Library. The library can be easily included in your checkout page and will be responsible for rendering the UI and handling the required communication with the Switch Platform to execute any type of transaction.

The Switch Platform enables real-time transactions on an any-to-any basis, be it multi-channel, multi-network, multi-method, or multi-currency. This abstraction feeds a shared, event-based database on top of which run multiple internal applications and external value-added services that make up our Platform Components.

Integrating with Switch requires code on two sides.

  • The client-side, to create the form that collects customer payment data.
  • The server-side, to create charges. This step is required to authenticate and avoid fraudulent requests.

For Dynamic Forms you should consider the following order of instructions.

  1. Display Form
  2. Create Charge
  3. Client Library Reference

After the Dynamic Forms integration, you will be able to add new payment channels without any changes to your code.

Display Form

Each payment method requires specific input fields and actions from the customer, and Dynamic Forms let you unify all these use cases in a single integration. Subsequently, enabling additional payment channels and configuring Dynamic Routing and Risk management rules is possible without having to change the integration.

To create a Dynamic Form, instantiate the client library with the environment and your Public Key, and call the dynamicForms over a container in your page.

Dynamic Forms can be added to your application through a quick and simple process that requires three steps from an integration perspective.

  1. Add HTML Container
  2. Load Client-Side Library
  3. Initialize Dynamic Forms

The following example shows how you can accomplish these three steps in your checkout page.

CHECKOUT PAGE
<html>
<body>
<!-- Step 1 -->
<!-- DIV container that will be used to render the Dynamic Forms -->
<!-- The UI will adapt to the space available -->
<div id="dynamic-forms-container"></div>
</body>
<!-- Step 2 -->
<!-- Import Switch client library -->
<script src="switch.js"></script>
<!-- Step 3 -->
<!-- Instatiante the client library -->
<script>
let formContainer = document.getElementById("dynamic-forms-container");
let formOptions = {
chargesUrl: "https://your.url.com/charges/",
merchantTransactionId: "123456",
};
let switchJs = new SwitchJs(SwitchJs.environments.SANDBOX, "ACCOUNT_PUBLIC_KEY");
switchJs.dynamicForms(formContainer);
</script>
</html>

Add HTML Container

Our Library requires a DIV container to be present in the page that will be used to render the UI. This HTML container should have a dedicated id so you can reference it when initializing the Dynamic Forms. In the previous example this is done by the HTML element <div id="dynamic-forms-container"> </div>.

Looking for more information about our Client Library?

Head over to the Client Library Reference and review all the functions and options available.

Load the Client-Side Library

This integration mechanism uses a Client-Side JavaScript Library to coordinate the execution process. As such, it is loaded as any JavaScript library <script src="switch.js"></script>.

Initialize Dynamic forms

Our Client Library provides the functions necessary to load and initialize the UI that will process payments. This is done essentially by performing two function calls, one to instantiate the Library itself and another to render the Dynamic Forms.

INITIALIZING THE DYNAMIC FORMS
let formContainer = document.getElementById('dynamic-forms-container');
let formOptions = {
chargesUrl: 'https://your.url.com/charges/',
merchantTransactionId: '123456',
};
// 1. Instantiate
let switchJs = new SwitchJs(SwitchJs.environments.SANDBOX, 'ACCOUNT_PUBLIC_KEY');
// 2. Render
switchJs.dynamicForms(formContainer, formOptions);

The first function call will initialize the client library by indicating the Switch environment and account that will be used to process transactions SwitchJs(SwitchJs.environments.SANDBOX, 'ACCOUNT_PUBLIC_KEY').

Afterward, it is time to render the Dynamic Forms on your checkout page. To achieve this we call the following function with the reference to the HTML element where the form will be drawn as well as the rendering options switchJs.dynamicForms(formContainer, formOptions).

Create Charge

After performing the previous steps, the Dynamic Forms have been successfully rendered in your checkout page. The user can now choose the preferred payment method towards acquiring the intended goods.

As stated in the Core Concepts section, our Platform divides a transaction into three executable elements: charge, instrument, and payment. The Client-Side Library will coordinate the creation of these elements, where required, and the associated communications with the Switch platform.

One of such communication steps will be with your backend platform, in order to authenticate the transaction being attempted and effectively create the charge. This authentication will be done using your private API key and will ensure that both you and the customer intended to execute the transaction. To this effect, the following steps will be executed:

dynamic_forms

  1. After the customer has selected the intended payment method, the browser calls the merchant backend through the chargesURL
  2. The merchant backend system receives a POST request containing the merchantTransactionId to correlate the transaction being attempted and using your Private API Key authenticates the transaction.
  3. The merchant backend calls the Switch Platform to proceed with creating the charge.
  4. The Switch platform creates a charge and replies back with the associated charge information, including ID.
  5. The merchant backend replies back to the original call made in step 1 with the provided charge_id.

ChargeURL Call

To execute steps 2 and 3 as previously outlined, which will lead to the creation of the charge by your backend system, our Platform expects your API to comply with the following signature.

PathMethodDescription
Configured by the chargeURL when initializing the Dynamic FormsPOSTThis API call is made by the Switch Platform and aims to authenticate the charge being attempted.

Result Parameter

chargeTypeString

Indicates the payment method that has been selected by the customer. For a list of updated values please contact our Integration Team.


merchantTransactionIdString

Parameter that univocally identifies the transaction being attempted. The Switch Platform will use the merchantTransactionId that is passed when initializing the Dynamic Form.

REQUEST EXAMPLE
$ curl -vX POST https://charge.url
-d '{
"chargeType": "card_onetime",
"merchantTransactionId": "506785940"
}'
Response Body Params

idString

The id returned by the Switch Platform that uniquely identifies the charge element for this transaction.

REQUEST EXAMPLE
{
"id": "06d7c2e4145f3be209e9ab5c6ed24da8b786f"
}

Switch API Call

As documented previously in steps 4 and 5, in order to generate a charge element your backend system must contact our API using the privateKey. Below you can find the endpoint that should be used to execute this step as well as all the required details to perform the call.

POST v2/charges

PathmethodDescription
https://api-test.switchpayments.com/v2/chargesPOSTCreates a charge element by using the information passed in the body parameters.

Request Body Params

charge_typeStringRequired

Indicates the payment method that has been selected by the customer, should contain the value passed by our API call. For a list of updated values please contact our Integration Team.


currencyStringRequired

ISO 4217 code that indicates the currency that will be used by the transaction.


amountNumberRequired

The amount that should be charged to the customer.


events_urlString

Allows you to configure the URL that will be called by the Switch Platform to notify about lifecycle events related to this transaction. Please note that the URL must use HTTPS.


redirect_urlString

Specifies the HTTPS URL to where the users should be sent after they authenticated the transaction on the payment method page.This parameter is only required for payment methods that require user redirection for authentication (e.g. PayPal).


instrument_paramsJSON Object

Specifies configuration parameters that are passed to the provider when creating the instrument element and which allow you to configure how the fund transfer is executed.


metadataJSON Object

This object allows you to pass any transaction related data points that may be useful to be displayed in the Switch Dashboard for analysis purposes.


channelsArray

Gives the ability to specify which channel should be used to process the transaction. Using this parameter you can leverage your business logic to select the channel rather than relying on Switch’s Dynamic Routing. If multiple values are present, a fallback mechanism will be used, giving precedence to the first entries.

REQUEST EXAMPLE
-u accountId:privateKey
-d '{
"charge_type": "card_onetime",
"amount": 42,
"currency": "EUR",
"events_url": "https://your.url/v1/notificationHandler"
}'
Response Body Params

idString

The id that uniquely identifies the created charge element for this transaction.


charge_typeString

Indicates the payment method that will be used to process the transaction.


charge_type_labelString

User-friendly description of the payment method that will be used to process the transaction.


currencyString

ISO 4217 code that indicates the currency that will be used by the transaction.


amountNumber

The amount that will be charged to the customer.


confirmedBoolean

Indicates whether the current charge element has been confirmed by the merchant using their Private Key.


externalBoolean

Indicates whether the current charge element was not created by the Switch Platform.


instrument_paramsJSON Object

The configuration parameters that were specified when creating the charge element, which allow you to configure how the funds transfer is executed by the provider.


events_urlString

Contains the URL that will be called by the Switch Platform to notify about lifecycle events related to this transaction.


redirect_urlJSON Object

The URL to where the users should be sent after they authenticated the transaction on the payment method page.


channelsArray

Documents the channels that will be used to process the transaction.


metadataJSON Object

The transaction-related data points that were passed when creating the charge, which may be useful to be displayed in the Switch Dashboard for analysis purposes.


external_idsJSON Object

Documents the provider id for the current charge, if available.


request_logJSON Object

Stores information about the device that was used to create the current charge element, such as country, ip_address, user_agent, and library_version.


created_atString

Indicates the date and time when the current charge element was created.


updated_atJSON Object

Documents the date and time when the last update was performed to the current charge.

RESPONSE EXAMPLE
{
"id": "756ae7bdc3390050cf6648fb819ac1c4de02f4d15b278954",
"charge_type": "card_onetime",
"amount": 10,
"currency": "EUR",
"confirmed": false,
"external": false,
"instrument_params": {
"enable3ds": true
},
"events_url": "https://merchant.com/events",
"channels": [{
"processor": "checkout",
"id": "85a557e4fdb6c8806f413bc75fabab162828e4f95b8e6390",
"label": "card_onetime_checkout"
},
{
"processor": "acapture",
"id": "9fb7b1e253f1c592210b7c37b40b18e576ff30995b8e40de",
"label": "card_onetime_acapture"
}],
"charge_type_label": "Card One-Time",
"redirect_url": "https://merchant.com/redirect",
"metadata": {
"orderId": "1337"
},
"external_ids": null,
"request_log": {
"country": "PT",
"ip_address": "100.10.10.10",
"user_agent": "curl/7.54.0",
"library_version": null
},
"created_at": "2018-06-18T10:28:36.358233+00:00",
"updated_at": "2018-06-18T10:28:36.358258+00:00"
}

Client Library Reference

Our Client Library provides the required functionality to initialize and operate Dynamic Forms on your checkout page. Here you can find out more about the available functions and what each can achieve.

SwitchJs(environment, accountPublicKey)
Constructor function to initialize the Switch Client-Side Library
Parameters

environmentString

The Switch Platform environment to which the Dynamic Forms Library will connect to process the payments. For ease of use, our library has constants available with the URLs.SwitchJs.environments.SANDBOX: constant containing the sandbox URL. SwitchJs.environments.LIVE: constant containing the production URL.


accountPublicKeyString

The Switch Public Key attributed to the account. Typically provided by our Sales Department during the integration process.

USAGE EXAMPLE
let switchJs = new SwitchJs(SwitchJs.environments.SANDBOX, 'ACCOUNT_PUBLIC_KEY');
Return Value

Object

An object containing the initialized Client-Side Library, which can be used for subsequent calls.

.dynamicForms(formContainer, formOptions)
Renders the Dynamic Form in the UI. Requires the Client-Side Library to be previously initiated.
Parameters

formContainerObject

The object containing the HTML element where the form will be rendered.


formOptionsObject

An object containing the initialization options for the Form. Please check below for further details regarding the available parameters.

USAGE EXAMPLE
let formContainer = document.getElementById('dynamic-forms-container');
let formOptions = {
chargesUrl: 'https://your.url.com/charges/',
merchantTransactionId: '123456',
};
let switchJs = new SwitchJs(SwitchJs.environments.SANDBOX, 'ACCOUNT_PUBLIC_KEY');
switchJs.dynamicForms(formContainer, formOptions);

.dynamicForms(formContainer, formOptions)
These parameters are passed to the .dynamicForms() function call and allow you to configure the UI/UX of the form.
Parameters

merchantTransactionIDStringRequired

id that uniquely identifies the transaction being attempted from your perspective. Allows you to correlate the transaction within your systems.


chargesUrlStringRequired

URL from your platform that will be called to generate the charge element in the Switch Platform.


chargeTypesArray

Allows you to override Dynamic Routing and specify which payment methods will be displayed. If unspecified, all the payment methods active at that moment in your account will be shown. Can be leveraged to limit certain methods according to your business logic (e.g. 'card_onetime', 'multibanco'). For a complete list of available charge types please contact our Integration Team.


selectedChargeTypeString

Defines the payment method that will be selected by default in the UI (e.g.'card_onetime').


iframeBoolean

Indicates whether the Dynamic Forms should be rendered directly on your checkout page or inside an iframe. true: default option where the UI is rendered inside an iframe. Only requires PCI’s SAQ A from a compliance perspective. false: UI elements are rendered directly on your website, mandating PCI’s SAQ A-EP.


autoRedirectBoolean

Certain payment methods have an execution flow which requires the user to be redirected to a given website (e.g. Paypal). This flag allows you control over whether this is performed automatically by Switch’s Client Side Library, or by you. true: default option where the user will be automatically redirected to the target website to complete the payment. false: redirection will not be automatically handled by the Dynamic Forms, requiring you to take further action.


showReferenceBoolean

Only applicable to Post-payment methods, this parameter controls if the Dynamic Forms will show the payment reference. true: default option where the UI will render the payment reference. false: gives you the ability to render the payment reference in your page without leveraging Dynamic Forms.


languageString

I18n parameter that controls the language used by the forms (e.g. en). Please contact our Integration Team for an updated list of available languages.


resetStyleBoolean

Indicates whether the forms should be rendered without the default CSS of Switch. This option can be useful if you want to customize the look and feel of the UI, as it allows a blank sheet approach. true: the forms will be rendered without any CSS associated, thus utilizing the default HTML style. false: default option where Switch’s CSS will be used to format the look and feel.


styleObject

JSON Object which allows to configure the look and feel of the Dynamic Forms through CSS properties.

USAGE EXAMPLE
let formStyle = {
formHeader: {'display': 'none'},
formField: {'margin': '10px 0 10px 0'}
};
let formOptions = {
merchantTransactionId: '123456',
chargesUrl: 'https://your.url.com/charges/',
chargeTypes: ['card_onetime', 'multibanco'],
selectedChargeType: 'card_onetime',
iframe: true,
autoRedirect: true,
showReference: true,
language: 'en',
resetStyle: true,
style: formStyle
};

.on(event, callbackFunction)
Registers a callback function that will be triggered every time a given behavior is performed by the Dynamic Forms. Using these event listeners you can monitor which actions are being performed by the forms and trigger any relevant actions on your side.
Parameters

eventString

The event that you intend to listen to. You can find some examples of events below.


callbackFunctionFunction

The callback function that will be executed by the Client Library when the subscribed event is triggered. Depending on the event in question, it will contain at most one variable with relevant information.

USAGE EXAMPLE
dynamicForms.on('charge-type-selected', (chargeType) => {
if (chargeType === 'card_onetime') {
console.log(Customer chose Card one-time');
}
});
Event ExampleDescription
forms-loadedThe Form has completed rendering on the webpage.
form-data-changedThe user has changed the data inputted in the Dynamic Forms.
form-data-errorThere was an error parsing the information submitted in the Form.
charge-types-loadedThe list of available charge types has been rendered in the UI.
charge-type-selectedThe user has selected the charge type he intends to utilize.
charge-type-canceledThe charge type that was previously selected has been canceled by the user.
submitThe Form has been submitted by the user.
instrument-successThe instrument element has been created successfully.
instrument-errorThe instrument element has failed to be created.

That's it!

By following these steps, your product is already enabled for many payment methods and providers, and your integration is ready to be tested. Please contact us if you have any feedback or need more help integrating. We want to make this integration as simple as possible, and depending on your server-side language or CMS, we might even be able to provide you with code samples.


Next Steps

Create your events_url and handle transaction lifecycle events. This process will allow you to mark transactions as paid in your database. Get to know a few additional transaction flows you should handle to truly support every payment method, provider, and transaction flow in the world.