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.
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.
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.
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.
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.
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.
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.
ThechargeTransaction
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 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.
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, }); } })();
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.
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>
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. createTransaction
allows performing a non-3DSecured charge transaction using the payment token.
3. createThreedsTransaction
allows performing a 3DSecured charge transaction using the payment token and previously obtained SCA parameters.
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_token
value when the script executes.
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.
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.
ThecreateTransaction
and 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.
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; } } }
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
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.
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.
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.
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.
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.
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.
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}
)