CCBill API Payment Widget integration guide

Vue

To integrate the CCBill API Payment Widget into your Vue.js application, complete the following steps:

1. Installation and Setup

To use the widget, add a <script> import in the header of the main index.html file.

To view the widget, set up the correct <meta> tag for viewports in the header of the same file.

2. Usage

Add the widget <ccb-payment-widget> element and the required parameters in the template of your component. In this example, the file is called app.vue.

Attributes

PARAMETER
apiKey string
A valid OAuth token generated using the merchant application ID and the secret key asigned to the client account involved in the transaction.
clientAccount string
Merchant account number.
The value must be in the range between 900000 and 999999.
subAccount string
Merchant subaccount number.
The value must be in the range between 0 and 9999.
currency string
Currency used for this transaction.
Accepted values: USD / GBP / EUR / CAD / AUD / JPY
initialPrice string
This is the initial transaction price.
Formatted as a float value up to 2 decimal points, e.g., 5.00
initialPeriod string
The length (in days) of the initial billing.
Formatted as an integer value, e.g., 5
NOTE: Set to 0 in case of a single and non-recurring transaction.
PARAMETER
language string
The language the widget will be rendered in.
Accepted values: en / es / fr / de / it / ja / ko / zh_tw / zh_cn / pt_br / hi / sv / da / no / nl

NOTE: If the language is not supplied or the supplied language is not supported, the widget will try to determine the language from the browser. If that language is not supported, it will default to English.
theme string
The theme the widget will be loaded in.
Accepted values are ccb-light and ccb-dark

NOTE: If the value is not supplied or is invalid, the system will default to ccb-light.
Custom themes are possible; please refer to the theming documentation.
description string
Optional product description to show in the widget.
Up to 500 characters (no HTML/images allowed).
lifeTimeSubscription string
Indicates whether the transaction is a lifetime subscription or not.
Formatted as boolean value 1 or 0
rebills string
Represents a recurring transaction, rebilling the consumer X times according to the value set.
Formatted as an integer value 1 to 99 ("99" being indefinite).

NOTE: When rebills is provided recurringPrice and recurringPeriod become required fields
recurringPrice string
The recurring price in case of a recurring transaction.
Formatted as a float value up to 2 decimal points, e.g., 5.00
It is a required parameter for recurring transactions.
recurringPeriod string
The recurring period in case of a recurring transaction.
Formatted as an integer value, e.g., 5

At this point, your application is consuming the widget. However, the required configuration is still missing.

Define these properties and their values in the script tag within your app.vue component file.

If all the passed parameters are correct, the following screen appears:

A successfully configured CCBill API Payment Widget.

In case of a misconfiguration or if one of the values passed in is not valid, the following screen is displayed:

CCBill Widget misconfiguration message.

3. Create Payment Token

Pressing the Place your order button generates a payment token, which passes into the application as a CustomEvent.

To get the data from the widget and use it in an application, add an event listener for a custom event called tokenCreated, which will give you data in the details property.

When the event is caught, the onGenerateTokenId method is called with data as input, and you can use the payment token.

CCBill Widget successfully configured.

Creating a charge with this payment token will require adding the customer's IP address as an additional payload (ipAddress) or header (X-Origin-IP) parameter.

4. Customize CSS (Optional)

Customize the appearance of the CCBill API Payment Widget through a preset Theme or with CSS variables to modify its appearance.

With CSS variables, the widget easily adapts to match the look and feel of a website. This guide will walk you through the customization process, including preset dark and light themes.

Setting the Viewport Meta Tag

The viewport meta tag sets the initial viewport properties for a web page. It helps control how the web page displays on various devices, ensuring the content fits and scales appropriately.

This is crucial for responsive web design and providing a good user experience on different screen sizes and orientations.

You can set up the correct <meta> tag for viewports in the header of the main index.html file.

Preset Light and Dark Themes

The dark or light themes are standard themes with which the widget is shipped. These themes are ready to use as-is without any additional customization.

1. Define the constant and its value in the my-app.ts file using ccb-dark or ccb-lightas values.
2. Add the theme widget attribute to pass the information to the widget.

Available CSS Variables

You can customize various aspects of the widget using the following CSS variables:

Element Variable
Widget Background --ccb-background
Element Variable
Ribbon - Language Dropdown
Background --ccb-ribbon-background
List - Background --ccb-language-dropdown-background
Text --ccb-language-dropdown-text
Icon - Chevron --ccb-language-dropdown-icon
Header - Price / Product Description
Background --ccb-header-background
Section Divider - Border --ccb-section-divider-border
Price - Text --ccb-header-price-text
Description - Text --ccb-header-description-text
Header - Currency Code - Text --ccb-header-currency-code-text
Section Headers
Header Text --ccb-section-header
Input Field and Dropdown
Background --ccb-input-field-background
Placeholder Text --ccb-input-field-placeholder
Text --ccb-input-field-text
Border --ccb-input-field-border
Border - In Focus --ccb-input-field-border-infocus
Dropdown Country - Divider --ccb-country-dropdown-divider
Dropdown Language - Background --ccb-language-dropdown-background
Links
Text --ccb-link
Text - Hover --ccb-link-hover
Text - Visited --ccb-link-visited
Terms & Conditions
Text --ccb-terms-and-conditions-text
Call to Action - Place your Order Button
Background --ccb-cta-background
Background - Hover --ccb-cta-background-hover
Background - Action --ccb-cta-background-action
Text --ccb-cta-text-color
Text - Hover --ccb-cta-text-color-hover
Footer
Background --ccb-footer-background
Text --ccb-footer-text
Border --ccb-validation-border
Input Field Text --ccb-validation-text
Error Message Text --ccb-validation-error-text
Background --ccb-validation-background
Element Variable
Border --ccb-validation-border
Input Field Text --ccb-validation-text
Error Message Text --ccb-validation-error-text
Background --ccb-validation-background

Feel free to modify these variables according to your website's color scheme and design preferences. Experiment with different values to achieve the desired look for your payment widget.

<!DOCTYPE html>
<html lang="">
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE-edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
<title>DemoVueMerchant</title><link rel="icon" href="<%= BASE_URL %>favicon.ico"/>
<script src="https://js.ccbill.com/payment-widget/v1/index.js"></script>
</head> <body> <noscript> <strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong> </noscript> <div id="app"></div> <!--built files will be auto injected--> </body> </html>
<template>
<div>
  <div>
    <h2 v-if="paymentToken">Payment Token Generated</h2>
    <p v-if="paymentToken">{{ paymentToken }}</p>
    <p v-else>No payment token available yet.</p>
  </div>
