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="https://cdn.switchpayments.com/libs/switch-5.stable.min.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.TEST, "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.TEST, '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.TEST, '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.TEST: constant containing the test environment 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.TEST, '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.TEST, '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.

You have multiple options available for customization in Dynamic Forms. To that effect, consider the following optional fields.

Parameters

autoRedirectBoolean

Whether customers will be automatically redirected to the provider’s payment page, when a payment method requires redirection. Defaults to true.


chargeIdString

ID of a previously created Charge. Useful when a single payment method is supposed to be displayed, instead of a list of all the available ones. Sending this parameter makes chargesUrl and merchantTransactionId optional, and not used.


showOptionalFieldsBoolean

Whether optional payment method form fields should be shown or not. A “false” value means that only the required fields will be displayed. Defaults to false.


showReferenceBoolean

For payment methods that include a reference (information that should be presented to the customers, for them to proceed with the payment, e.g.: multibanco, boleto, pix, …), this parameter defines whether the Dynamic Forms should handle the display of it or not. Defaults to true.


chargeTypesArray

List of charge types that will be available to the customers. By default, all the payment channels enabled on your Merchant account are available. This list works as a filter over that, if you want to display only certain payment methods to a given customer.


chargesUrlString

This should be an endpoint on your end, which is prepared to receive Charge creation requests from Dynamic Forms. It will be called every time a customer selects a payment method on the Dynamic Forms list. Requests to this endpoint will include the specified merchantTransactionId, the charge type selected by the customer, and the additional parameters set in chargeParameters. It is required by default, but optional if chargeId is specified.


chargeParametersObject

Object with extra data that will be sent in chargesUrl requests.


languageString

Language in which the forms should be displayed. Defaults to the browser set language.


merchantTransactionIdString

An ID that identifies the transaction on your end. It will be sent in chargeUrl requests. It is required by default, but optional if chargeId is specified.


payoutsBoolean

Sets whether payout methods should be displayed. If this is set to true, only payout methods will be available. Defaults to false.


themeString

Set the theme that will be used. Most customizations should be made using the customStyles parameter, but theme can help with some more radical changes to some parts of the layout. Currently the only available themes are base and material. The one single difference between them are the form inputs, which have a material-design-like look and feel on the material theme. Defaults to base.


customStylesObject

This is where you customize the Dynamic Forms to match your website’s style. The possibilities are endless. Contact our Support Team to know more.


validateFormOnChangeBoolean

Whether form data should be validated immediately when input by the user, or only at the form submission stage. Defaults to true.


selectedChargeTypeString

Charge type that will be initially selected on forms render. Charge types list screen will be skipped, and the payment form for this charge type will be immediately displayed. Other charge types are still available by navigating back to the list.

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-successObject with the created Charge ID. Triggered when Dynamic Forms receive a successful response from chargesUrl.
charge-errorObject with the unsuccessful response returned by chargesUrl.
charge-types-loadedThe list of available charge types has been rendered in the UI.
charge-type-selectedCharge type selected by the customer.
charge-type-canceledThe charge type that was previously selected has been canceled by the user. Triggered when the user goes back to charge type selection list.
instrument-authorizedInstrument details of the successfully created authorized Instrument.
instrument-pendingWhen an Instrument was successfully created, but it’s not authorized yet, you may need to wait for some action from the user.
If the instrument has a reference to be displayed, and showReference is disabled, you should display it to the customer. If the instrument requires a redirect, and autoRedirect is disabled, you should redirect the customer now.
instrument-invalidThis event is triggered when the instrument fails, either because the user input data is wrong, or a provider is down.
submitTriggered every time the user submits the form.

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 know to handle.