<ccb-payment-widget :apiKey="apiKey" :language="language" :currency="currency" :initialPrice="initialPrice" :initialPeriod="initialPeriod" :recurringPrice="recurringPrice" :recurringPeriod="recurringPeriod" :rebills="rebills" :lifeTimeSubscription="lifeTimeSubscription" :description="description" :clientAccount="clientAccount" :subAccount="subAccount" :theme="theme" :apiBaseUrl="apiBaseUrl" @tokenCreated="_onGenerateTokenId" ></ccb-payment-widget>
</div> </template> <script>
export default { data: function () { return { paymentToken: '', }; }, props: { apiKey: { type: String, default: 'YOUR_API_KEY' }, language: { type: String, default: 'en' }, currency: { type: String, default: 'USD' }, initialPrice: { type: String, default: '12.22' }, initialPeriod: { type: String, default: '5' }, clientAccount: { type: String, default: '901909' }, subAccount: { type: String, default: '0' }, apiBaseUrl: { type: String, default: 'https://api.dev.ccbill.com/' }, recurringPrice: { type: String, }, recurringPeriod: { type: String, }, rebills: { type: String, }, lifeTimeSubscription: { type: String, }, description: { type: String, },
// Set theme value here. theme: { type: String, default: 'ccb-dark' },
}, methods:{ _onGenerateTokenId(event){ this.paymentToken = event.detail.paymentToken.paymentTokenId; }, },
mounted() { const ccbPaymentWidget = this.$el.querySelector('ccb-payment-widget'); // Manually add an event listener to capture Lit custom events ccbPaymentWidget.addEventListener('tokenCreated', this._onGenerateTokenId); }, beforeUnmount() { const ccbPaymentWidget = this.$el.querySelector('ccb-payment-widget'); // Remove the event listener when the Vue component is unmounted ccbPaymentWidget.removeEventListener('tokenCreated', this._onGenerateTokenId); }, }
</script>
html {
  /* Custom - Background */
  --ccb-background: #280F50;

  /* Custom - Header - Ribbon */
  --ccb-ribbon-background: #62389E;
  --ccb-header-language-dropdown-text: #ffffff;
  --ccb-header-language-dropdown-icon: #ffffff;
  --ccb-header-language-background: #62389E;

  /* Add more customizations here */
}

JavaScript

To integrate the CCBill API Payment Widget into your JavaScript application, complete the following steps:

1. Installation and Setup

To use the widget, add a <script> import in the header of the main index.html file.

Set up the correct <meta> tag for viewports in the header of the same file to view the widget.

2. Usage

Create a placeholder <div> with an ID in the body of the index.html file to add the widget. The <div> will be used to append the widget dynamically from a JavaScript file (app.js).

Add an additional <script> tag pointing to the app.js file. The file contains widget configuration and initialization.

Currently, the application is consuming the widget but has no configuration yet.

To initialize the widget, do the following in the app.js file:

1. Add the required parameter constants and their values.

2. Set the required attributes on the widget.

3. Lastly, append the widget to the placeholder <div> created earlier.

Attributes

PARAMETER
apiKey string
A valid OAuth token generated using the merchant application ID and the secret key asigned to the client account involved in the transaction.
clientAccount string
Merchant account number.
The value must be in the range between 900000 and 999999.
subAccount string
Merchant subaccount number.
The value must be in the range between 0 and 9999.
currency string
Currency used for this transaction.
Accepted values: USD / GBP / EUR / CAD / AUD / JPY
initialPrice string
This is the initial transaction price.
Formatted as a float value up to 2 decimal points, e.g., 5.00
initialPeriod string
The length (in days) of the initial billing.
Formatted as an integer value, e.g., 5
NOTE: Set to 0 in case of a single and non-recurring transaction.
PARAMETER
language string
The language the widget will be rendered in.
Accepted values: en / es / fr / de / it / ja / ko / zh_tw / zh_cn / pt_br / hi / sv / da / no / nl

NOTE: If the language is not supplied or the supplied language is not supported, the widget will try to determine the language from the browser. If that language is not supported, it will default to English.
theme string
The theme the widget will be loaded in.
Accepted values are ccb-light and ccb-dark

NOTE: If the value is not supplied or is invalid, the system will default to ccb-light.
Custom themes are possible; please refer to the theming documentation.
description string
Optional product description to show in the widget.
Up to 500 characters (no HTML/images allowed).
lifeTimeSubscription string
Indicates whether the transaction is a lifetime subscription or not.
Formatted as boolean value 1 or 0
rebills string
Represents a recurring transaction, rebilling the consumer X times according to the value set.
Formatted as an integer value 1 to 99 ("99" being indefinite).

NOTE: When rebills is provided recurringPrice and recurringPeriod become required fields
recurringPrice string
The recurring price in case of a recurring transaction.
Formatted as a float value up to 2 decimal points, e.g., 5.00
It is a required parameter for recurring transactions.
recurringPeriod string
The recurring period in case of a recurring transaction.
Formatted as an integer value, e.g., 5

Depending on whether the passed parameters are correct, different screens appear.

If all the passed parameters are correct, the following screen appears:

A successfully configured CCBill API Payment Widget.

In case of a misconfiguration or if one of the values passed in is not valid, the following screen is displayed:

CCBill Widget misconfiguration message.

3. Create Payment Token

This step shows how a filled-out and submitted form generates a payment token, which is required to send a charge request:

Pressing the Place your order button generates a payment token, which passes into the application as a CustomEvent.

To get the data from the widget and use it in an application, add an event listener for a custom event called tokenCreated, which will give you data in the details property.

Payment token generated using the CCBill Payment Widget,
Successfully generated payment token using the CCBill Payment Widget.

Creating a charge with this payment token will require adding the customer's IP address as an additional payload (ipAddress) or header (X-Origin-IP) parameter.

4. Customize CSS (Optional)

Customize the appearance of the CCBill API Payment Widget through a preset Theme or with CSS variables to modify its appearance.

With CSS variables, the widget easily adapts to match the look and feel of a website. This guide will walk you through the customization process, including preset dark and light themes.

Setting the Viewport Meta Tag

The viewport meta tag sets the initial viewport properties for a web page. It helps control how the web page displays on various devices, ensuring the content fits and scales appropriately.

This is crucial for responsive web design and providing a good user experience on different screen sizes and orientations.

You can set up the correct <meta> tag for viewports in the header of the main index.html file.

Preset Light and Dark Themes

The dark or light themes are standard themes with which the widget is shipped. These themes are ready to use as-is without any additional customization.

Define the constant and its value in the app.js file using ccb-dark or ccb-light as values.

Add the theme widget attribute to pass the information to the widget.

Available CSS Variables

To customize the theme further you must link your CSS stylesheet in the index.html file.

You can customize various aspects of the widget using the following CSS variables:

Element Variable
Widget Background --ccb-background
Element Variable
Ribbon - Language Dropdown
Background --ccb-ribbon-background
List - Background --ccb-language-dropdown-background
Text --ccb-language-dropdown-text
Icon - Chevron --ccb-language-dropdown-icon
Header - Price / Product Description
Background --ccb-header-background
Section Divider - Border --ccb-section-divider-border
Price - Text --ccb-header-price-text
Description - Text --ccb-header-description-text
Header - Currency Code - Text --ccb-header-currency-code-text
Section Headers
Header Text --ccb-section-header
Input Field and Dropdown
Background --ccb-input-field-background
Placeholder Text --ccb-input-field-placeholder
Text --ccb-input-field-text
Border --ccb-input-field-border
Border - In Focus --ccb-input-field-border-infocus
Dropdown Country - Divider --ccb-country-dropdown-divider
Dropdown Language - Background --ccb-language-dropdown-background
Links
Text --ccb-link
Text - Hover --ccb-link-hover
Text - Visited --ccb-link-visited
Terms & Conditions
Text --ccb-terms-and-conditions-text
Call to Action - Place your Order Button
Background --ccb-cta-background
Background - Hover --ccb-cta-background-hover
Background - Action --ccb-cta-background-action
Text --ccb-cta-text-color
Text - Hover --ccb-cta-text-color-hover
Footer
Background --ccb-footer-background
Text --ccb-footer-text
Border --ccb-validation-border
Input Field Text --ccb-validation-text
Error Message Text --ccb-validation-error-text
Background --ccb-validation-background
Element Variable
Border --ccb-validation-border
Input Field Text --ccb-validation-text
Error Message Text --ccb-validation-error-text
Background --ccb-validation-background

Feel free to modify these variables according to your website's color scheme and design preferences. Experiment with different values to achieve the desired look for your payment widget.


<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE-edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
<link rel="stylesheet" href="styles.css" />
<title>DemoVanillaJSMerchant</title>
<script src="https://js.ccbill.com/payment-widget/v1/index.js"></script>
</head> <body> <div id="ccb-payment-token" style="display: none;"> <h2>Payment Token Generated</h2> <pre>"paymentTokenId": <span id="ccb-payment-token-id"></span></pre> <pre>"clientAccnum": <span id="ccb-client-account"></span></pre> <pre>"clientSubacc": <span id="ccb-client-sub-account"></span></pre> <pre>"createdDatetime": <span id="ccb-created-date-time"></span></pre> <pre>"timeToLive": <span id="ccb-time-to-live"></span></pre> <pre>"validNumberOfUse": <span id="ccb-valid-number-of-use"></span></pre> <pre>"subscriptionId": <span id="ccb-subscription-id"></span></pre> </div>
<div id="ccb-payment-widget"></div>
<script src="./app.js"></script>
</body> </html>

(function () {
  const widgetPlaceholder = document.getElementById("ccb-payment-widget");

  const widget = new ccbill.PaymentWidget();

const apiKey = "YOUR-API-KEY"; const initialPrice = "1.00"; const initialPeriod = "30"; const currency = "USD"; const clientAccount = "901909"; const subAccount = "0";
// Set theme value here const theme = 'ccb-dark';
widget.setAttribute("apiKey", apiKey); widget.setAttribute("initialPrice", initialPrice); widget.setAttribute("initialPeriod", initialPeriod); widget.setAttribute("currency", currency); widget.setAttribute("clientAccount", clientAccount); widget.setAttribute("subAccount", subAccount);
widgetPlaceholder.appendChild(widget);
// Listen for tokenCreated to get the payment token widget.addEventListener("tokenCreated", (event) => { const paymentToken = event.detail.paymentToken;
document .getElementById("ccb-payment-token-id") .textContent(paymentToken.paymentTokenId); document .getElementById("ccb-client-account") .textContent(paymentToken.clientAccount); document .getElementById("ccb-client-sub-account") .textContent(paymentToken.subAccount); document .getElementById("ccb-created-date-time") .textContent(paymentToken.createdDatetime); document .getElementById("ccb-time-to-live") .textContent(paymentToken.timeToLive); document .getElementById("ccb-valid-number-of-use") .textContent(paymentToken.validNumberOfUse); document .getElementById("ccb-subscription-id") .textContent(paymentToken.subscriptionId); document.getElementById("ccb-payment-token").style.display = "block"; }); })();

html {
  /* Custom - Background */
  --ccb-background: #280F50;

  /* Custom - Header - Ribbon */
  --ccb-ribbon-background: #62389E;
  --ccb-header-language-dropdown-text: #ffffff;
  --ccb-header-language-dropdown-icon: #ffffff;
  --ccb-header-language-background: #62389E;

  /* Add more customizations here */
}

Web Components

Complete the following steps to integrate the CCBill API Payment Widget into your HTML application.

1. Installation and Setup

To use the widget, add a <script> import in the header of the main index.html file.

To view the widget, set up the correct <meta> tag for viewports in the header of the same file.

2. Usage

Add a custom <ccb-payment-widget> element and the required parameters in the typescript file of your web component. In this example, the file is called my-app.ts.
There are two ways to add the widget element to the template file:

Standard HTML Element

<div><ccb-payment-widget></ccb-payment-widget></div>

HTML Element with Self-closing Tags

<div><ccb-payment-widget /></div>

Attributes

PARAMETER
apiKey string
A valid OAuth token generated using the merchant application ID and the secret key asigned to the client account involved in the transaction.
clientAccount string
Merchant account number.
The value must be in the range between 900000 and 999999.
subAccount string
Merchant subaccount number.
The value must be in the range between 0 and 9999.
currency string
Currency used for this transaction.
Accepted values: USD / GBP / EUR / CAD / AUD / JPY
initialPrice string
This is the initial transaction price.
Formatted as a float value up to 2 decimal points, e.g., 5.00
initialPeriod string
The length (in days) of the initial billing.
Formatted as an integer value, e.g., 5
NOTE: Set to 0 in case of a single and non-recurring transaction.
PARAMETER
language string
The language the widget will be rendered in.
Accepted values: en / es / fr / de / it / ja / ko / zh_tw / zh_cn / pt_br / hi / sv / da / no / nl

NOTE: If the language is not supplied or the supplied language is not supported, the widget will try to determine the language from the browser. If that language is not supported, it will default to English.
theme string
The theme the widget will be loaded in.
Accepted values are ccb-light and ccb-dark

NOTE: If the value is not supplied or is invalid, the system will default to ccb-light.
Custom themes are possible; please refer to the theming documentation.
description string
Optional product description to show in the widget.
Up to 500 characters (no HTML/images allowed).
lifeTimeSubscription string
Indicates whether the transaction is a lifetime subscription or not.
Formatted as boolean value 1 or 0
rebills string
Represents a recurring transaction, rebilling the consumer X times according to the value set.
Formatted as an integer value 1 to 99 ("99" being indefinite).

NOTE: When rebills is provided recurringPrice and recurringPeriod become required fields
recurringPrice string
The recurring price in case of a recurring transaction.
Formatted as a float value up to 2 decimal points, e.g., 5.00
It is a required parameter for recurring transactions.
recurringPeriod string
The recurring period in case of a recurring transaction.
Formatted as an integer value, e.g., 5

The Web Components application is now consuming the widget. However, the required configuration is still missing.

Define the constants and their values by adding the appropriate attributes to the widget tag in the my-app.ts template.

To provide these values to the payment widget, add the appropriate attributes to the widget tag in the render method.

Depending on whether the passed parameters are correct, different screens appear.

If all the passed parameters are correct, the following screen appears:

A successfully configured CCBill API Payment Widget.

In case of a misconfiguration or if one of the values passed in is not valid, the following screen is displayed:

CCBill Widget misconfiguration message.

3. Create Payment Token

This step shows how a filled-out and submitted form generates a payment token, which is required to send a charge request:

Pressing the Place your order button generates a payment token, which passes into the application as a CustomEvent.

To get the data from the widget and use it in an application, add an event listener for a custom event called tokenCreated, which will give you data in the details property.

CCBill Widget successfully configured.

When the event is caught, the onGenerateTokenId method is called with data as input, and you can use the payment token.

Creating a charge with this payment token will require adding the customer's IP address as an additional payload ipAddress or header X-Origin-IP parameter.

4. Customize CSS (Optional)

Customize the appearance of the CCBill API Payment Widget through a preset Theme or with CSS variables to modify its appearance.

With CSS variables, the widget easily adapts to match the look and feel of a website. This guide will walk you through the customization process, including preset dark and light themes.

Setting the Viewport Meta Tag

The viewport meta tag sets the initial viewport properties for a web page. It helps control how the web page displays on various devices, ensuring the content fits and scales appropriately.

This is crucial for responsive web design and providing a good user experience on different screen sizes and orientations.

You can set up the correct <meta> tag for viewports in the header of the main index.html file.

Preset Light and Dark Themes

The dark or light themes are standard themes with which the widget is shipped. These themes are ready to use as-is without any additional customization.

1. Define the constant and its value in the my-app.ts file using ccb-dark or ccb-lightas values.

2. Add the theme widget attribute to pass the information to the payment widget.

Available CSS Variables

To customize the theme further you must link your CSS stylesheet in the index.html file.

You can customize various aspects of the widget using the following CSS variables:

Element Variable
Widget Background --ccb-background
Element Variable
Ribbon - Language Dropdown
Background --ccb-ribbon-background
List - Background --ccb-language-dropdown-background
Text --ccb-language-dropdown-text
Icon - Chevron --ccb-language-dropdown-icon
Header - Price / Product Description
Background --ccb-header-background
Section Divider - Border --ccb-section-divider-border
Price - Text --ccb-header-price-text
Description - Text --ccb-header-description-text
Header - Currency Code - Text --ccb-header-currency-code-text
Section Headers
Header Text --ccb-section-header
Input Field and Dropdown
Background --ccb-input-field-background
Placeholder Text --ccb-input-field-placeholder
Text --ccb-input-field-text
Border --ccb-input-field-border
Border - In Focus --ccb-input-field-border-infocus
Dropdown Country - Divider --ccb-country-dropdown-divider
Dropdown Language - Background --ccb-language-dropdown-background
Links
Text --ccb-link
Text - Hover --ccb-link-hover
Text - Visited --ccb-link-visited
Terms & Conditions
Text --ccb-terms-and-conditions-text
Call to Action - Place your Order Button
Background --ccb-cta-background
Background - Hover --ccb-cta-background-hover
Background - Action --ccb-cta-background-action
Text --ccb-cta-text-color
Text - Hover --ccb-cta-text-color-hover
Footer
Background --ccb-footer-background
Text --ccb-footer-text
Border --ccb-validation-border
Input Field Text --ccb-validation-text
Error Message Text --ccb-validation-error-text
Background --ccb-validation-background
Element Variable
Border --ccb-validation-border
Input Field Text --ccb-validation-text
Error Message Text --ccb-validation-error-text
Background --ccb-validation-background

Feel free to modify these variables according to your website's color scheme and design preferences. Experiment with different values to achieve the desired look for your payment widget.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
<base href="/" /> <title>DemoWebComponentMerchant</title>
<link rel="stylesheet" href="styles.css"/>
<script src="https://js.ccbill.com/payment-widget/v1/index.js"></script>
</head> <body> <my-app></my-app> <script type="module" src="./out-tsc/src/my-app.js"></script> </body> </html>
import { LitElement, html } from "lit";
import { property, customElement, state } from "lit/decorators.js";
import { when } from "lit/directives/when.js";

interface PaymentToken {
  paymentTokenId: string;
  programParticipationId: string;
  originalPaymentTokenId: string;
  clientAccnum: number;
  clientSubacc: number;
  createdDatetime: Date;
  timeToLive: number;
  validNumberOfUse: number;
  subscriptionId: string;
  paymentInfoId: string;
  errors: {};
}
@customElement("my-app") class MyApp extends LitElement { @property({ type: String }) header = "My app"; @state() paymentToken!: PaymentToken; apiKey = "YOUR_API_KEY"; currency = "USD"; clientAccount = "90000"; subAccount = "0"; initialPrice = "0.00"; initialPeriod = "0";
// Set theme value here theme = "ccb-dark"; // Set theme value here theme = "ccb-light";
getPaymentToken($event: CustomEvent) { this.paymentToken = $event.detail.paymentToken; }
render() { return html` ${when(this.paymentToken, () => { return html` <h2>Payment Token Generated</h2> <pre>"paymentTokenId":${this.paymentToken.paymentTokenId}</pre> <pre>"clientAccnum":${this.paymentToken.clientAccnum}</pre> <pre>"clientSubacc":${this.paymentToken.clientSubacc}</pre> <pre>"createdDatetime":${this.paymentToken.createdDatetime}</pre> <pre>"timeToLive":${this.paymentToken.timeToLive}</pre> <pre>"validNumberOfUse":${this.paymentToken.validNumberOfUse}</pre> <pre>"subscriptionId":${this.paymentToken.subscriptionId}</pre> `; })}
<ccb-payment-widget
apiKey="${this.apiKey}" clientAccount="${this.clientAccount}" subAccount="${this.subAccount}" initialPrice="${this.initialPrice}" initialPeriod="${this.initialPeriod}" currency="${this.currency}" @tokenCreated="${this.getPaymentToken}" ></ccb-payment-widget>
`; } }
html {
  /* Custom - Background */
  --ccb-background: #280F50;

  /* Custom - Header - Ribbon */
  --ccb-ribbon-background: #62389E;
  --ccb-header-language-dropdown-text: #ffffff;
  --ccb-header-language-dropdown-icon: #ffffff;
  --ccb-header-language-background: #62389E;

  /* Add more customizations here */
}

HTML

To integrate the CCBill API Payment Widget into your Web Component application, complete the following steps:

1. Installation and Setup

To use the widget, add a <script> import in the header of the main index.html file.

To view the widget, set up the correct <meta> tag for viewports in the header of the same file.

2. Usage

This step demonstrates how to display the payment form:

Add a custom <ccb-payment-widget> tag with all required attributes and their values.

Attributes

PARAMETER
apiKey string
A valid OAuth token generated using the merchant application ID and the secret key asigned to the client account involved in the transaction.
clientAccount string
Merchant account number.
The value must be in the range between 900000 and 999999.
subAccount string
Merchant subaccount number.
The value must be in the range between 0 and 9999.
currency string
Currency used for this transaction.
Accepted values: USD / GBP / EUR / CAD / AUD / JPY
initialPrice string
This is the initial transaction price.
Formatted as a float value up to 2 decimal points, e.g., 5.00
initialPeriod string
The length (in days) of the initial billing.
Formatted as an integer value, e.g., 5
NOTE: Set to 0 in case of a single and non-recurring transaction.
PARAMETER
language string
The language the widget will be rendered in.
Accepted values: en / es / fr / de / it / ja / ko / zh_tw / zh_cn / pt_br / hi / sv / da / no / nl

NOTE: If the language is not supplied or the supplied language is not supported, the widget will try to determine the language from the browser. If that language is not supported, it will default to English.
theme string
The theme the widget will be loaded in.
Accepted values are ccb-light and ccb-dark

NOTE: If the value is not supplied or is invalid, the system will default to ccb-light.
Custom themes are possible; please refer to the theming documentation.
description string
Optional product description to show in the widget.
Up to 500 characters (no HTML/images allowed).
lifeTimeSubscription string
Indicates whether the transaction is a lifetime subscription or not.
Formatted as boolean value 1 or 0
rebills string
Represents a recurring transaction, rebilling the consumer X times according to the value set.
Formatted as an integer value 1 to 99 ("99" being indefinite).

NOTE: When rebills is provided recurringPrice and recurringPeriod become required fields
recurringPrice string
The recurring price in case of a recurring transaction.
Formatted as a float value up to 2 decimal points, e.g., 5.00
It is a required parameter for recurring transactions.
recurringPeriod string
The recurring period in case of a recurring transaction.
Formatted as an integer value, e.g., 5

Depending on whether the passed parameters are correct, different screens appear.

If all the passed parameters are correct, the following screen appears:

A successfully configured CCBill API Payment Widget.

In case of a misconfiguration or if one of the values passed in is not valid, the following screen is displayed:

CCBill Widget misconfiguration message.

3. Create Payment Token

This step shows how a filled-out and submitted form generates a payment token, which is required to send a charge request:

Pressing the Place your order button generates a payment token, which passes into the application as a CustomEvent.

To get the data from the widget and use it in an application, add an event listener for a custom event called tokenCreated, which will give you data in the detail property.

For this demo, it can be done directly in the HTML file using a script tag.

Here is an example of the application getting a payment token and printing it in the console:

Successfully generated payment token using the CCBill Payment Widget.

Creating a charge with this payment token will require adding the customer's IP address as an additional payload ipAddress or header X-Origin-IP parameter.

4. Customize CSS (Optional)

Customize the appearance of the CCBill API Payment Widget through a preset Theme or with CSS variables to modify its appearance.

With CSS variables, the widget easily adapts to match the look and feel of a website. This guide will walk you through the customization process, including preset dark and light themes.

Setting the Viewport Meta Tag

The viewport meta tag sets the initial viewport properties for a web page. It helps control how the web page displays on various devices, ensuring the content fits and scales appropriately.

This is crucial for responsive web design and providing a good user experience on different screen sizes and orientations.

You can set up the correct <meta> tag for viewports in the header of the main index.html file.

Preset Light and Dark Themes

The dark or light themes are standard themes with which the widget is shipped. These themes are ready to use as-is without any additional customization.

Define the theme attribute and its value in the ccb-payment-widget tag using ccb-dark or ccb-lightas values.

Available CSS Variables

To customize the theme further you must link your CSS stylesheet in the index.html file.

You can customize various aspects of the widget using the following CSS variables:

Element Variable
Widget Background --ccb-background
Element Variable
Ribbon - Language Dropdown
Background --ccb-ribbon-background
List - Background --ccb-language-dropdown-background
Text --ccb-language-dropdown-text
Icon - Chevron --ccb-language-dropdown-icon
Header - Price / Product Description
Background --ccb-header-background
Section Divider - Border --ccb-section-divider-border
Price - Text --ccb-header-price-text
Description - Text --ccb-header-description-text
Header - Currency Code - Text --ccb-header-currency-code-text
Section Headers
Header Text --ccb-section-header
Input Field and Dropdown
Background --ccb-input-field-background
Placeholder Text --ccb-input-field-placeholder
Text --ccb-input-field-text
Border --ccb-input-field-border
Border - In Focus --ccb-input-field-border-infocus
Dropdown Country - Divider --ccb-country-dropdown-divider
Dropdown Language - Background --ccb-language-dropdown-background
Links
Text --ccb-link
Text - Hover --ccb-link-hover
Text - Visited --ccb-link-visited
Terms & Conditions
Text --ccb-terms-and-conditions-text
Call to Action - Place your Order Button
Background --ccb-cta-background
Background - Hover --ccb-cta-background-hover
Background - Action --ccb-cta-background-action
Text --ccb-cta-text-color
Text - Hover --ccb-cta-text-color-hover
Footer
Background --ccb-footer-background
Text --ccb-footer-text
Border --ccb-validation-border
Input Field Text --ccb-validation-text
Error Message Text --ccb-validation-error-text
Background --ccb-validation-background
Element Variable
Border --ccb-validation-border
Input Field Text --ccb-validation-text
Error Message Text --ccb-validation-error-text
Background --ccb-validation-background

Feel free to modify these variables according to your website's color scheme and design preferences. Experiment with different values to achieve the desired look for your payment widget.


<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="styles.css"/>
<title>DemoHTMLMerchant</title>
<script src="https://js.ccbill.com/payment-widget/v1/index.js"></script>
</head> <body>
<ccb-payment-widget
apiKey="YOUR-API-KEY" initialPrice="1.00" initialPeriod="0" clientAccount="901909" subAccount="0" currency="USD"
<!--Set Up Dark Theme--> theme="ccb-dark"
></ccb-payment-widget>
<script> document.addEventListener('tokenCreated', (event) => { // Print the token to the console console.log('tokenCreated', event.detail.paymentToken) }) </script>
</body> </html>

html {
  /* Custom - Background */
  --ccb-background: #280F50;

  /* Custom - Header - Ribbon */
  --ccb-ribbon-background: #62389E;
  --ccb-header-language-dropdown-text: #ffffff;
  --ccb-header-language-dropdown-icon: #ffffff;
  --ccb-header-language-background: #62389E;

  /* Add more customizations here */
}

React

Complete the following steps to integrate the Payment Widget into your React application.

1. Installation and Setup

To use the widget, add a <script> import in the header of the main index.html file.

The Payment Widget HTML tag, ccb-payment-widget, is a non-standard element, and you must tell the React app to use this element:

1. Declare a global type using the declare global block.

2. Create the JSX namespace.

3. Add an IntrinsicElements interface.

4. Define a property in the interface corresponding to the element's name and specify its accepted props.

2. Usage

The React application is now aware of the custom element in the template of the App.tsx component.

There are two ways to add the widget element to the template file:

Standard HTML Element

<div> <ccb-payment-widget></ccb-payment-widget> </div>

HTML Element with Self-closing Tags

<div> <ccb-payment-widget /> </div>

The React application is now consuming the widget. However, the required configuration is still missing.

Define the constants and their values by adding the appropriate attributes to the widget tag in the App.tsx template.

Attributes

PARAMETER
apiKey string
A valid OAuth token generated using the merchant application ID and the secret key asigned to the client account involved in the transaction.
clientAccount string
Merchant account number.
The value must be in the range between 900000 and 999999.
subAccount string
Merchant subaccount number.
The value must be in the range between 0 and 9999.
currency string
Currency used for this transaction.
Accepted values: USD / GBP / EUR / CAD / AUD / JPY
initialPrice string
This is the initial transaction price.
Formatted as a float value up to 2 decimal points, e.g., 5.00
initialPeriod string
The length (in days) of the initial billing.
Formatted as an integer value, e.g., 5
NOTE: Set to 0 in case of a single and non-recurring transaction.
PARAMETER
language string
The language the widget will be rendered in.
Accepted values: en / es / fr / de / it / ja / ko / zh_tw / zh_cn / pt_br / hi / sv / da / no / nl

NOTE: If the language is not supplied or the supplied language is not supported, the widget will try to determine the language from the browser. If that language is not supported, it will default to English.
theme string
The theme the widget will be loaded in.
Accepted values are ccb-light and ccb-dark

NOTE: If the value is not supplied or is invalid, the system will default to ccb-light.
Custom themes are possible; please refer to the theming documentation.
description string
Optional product description to show in the widget.
Up to 500 characters (no HTML/images allowed).
lifeTimeSubscription string
Indicates whether the transaction is a lifetime subscription or not.
Formatted as boolean value 1 or 0
rebills string
Represents a recurring transaction, rebilling the consumer X times according to the value set.
Formatted as an integer value 1 to 99 ("99" being indefinite).

NOTE: When rebills is provided recurringPrice and recurringPeriod become required fields
recurringPrice string
The recurring price in case of a recurring transaction.
Formatted as a float value up to 2 decimal points, e.g., 5.00
It is a required parameter for recurring transactions.
recurringPeriod string
The recurring period in case of a recurring transaction.
Formatted as an integer value, e.g., 5

If all the passed parameters are correct, the following screen appears:

A successfully configured CCBill API Payment Widget.

In case of a misconfiguration or if one of the values passed in is not valid, the following screen is displayed:

CCBill Widget misconfiguration message.

3. Create Payment Token

Pressing the Place your order button generates a payment token, which passes into the application as a CustomEvent.

To get the data from the widget and use it in an application, add an event listener for a custom event called tokenCreated,which will give you data in the detail property.

When the event is caught, the onGenerateTokenId method is called with data as input, and you can use the payment token.

CCBill Widget successfully configured.

Creating a charge with this payment token will require adding the customer's IP address as an additional payload (ipAddress) or header (X-Origin-IP) parameter.

4. Customize CSS (Optional)

Customize the appearance of the Payment Widget through a preset Theme or with CSS variables to modify its appearance.

With CSS variables, the widget easily adapts to match the look and feel of a website. This guide will walk you through the customization process, including preset dark and light themes.

Setting the Viewport Meta Tag

The viewport meta tag sets the initial viewport properties for a web page. It helps control how the web page displays on various devices, ensuring the content fits and scales appropriately.

This is crucial for responsive web design and providing a good user experience on different screen sizes and orientations.

You can set up the correct <meta> tag for viewports in the header of the main index.html file.

Preset Light and Dark Themes

The dark or light themes are standard themes with which the widget is shipped. These themes are ready to use as-is without any additional customization.

1. Define the constant and its value in the app.js file using ccb-dark or ccb-lightas values.

2. Add the theme widget attribute to pass the information to the Payment Widget.

Available CSS Variables

To customize the theme further you must link your CSS stylesheet in the index.html file.

You can customize various aspects of the Payment Widget using the following CSS variables:

Element Variable
Widget Background --ccb-background
Element Variable
Ribbon - Language Dropdown
Background --ccb-ribbon-background
List - Background --ccb-language-dropdown-background
Text --ccb-language-dropdown-text
Icon - Chevron --ccb-language-dropdown-icon
Header - Price / Product Description
Background --ccb-header-background
Section Divider - Border --ccb-section-divider-border
Price - Text --ccb-header-price-text
Description - Text --ccb-header-description-text
Header - Currency Code - Text --ccb-header-currency-code-text
Section Headers
Header Text --ccb-section-header
Input Field and Dropdown
Background --ccb-input-field-background
Placeholder Text --ccb-input-field-placeholder
Text --ccb-input-field-text
Border --ccb-input-field-border
Border - In Focus --ccb-input-field-border-infocus
Dropdown Country - Divider --ccb-country-dropdown-divider
Dropdown Language - Background --ccb-language-dropdown-background
Links
Text --ccb-link
Text - Hover --ccb-link-hover
Text - Visited --ccb-link-visited
Terms & Conditions
Text --ccb-terms-and-conditions-text
Call to Action - Place your Order Button
Background --ccb-cta-background
Background - Hover --ccb-cta-background-hover
Background - Action --ccb-cta-background-action
Text --ccb-cta-text-color
Text - Hover --ccb-cta-text-color-hover
Footer
Background --ccb-footer-background
Text --ccb-footer-text
Border --ccb-validation-border
Input Field Text --ccb-validation-text
Error Message Text --ccb-validation-error-text
Background --ccb-validation-background
Element Variable
Border --ccb-validation-border
Input Field Text --ccb-validation-text
Error Message Text --ccb-validation-error-text
Background --ccb-validation-background

Feel free to modify these variables according to your website's color scheme and design preferences. Experiment with different values to achieve the desired look for your Payment Widget.


<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" /><link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<base href="/" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" /> <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<link rel="stylesheet" href="styles.css"/>
<title>DemoReactMerchant</title>
<script src="https://js.ccbill.com/payment-widget/v1/index.js"></script> </head> <body> <noscript>You need to enable JavaScript to run this app.</noscript> <div id="root"></div> </body> </html>

import React, { useState } from 'react';
import './App.css';
declare global { namespace JSX { interface IntrinsicElements { "ccb-payment-widget": MyElementAttributes; } interface MyElementAttributes { apiKey: string; clientAccount: string; subAccount: string; currency: string; initialPrice: string; initialPeriod: string; language?: string; description?: string; recurringPrice?: string; recurringPeriod?: string; rebills?: string; lifeTimeSubscription?: string; theme?: string; } } }
interface PaymentToken { paymentTokenId: string; programParticipationId: string; originalPaymentTokenId: string; clientAccnum: number; clientSubacc: number; createdDatetime: Date; timeToLive: number; validNumberOfUse: number; subscriptionId: string; paymentInfoId: string; errors: {}; } function App() { const [paymentToken, setPaymentToken] = useState(null); // Required parameters const apiKey = "YOUR-API-KEY"; const initialPrice = "0.00"; const initialPeriod = "0"; const currency = "USD"; const clientAccount = "900000"; const subAccount = "0";
// Set theme value here const theme = "ccb-light";
// Register event listener for token generation React.useEffect(() => { window.addEventListener("tokenCreated", _onGenerateTokenId); return () => { window.removeEventListener("tokenCreated", _onGenerateTokenId); }; }, []);
// Handle behaviour on tokenCreated event function _onGenerateTokenId(event: Event) { const receivedPaymentToken = (event as CustomEvent).detail .paymentToken as PaymentToken; setPaymentToken(receivedPaymentToken); }
return ( <div> {paymentToken ? ( <div> <h2>Payment Token Generated</h2> <pre>{JSON.stringify(paymentToken, null, 2)}</pre> </div> ) : ( <p>No payment token available yet.</p> )}
<ccb-payment-widget apiKey={apiKey} currency={currency} initialPrice={initialPrice} initialPeriod={initialPeriod} clientAccount={clientAccount} subAccount={subAccount}
theme={theme}
/> </div> ); } export default App;
			html {
			  /* Custom - Background */
			  --ccb-background: #280F50;

			  /* Custom - Header - Ribbon */
			  --ccb-ribbon-background: #62389E;
			  --ccb-header-language-dropdown-text: #ffffff;
			  --ccb-header-language-dropdown-icon: #ffffff;
			  --ccb-header-language-background: #62389E;

			  /* Add more customizations here */
			}
		

Angular

Complete the following steps to integrate the CCBill API Payment Widget into your Angular application.

1. Installation and Setup

To use the widget, add a <script> import in the header of the main index.html file.

The <ccb-payment-widget> HTML tag is a non-standard element. You must tell the Angular app to use this element by defining a schema.

Add the CUSTOM_ELEMENTS_SCHEMA to the @NgModule decorator in the app.module.ts file.

If using standalone components, add the schema within the @Component decorator.

2. Usage

The Angular application is now aware of possible custom elements.

Add the custom <ccb-payment-widget> HTML tag in the app.component.html component template to enable the app to use these elements.

There are two ways to add the widget element to your template file:

Standard HTML Element

<div> <ccb-payment-widget></ccb-payment-widget> </div>

HTML Element with Self-closing Tags

<div> <ccb-payment-widget /> </div>

The Angular application can now consume the widget but lacks the required configuration.

To initialize the widget, define the required parameters and their values in the app.component.ts file so they can be used in the app.component.html template.

Attributes

PARAMETER
apiKey string
A valid OAuth token generated using the merchant application ID and the secret key asigned to the client account involved in the transaction.
clientAccount string
Merchant account number.
The value must be in the range between 900000 and 999999.
subAccount string
Merchant subaccount number.
The value must be in the range between 0 and 9999.
currency string
Currency used for this transaction.
Accepted values: USD / GBP / EUR / CAD / AUD / JPY
initialPrice string
This is the initial transaction price.
Formatted as a float value up to 2 decimal points, e.g., 5.00
initialPeriod string
The length (in days) of the initial billing.
Formatted as an integer value, e.g., 5
NOTE: Set to 0 in case of a single and non-recurring transaction.
PARAMETER
language string
The language the widget will be rendered in.
Accepted values: en / es / fr / de / it / ja / ko / zh_tw / zh_cn / pt_br / hi / sv / da / no / nl

NOTE: If the language is not supplied or the supplied language is not supported, the widget will try to determine the language from the browser. If that language is not supported, it will default to English.
theme string
The theme the widget will be loaded in.
Accepted values are ccb-light and ccb-dark

NOTE: If the value is not supplied or is invalid, the system will default to ccb-light.
Custom themes are possible; please refer to the theming documentation.
description string
Optional product description to show in the widget.
Up to 500 characters (no HTML/images allowed).
lifeTimeSubscription string
Indicates whether the transaction is a lifetime subscription or not.
Formatted as boolean value 1 or 0
rebills string
Represents a recurring transaction, rebilling the consumer X times according to the value set.
Formatted as an integer value 1 to 99 ("99" being indefinite).

NOTE: When rebills is provided recurringPrice and recurringPeriod become required fields
recurringPrice string
The recurring price in case of a recurring transaction.
Formatted as a float value up to 2 decimal points, e.g., 5.00
It is a required parameter for recurring transactions.
recurringPeriod string
The recurring period in case of a recurring transaction.
Formatted as an integer value, e.g., 5

To provide these values to the widget, add the appropriate attributes to the widget tag in the app.component.html template.

If all the passed parameters are correct, the following screen appears:

A successfully configured CCBill API Payment Widget.

In case of a misconfiguration or if one of the values passed in is not valid, the following screen is displayed:

CCBill Widget misconfiguration message.

3. Create Payment Token

Pressing the Place your order button generates a payment token, which passes into the application as a CustomEvent.

To get the data from the widget and use it in an application, add an event listener for a custom event called tokenCreated, which will give you data in the details property.

CCBill Widget successfully configured.

When the event is caught, the onGenerateTokenId method is called with data as input, and you can use the payment token.

Creating a charge with this payment token will require adding the customer's IP address as an additional payload (ipAddress) or header (X-Origin-IP) parameter.

4. Customize CSS (Optional)

Customize the appearance of the CCBill API Payment Widget through a preset Theme or with CSS variables to modify its appearance.

With CSS variables, the widget easily adapts to match the look and feel of a website. This guide will walk you through the customization process, including preset dark and light themes.

Setting the Viewport Meta Tag

The viewport meta tag sets the initial viewport properties for a web page. It helps control how the web page displays on various devices, ensuring the content fits and scales appropriately.

This is crucial for responsive web design and providing a good user experience on different screen sizes and orientations.

You can set up the correct <meta> tag for viewports in the header of the main index.html file.

Preset Dark and Light Themes

The dark or light themes are standard themes with which the widget is shipped. These themes are ready to use as-is without any additional customization.

Define the constant and its value in the app.component.ts file using ccb-dark or ccb-light as values.

Add the theme widget attribute to pass the information to the widget.

Available CSS Variables

To customize the theme further you must link your CSS stylesheet in the index.html file.

You can customize various aspects of the widget using the following CSS variables:

Element Variable
Widget Background --ccb-background
Element Variable
Ribbon - Language Dropdown
Background --ccb-ribbon-background
List - Background --ccb-language-dropdown-background
Text --ccb-language-dropdown-text
Icon - Chevron --ccb-language-dropdown-icon
Header - Price / Product Description
Background --ccb-header-background
Section Divider - Border --ccb-section-divider-border
Price - Text --ccb-header-price-text
Description - Text --ccb-header-description-text
Header - Currency Code - Text --ccb-header-currency-code-text
Section Headers
Header Text --ccb-section-header
Input Field and Dropdown
Background --ccb-input-field-background
Placeholder Text --ccb-input-field-placeholder
Text --ccb-input-field-text
Border --ccb-input-field-border
Border - In Focus --ccb-input-field-border-infocus
Dropdown Country - Divider --ccb-country-dropdown-divider
Dropdown Language - Background --ccb-language-dropdown-background
Links
Text --ccb-link
Text - Hover --ccb-link-hover
Text - Visited --ccb-link-visited
Terms & Conditions
Text --ccb-terms-and-conditions-text
Call to Action - Place your Order Button
Background --ccb-cta-background
Background - Hover --ccb-cta-background-hover
Background - Action --ccb-cta-background-action
Text --ccb-cta-text-color
Text - Hover --ccb-cta-text-color-hover
Footer
Background --ccb-footer-background
Text --ccb-footer-text
Border --ccb-validation-border
Input Field Text --ccb-validation-text
Error Message Text --ccb-validation-error-text
Background --ccb-validation-background
Element Variable
Border --ccb-validation-border
Input Field Text --ccb-validation-text
Error Message Text --ccb-validation-error-text
Background --ccb-validation-background

Feel free to modify these variables according to your website's color scheme and design preferences. Experiment with different values to achieve the desired look for your payment widget.


<!DOCTYPE html>
	<html lang="en">
	<head>
		<meta charset="utf-8" />
		<title>DemoAngularMerchant</title>
		<base href="/" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
<link rel="icon" type="image/x-icon" href="favicon.ico" />
<link rel="stylesheet" href="styles.css"/>
<script src="https://js.ccbill.com/payment-widget/v1/index.js"></script>
</head> <body> <app-root></app-root> </body> </html>
				
	# When custom elements schema

	import { CUSTOM_ELEMENTS_SCHEMA, NgModule } from "@angular/core";
	import { BrowserModule } from "@angular/platform-browser";

	import { AppComponent } from "./app.component";
	
@NgModule({ declarations: [AppComponent], imports: [BrowserModule], bootstrap: [AppComponent], schemas: [CUSTOM_ELEMENTS_SCHEMA], })
export class AppModule {} # When using a standalone components import { Component, CUSTOM_ELEMENTS_SCHEMA } from "@angular/core";
@Component({ selector: "app-root", standalone: true, schemas: [CUSTOM_ELEMENTS_SCHEMA], template: `<h2>Root Component</h2>`, })
export class AppComponent {}
		import {Component} from '@angular/core';
interface PaymentToken {
  paymentTokenId: string;
  programParticipationId: string;
  originalPaymentTokenId: string;
  clientAccnum: number;
  clientSubacc: number;
  createdDatetime: Date;
  timeToLive: number;
  validNumberOfUse: number;
  subscriptionId: string;
  paymentInfoId: string;
  errors: {};
}
@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'], }) export class AppComponent { paymentToken!: PaymentToken; apiKey = 'YOUR_API_KEY'; currency = 'USD'; clientAccount = '900000'; subAccount = '0'; initialPrice = '0.00'; initialPeriod = '0';
// Set theme value here
theme = "ccb-dark";
onGenerateTokenId(event: Event) { this.paymentToken = (event as CustomEvent).detail .paymentToken as PaymentToken; } }

<div *ngIf="paymentToken">
  <h2>Payment Token Generated</h2>
  <pre>{{ paymentToken | json }}</pre>
</div>
<ccb-payment-widget
[apiKey]="apiKey" [currency]="currency" [clientAccount]="clientAccount" [subAccount]="subAccount" [initialPrice]="initialPrice" [initialPeriod]="initialPeriod" (tokenCreated)="onGenerateTokenId($event)"
/>
		
html { /* Custom - Background */ --ccb-background: #280F50; /* Custom - Header - Ribbon */ --ccb-ribbon-background: #62389E; --ccb-header-language-dropdown-text: #ffffff; --ccb-header-language-dropdown-icon: #ffffff; --ccb-header-language-background: #62389E; /* Add more customizations here */ }

TypeScript/Node.js

The code example is written in TypeScript. It describes the steps required to perform authentication with the CCBill API and the payment token obtained using the CCBill API Payment Widget to perform the charge by payment token action (non-3DSecure and 3DSecure versions). This script covers the backend portion of the integration with the CCBill's RESTful Transaction API.

1. Install Dependencies

The backend code uses the Axios dependency to make HTTP requests. Install it with:

NPM:

npm install axios

Yarn:

yarn add axios

Begin by importing the axios library.

2. Define Endpoints

The endpoints section defines the API endpoints you will use throughout the process.

The example uses three endpoints to demonstrate the charge flow:

1. tokenEndpoint allows requesting the CCBill Auth (Bearer) token required for authentication in subsequent operations.

2. nonThreedsTransactionEndpoint allows performing a non-3DSecured charge transaction using the payment token.

3. threedsTransactionEndpoint allows performing a 3DSecured charge transaction using the payment token and previously obtained SCA parameters.

3. Provide Client Credentials

Set your Merchant Application ID as the value of clientId, and the Merchant Secret as the value of clientSecret.

The example code will set the accessToken value when the script executes.

4. Add Data

Provide the appropriate data for the request. To create a charge, the following parameters are obtained using the payment widget:

1. The paymentToken previously obtained using the widget.

Ensure the client's IP address is added as a payload ipAddress or header X-Origin-IP) parameter.

2. TransactionData, including the client account number, subaccount, the initial price, and period.

3. If using 3DS, provide the ThreedsParameters previously obtained using the payment widget.

5. Generate Token

Create a function to fetch the OAuth token (getOAuthToken). The function requires the client ID, client secret, and token endpoint to request the token.

The token helps authenticate the payment requests.

6. Charge Transaction and Handle Response

ThechargeTransactionfunction performs the charge based on the provided endpoint, data, payment token, and generated access token.

If calling the function throws no errors, the response is passed to the handleResponse function.

In this case, it only logs the response data. In a realistic scenario, it would allow you to continue processing the transaction and return the response to your client.

7. Test Transaction

The code fetches the OAuth token based on the previously provided data.

If the access token is generated successfully, the code performs a non-3DS transaction and then a 3DSecure transaction, using the previously obtained SCA and other transaction data.

		
import axios from 'axios';
interface TransactionData { clientAccnum: number; clientSubacc: number; initialPrice: number; initialPeriod: number; }
interface ThreedsParameters { threedsEci: string; threedsError: string; threedsStatus: string; threedsClientTransactionId: string; threedsAcsTransId: string; threedsDsTransId: string; threedsCurrency: string; threedsAmount: string; threedsCardToken: string; threedsVersion: string; threedsCavv: string; threedsXid: string; threedsSuccess: string; threedsAuthenticationType: string; threedsAuthenticationValue: string; } interface TransactionResponse { declineCode: number | undefined; declineText: string | undefined; denialId: number | undefined; approved: boolean; paymentUniqueId: string | undefined; sessionId: number | undefined; subscriptionId: number | undefined; newPaymentTokenId: number | undefined; } interface ApiResponse { status: number; data: TransactionResponse; } type ThreedsTransactionData = TransactionData & ThreedsParameters; // Endpoints const baseUrl = 'https://api.ccbill.com';
const tokenEndpoint = `${baseUrl}/ccbill-auth/oauth/token?grant_type=client_credentials`;
const nonThreedsTransactionEndpoint = `${baseUrl}/transactions/payment-tokens/`;
const threedsTransactionEndpoint = `${nonThreedsTransactionEndpoint}threeds/`;
// Client credentials
const clientId = 'YOUR-CLIENT-ID'; const clientSecret = 'YOUR-CLIENT-SECRET';
let accessToken: string | null = ''; // the access token will be obtained during script execution
// Requests data
const paymentToken = 'YOUR-PAYMENT-TOKEN';
const transactionData = { clientAccnum: 900684, clientSubacc: 0, initialPrice: 10, initialPeriod: 10, };
const threedsParameters = { threedsEci: '05', threedsError: '', threedsStatus: 'Y', threedsClientTransactionId: 'mcn-id-h76oy394utw', threedsAcsTransId: 'd6f15aae-2c9d-4333-a920-954be07c0c76', threedsDsTransId: 'd65e93c3-35ab-41ba-b307-767bfc19eae3', threedsCurrency: '978', threedsAmount: '10', threedsCardToken: '01ae5d142g7efb4b', threedsVersion: '2.2.0', threedsCavv: '', threedsXid: '', threedsSuccess: 'true', threedsAuthenticationType: '01', threedsAuthenticationValue: '5VdhGOTXBJw9+kEBOTtaJiLUAr8=', };
async function getOAuthToken(tokenEndpoint: string, clientId: string, clientSecret: string): Promise<string | null> { try { const response = await axios.post(tokenEndpoint, null, { auth: { username: clientId, password: clientSecret, }, }); if (response.status === 200) { return response.data.access_token; } else { console.log('Token request failed with status code:', response.status); console.log('Response content:', response.data); return null; } } catch (error) { console.error('Error while getting the OAuth token:', error); return null; } }
async function chargeTransaction(endpoint: string, accessToken: string, paymentToken: string, transactionData: TransactionData | ThreedsTransactionData): Promise<void> { const headers = { authorization: `Bearer ${accessToken}`, }; try { const response = await axios.post(`${endpoint}${paymentToken}`, transactionData, { headers, }); handleResponse(response); } catch (error) { console.error('Error while charging the transaction:', error); } }
function handleResponse(response: ApiResponse): void { if (response.status === 200) { console.log('Response:', response.data); } else { console.error('Error:', response.data); } }
(async () => { // Get access token accessToken = await getOAuthToken(tokenEndpoint, clientId, clientSecret);
if (accessToken) { // Charge regular transaction await chargeTransaction(nonThreedsTransactionEndpoint, accessToken, paymentToken, transactionData); // Charge threeds verified transaction await chargeTransaction(threedsTransactionEndpoint, accessToken, paymentToken, { ...transactionData, ...threedsParameters, }); } })();

Java

The code example is written in Java. It describes the steps required to perform authentication with the CCBill API and the payment token obtained using the CCBill API Payment Widget to perform the charge by payment token action (non-3DSecure and 3DSecure versions). This script covers the backend portion of the integration with the CCBill's RESTful Transaction API.

1. Install Dependencies

Add the dependencies for building and importing the libraries. For example, if using Maven, you need a pom.xml file that lists all the dependencies with version numbers you want to use:

<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>2.7.1</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-webflux</artifactId> <version>2.7.1</version> </dependency> </dependencies>

2. Define Endpoints

The endpoints section defines the API endpoints you will use throughout the process.

The example uses three endpoints to demonstrate the charge flow:

1. getAuthToken allows requesting the CCBill Auth (Bearer) token required for authentication in subsequent operations.

2. createTransactionallows performing a non-3DSecured charge transaction using the payment token.

3. createThreedsTransactionallows performing a 3DSecured charge transaction using the payment token and previously obtained SCA parameters.

3. Provide Client Credentials

Set your Merchant Application ID as the value of username, and the Merchant Secret as the value of password.

The example code will set theaccess_tokenvalue when the script executes.

4. Add Data

Provide the appropriate data for the request. To create a charge, the following parameters are obtained using the payment widget:

1. The paymentToken previously obtained using the payment widget. Ensure the client's IP address is added as a payload (ipAddress) or header (X-Origin-IP) parameter.

2. TransactionRequestParams, including the client account number, subaccount, the initial price, and period.

3. If using 3DS, provide the ThreedsTransactionRequestParams previously obtained using the payment widget.

5. Generate OAuth Token

Create a function to fetch the OAuth token (getAuthToken). The function requires the username, password, and token endpoint to request the token.

The token helps authenticate the payment requests.

6. Charge Transaction and Handle Response

ThecreateTransactionand createThreedsTransaction functions perform the charge based on the provided endpoint, data, payment token, and generated access token.

If calling the functions throws no errors, the response is passed to the TransactionResponse function.

In this case, it only logs the response data. In a realistic scenario, it would allow you to continue processing the transaction and return the response to your client.

7. Test Transaction

The code fetches the OAuth token based on the previously provided data.

If the access token is generated successfully, the code performs a non-3DS transaction and then a 3DSecure transaction using the previously obtained SCA and other transaction data.

package com.ccbill.mcn.transaction.service.integration.example;

import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;

import java.math.BigDecimal;
import java.math.BigInteger;

@Component
public class IntegrationCodeExamples {

public ResponseEntity<AuthTokenResponse> getAuthToken(String username, String password) {
String base64Credentials = getCredentials(username, password);
WebClient webClient = WebClient.create("https://api.ccbill.com"); return webClient.post() .uri("/ccbill-auth/oauth/token?grant_type=client_credentials")
.header("Authorization", "Basic " + base64Credentials) .header("Content-Type", "application/x-www-form-urlencoded") .retrieve() .toEntity(AuthTokenResponse.class) .block(); }
public ResponseEntity<TransactionResponse> createTransaction(String authToken, String paymentToken, TransactionRequestParams transactionRequestParams) {
WebClient webClient = WebClient.create("https://api.ccbill.com"); return webClient.post() .uri("transactions/payment-tokens/" + paymentToken)
.header("Authorization", "Bearer " + authToken) .bodyValue(transactionRequestParams) .retrieve() .toEntity(TransactionResponse.class) .block(); }
public ResponseEntity<TransactionResponse> createThreedsTransaction(String authToken, String paymentToken, ThreedsTransactionRequestParams threedsTransactionRequestParams) {
WebClient webClient = WebClient.builder().baseUrl("https://api.ccbill.com").build(); return webClient.post() .uri("/transactions/payment-tokens/threeds/" + paymentToken)
.header("Authorization", "Bearer " + authToken) .body(BodyInserters.fromValue(threedsTransactionRequestParams)) .retrieve() .toEntity(TransactionResponse.class) .block(); }
private String getCredentials(String username, String password) { String credentials = username + ":" + password; byte[] credentialsBytes = credentials.getBytes(); byte[] base64 = Base64.encodeBase64(credentialsBytes); return new String(base64); }
public static class AuthTokenResponse { private String access_token; private String token_type; private Long expires_in; private String scope; private String jti; public String getAccess_token() { return access_token; } public void setAccess_token(String access_token) { this.access_token = access_token; } public String getToken_type() { return token_type; } public void setToken_type(String token_type) { this.token_type = token_type; } public Long getExpires_in() { return expires_in; } public void setExpires_in(Long expires_in) { this.expires_in = expires_in; } public String getScope() { return scope; } public void setScope(String scope) { this.scope = scope; } public String getJti() { return jti; } public void setJti(String jti) { this.jti = jti; } }
public static class TransactionRequestParams { private Integer clientAccnum; private Integer clientSubacc; private BigDecimal initialPrice; private Long initialPeriod; public Integer getClientAccnum() { return clientAccnum; } public void setClientAccnum(Integer clientAccnum) { this.clientAccnum = clientAccnum; } public Integer getClientSubacc() { return clientSubacc; } public void setClientSubacc(Integer clientSubacc) { this.clientSubacc = clientSubacc; } public BigDecimal getInitialPrice() { return initialPrice; } public void setInitialPrice(BigDecimal initialPrice) { this.initialPrice = initialPrice; } public Long getInitialPeriod() { return initialPeriod; } public void setInitialPeriod(Long initialPeriod) { this.initialPeriod = initialPeriod; } }
public static class ThreedsTransactionRequestParams extends TransactionRequestParams { private String threedsEci; private String threedsError; private String threedsStatus; private String threedsSuccess; private String threedsVersion; private String threedsXid; private String threedsCavv; private BigDecimal threedsAmount; private String threedsClientTransactionId; private String threedsAcsTransId; private String threedsDsTransId; private String threedsCurrency; private String threedsCardToken; private String threedsAuthenticationType; private String threedsAuthenticationValue; public String getThreedsAuthenticationType() { return threedsAuthenticationType; } public void setThreedsAuthenticationType(String threedsAuthenticationType) { this.threedsAuthenticationType = threedsAuthenticationType; } public String getThreedsAuthenticationValue() { return threedsAuthenticationValue; } public void setThreedsAuthenticationValue(String threedsAuthenticationValue) { this.threedsAuthenticationValue = threedsAuthenticationValue; } public String getThreedsClientTransactionId() { return threedsClientTransactionId; } public void setThreedsClientTransactionId(String threedsClientTransactionId) { this.threedsClientTransactionId = threedsClientTransactionId; } public String getThreedsAcsTransId() { return threedsAcsTransId; } public void setThreedsAcsTransId(String threedsAcsTransId) { this.threedsAcsTransId = threedsAcsTransId; } public String getThreedsEci() { return threedsEci; } public void setThreedsEci(String threedsEci) { this.threedsEci = threedsEci; } public String getThreedsError() { return threedsError; } public void setThreedsError(String threedsError) { this.threedsError = threedsError; } public String getThreedsStatus() { return threedsStatus; } public void setThreedsStatus(String threedsStatus) { this.threedsStatus = threedsStatus; } public String getThreedsSuccess() { return threedsSuccess; } public void setThreedsSuccess(String threedsSuccess) { this.threedsSuccess = threedsSuccess; } public String getThreedsVersion() { return threedsVersion; } public void setThreedsVersion(String threedsVersion) { this.threedsVersion = threedsVersion; } public String getThreedsXid() { return threedsXid; } public void setThreedsXid(String threedsXid) { this.threedsXid = threedsXid; } public String getThreedsCavv() { return threedsCavv; } public void setThreedsCavv(String threedsCavv) { this.threedsCavv = threedsCavv; } public BigDecimal getThreedsAmount() { return threedsAmount; } public void setThreedsAmount(BigDecimal threedsAmount) { this.threedsAmount = threedsAmount; } public String getThreedsDsTransId() { return threedsDsTransId; } public void setThreedsDsTransId(String threedsDsTransId) { this.threedsDsTransId = threedsDsTransId; } public String getThreedsCurrency() { return threedsCurrency; } public void setThreedsCurrency(String threedsCurrency) { this.threedsCurrency = threedsCurrency; } public String getThreedsCardToken() { return threedsCardToken; } public void setThreedsCardToken(String threedsCardToken) { this.threedsCardToken = threedsCardToken; } }
public static class TransactionResponse { private Long declineCode; private String declineText; private BigInteger denialId; private boolean approved; private String paymentUniqueId; private String sessionId; private Long subscriptionId; private String newPaymentTokenId; public Long getDeclineCode() { return declineCode; } public void setDeclineCode(Long errorCode) { this.declineCode = errorCode; } public String getDeclineText() { return declineText; } public void setDeclineText(String declineText) { this.declineText = declineText; } public BigInteger getDenialId() { return denialId; } public void setDenialId(BigInteger denialId) { this.denialId = denialId; } public boolean isApproved() { return approved; } public void setApproved(boolean approved) { this.approved = approved; } public String getPaymentUniqueId() { return paymentUniqueId; } public void setPaymentUniqueId(String paymentUniqueId) { this.paymentUniqueId = paymentUniqueId; } public String getSessionId() { return sessionId; } public void setSessionId(String sessionId) { this.sessionId = sessionId; } public Long getSubscriptionId() { return subscriptionId; } public void setSubscriptionId(Long subscriptionId) { this.subscriptionId = subscriptionId; } public String getNewPaymentTokenId() { return newPaymentTokenId; } public void setNewPaymentTokenId(String newPaymentTokenId) { this.newPaymentTokenId = newPaymentTokenId; } } }

Python

The code example is written in Python. It describes the steps required to perform authentication with the CCBill API and the payment token obtained using the CCBill API Payment Widget to perform the charge by payment token action (non-3DSecure and 3DSecure versions). This script covers the backend portion of the integration with the CCBill's RESTful Transaction API

1. Install Libraries

The Python backend uses the requests library to send API requests. Download the module using the PIP package manager:

pip install requests

Import the requests library and the requests.HTTPBasicAuth module.

2. Define Endpoints

The endpoints section defines the API endpoints you will use throughout the process. The example uses three endpoints to demonstrate the charge flow:

1. token_endpoint allows requesting the CCBill Auth (Bearer) token required for authentication in subsequent operations.

2. non_threeds_transaction_endpoint allows performing a non-3DSecured charge transaction using the payment token.

3. threeds_transaction_endpoint allows performing a 3DSecured charge transaction using the payment token and previously obtained SCA parameters.

3. Provide Client Credentials

Set your Merchant Application ID as the value of client_id and the Merchant Secret as the value of client_secret.

The example code will set the accessToken value when the script executes.

4. Add Data

Provide the appropriate data for the request. To create a charge, the following parameters are obtained using the payment widget:

1. The payment_token previously obtained using the payment widget.

Ensure the client's IP address is added as a payload (ipAddress) or header (X-Origin-IP) parameter.

2. transaction_data, including the client account number, subaccount, the initial price, and period.

3. If using 3DS, provide the threeds_parameters previously obtained using the payment widget.

5. Generate Token

Create a function to fetch the OAuth token (get_oauth_token). The function requires the client ID, client secret, and token endpoint to request the token.

The token helps authenticate the payment requests.

6. Charge Transaction and Handle Response

The charge_transaction function performs the charge based on the provided endpoint, data, payment token, and generated access token.

If calling the function throws no errors, the response is passed to the handle_response function.

In this case, it only logs the response data. In a realistic scenario, it would allow you to continue processing the transaction and return the response to your client.

7. Test Transaction

The code fetches the OAuth token based on the previously provided data.

If the access token is generated successfully, the code performs a non-3DS transaction and then a 3DSecure transaction using the previously obtained SCA and other transaction data.

# import libraries import requests from requests.auth import HTTPBasicAuth
# endpoints base_url = "https://api.ccbill.com"
token_endpoint = f"{base_url}/ccbill-auth/oauth/token"
non_threeds_transaction_endpoint = f"{base_url}/transactions/payment-tokens/"
threeds_transaction_endpoint = f"{non_threeds_transaction_endpoint}threeds/"
# client credentials
client_id = "YOUR-CLIENT-ID" client_secret = "YOUR-CLIENT-SECRET"
access_token = "" # the access token will be obtained during script execution
# requests data
payment_token = "YOUR-PAYMENT-TOKEN";
transaction_data = { "clientAccnum": 900000, "clientSubacc": 0, "initialPrice": 0, "initialPeriod": 0 }
threeds_parameters = { "threedsEci": "00", "threedsError": "", "threedsStatus": "Y", "threedsClientTransactionId": "mcn-id-h76oy394utw", "threedsAcsTransId": "d6f15aae-2c9d-4333-a920-954be07c0c76", "threedsDsTransId": "d65e93c3-35ab-41ba-b307-767bfc19eae3", "threedsCurrency": "978", "threedsAmount": "10", "threedsCardToken": "01ae5d142g7efb4b", "threedsVersion": "2.1.0", "threedsCavv": "", "threedsXid": "", "threedsSuccess": "true", "threedsAuthenticationType": "01", "threedsAuthenticationValue": "5VdhGOTXBJw9+kEBOTtaJiLUAr8=" }
def get_oauth_token(token_endpoint, client_id, client_secret): data = { "grant_type": "client_credentials" } response = requests.post( token_endpoint, data=data, auth=HTTPBasicAuth(client_id, client_secret) ) if response.status_code == 200: return response.json().get("access_token") else: print("Token request failed with status code:", response.status_code) print("Response content:", response.content) return None
def charge_transaction(endpoint, access_token, payment_token, transaction_data): headers = { "Authorization": f"Bearer {access_token}" } response = requests.post( f"{endpoint}{payment_token}", json=transaction_data, headers=headers ) handle_response(response)
def handle_response(response): if response.status_code == 200: print("Response: ", response.json()) else: print("Error: ", response.content) return None
if __name__ == "__main__":
# get access token access_token = get_oauth_token(token_endpoint, client_id, client_secret)
if access_token: # charge regular transaction charge_transaction( non_threeds_transaction_endpoint, access_token, payment_token, transaction_data ) # charge threeds verified transaction charge_transaction(threeds_transaction_endpoint, access_token, payment_token, {**transaction_data, **threeds_parameters} )