Services
Basis Theory Elements offers several methods and to interact with the underlying data and services to collect or share data safely.
Methods
Once you have created and mounted an element instance, you can invoke the methods below:
<div id="my-card"></div>
<script>
var cardElement = BasisTheory.createElement("card");
await cardElement.mount("#my-card");
cardElement.focus();
</script>
Name | Resulting Type | Eligible Elements | Description |
---|---|---|---|
clear | void | All | Clears the element input(s) value. |
focus | void | All | Focuses on the element input. |
blur | void | All | Blurs the element input. |
month | number | cardExpirationDate | Data-parsing method that resolves to the month value of the input date, where "January" = 1. |
year | number | cardExpirationDate | Data-parsing method that resolves to the four-digit year value of the input date. |
format * | string | cardExpirationDate | Data-parsing method that takes a date format as an argument and returns the expiration date in the given format. |
setValue | void | All | Accepts a synthetic reference from a retrieved token and safely sets it as the input value. |
setValueRef * | void | text cardNumber cardExpirationDate cardElement cardVerificationCode | Sets the element's value to the value of the provided element. |
Format*
Our card expiration date format implements Luxon's toFormat, so all of Luxon's date formatting tokens are available.
const cardExpirationDateElement = BasisTheory.createElement("cardExpirationDate", {
targetId: "expirationDate",
value: "04/25",
});
...
const requestBody = {
...
expiration_date1: cardExpirationDateElement.format("yyyy-MM"), // 2025-04
expiration_date2: cardExpirationDateElement.format("MM"), // 04
expiration_date3: cardExpirationDateElement.format("M"), // 4
expiration_date4: cardExpirationDateElement.format("MM/yyyy"), // 04/2025
expiration_date5: cardExpirationDateElement.format("yy"), // 25
...
}
setValueRef*
Sets the element's value to the value of the provided element.
const cardExpirationDateElement = BasisTheory.createElement("cardExpirationDate", {
targetId: "expirationDate",
value: "04/25",
});
const cardExpirationDateElementReadOnly = BasisTheory.createElement("cardExpirationDate", {
targetId: "expirationDateReadOnly",
readOnly: true
});
cardExpirationDateElementReadOnly.setValueRef(cardExpirationDateElement)
cardExpirationDateElementReadOnly
will be updated every time the value of cardExpirationDateElement
changes.
setValueRef
to keep an element in sync with another element, or to set the text of an element, it is strongly recommended that you make the element that is being acted upon readonly
. This is possible by setting readOnly
to true
.Tokenization Services
Element values can be securely tokenized by simply passing the Element instance (or one of its data parsing methods) in the tokenization payload.
plainText
values, data will be HTML encoded before storage for security reasons.Create Token
The examples below show how to use Elements instances in the payload of the tokens.create
service.
BasisTheory.tokens
.create({
type: "token",
data: {
sensitiveData: sensitiveDataElement,
nonSensitiveData: "plainText", // see warning on plain text data
otherData: {
someInteger: 20,
someBoolean: false,
},
someOtherData: ["plainText1", "plainText2"],
},
metadata: {
nonSensitiveField: "nonSensitiveValue",
},
})
.then((token) => {
console.log(token.id); // token to store
console.log(JSON.stringify(token)); // full response
});
BasisTheory.tokens
.create({
type: "card",
data: cardElement,
})
.then((token) => {
console.log(token.id); // token to store
console.log(JSON.stringify(token.data)); // masked card data
});
BasisTheory.tokens
.create({
type: "card",
data: {
number: cardNumberElement,
expiration_month: cardExpirationDateElement.month(),
expiration_year: cardExpirationDateElement.year(),
cvc: cardVerificationCodeElement
}
})
.then((token) => {
console.log(token.id); // token to store
console.log(JSON.stringify(token.data)); // masked card data
});
BasisTheory.tokens
.create({
type: "bank",
data: {
routingNumber: routingNumberElement,
accountNumber: accountNumberElement,
},
})
.then((token) => {
console.log(token.id); // token to store
console.log(JSON.stringify(token.data)); // redacted bank data
});
Tokenize
The example below shows how to use Elements instances in the payload of the tokenize
service.
BasisTheory.tokenize({
card1: {
type: "card",
data: cardElement,
},
card2: {
type: "card",
data: {
number: cardNumberElement,
expiration_month: cardExpirationDateElement.month(),
expiration_year: cardExpirationDateElement.year(),
cvc: cardVerificationCodeElement,
},
},
sensitiveData: sensitiveDataElement,
nonSensitiveData: "plainText", // see warning on plain text data
otherData: {
someInteger: 20,
someBoolean: false,
},
someOtherData: ["plainText1", "plainText2"],
}).then((tokens) => {
console.log(tokens.card1.id, tokens.card2.id, tokens.sensitiveData); // token to store
console.log(JSON.stringify(tokens)); // full response
});
Token Update
Aside from creating tokens, an Element value can be used to update a token using tokens.update
.
To do that, simply pass the Element instance (or one of its data parsing methods) in the payload.
BasisTheory.tokens
.update("ca9f3fd7-3906-4087-83aa-9a6129221297", {
// replace w/ desired token id
data: cardElement,
})
.then((token) => {
console.log(JSON.stringify(token.data)); // redacted updated token data
});
Create Token Intent
The examples below show how to use Elements instances in the payload of the tokenIntents.create
service.
BasisTheory.tokenIntents
.create({
type: "card",
data: cardElement
})
.then((tokenIntent) => {
console.log(tokenIntent.id); // token intent id to validate and convert to a token
});
BasisTheory.tokenIntents
.create({
type: "card",
data: {
number: cardNumberElement,
expiration_month: cardExpirationDateElement.month(),
expiration_year: cardExpirationDateElement.year(),
cvc: cardVerificationCodeElement
}
})
.then((tokenIntent) => {
console.log(tokenIntent.id); // token intent id to validate and convert to a token
});
Detokenization Services
Element values can be securely detokenized and revealed using these detokenization services and the Element's setValue
method.
Retrieve Token
When retrieve
is called from a Basis Theory instance configured with elements: true
, the API request is made from inside a Basis Theory hosted iframe
and the returned data remains within it.
The examples below show how to use retrieve
and setValue
, but for more information on revealing and session keys, visit the Reveal Tokenized Data guide.
const textElement = BasisTheory.createElement("text", {
targetId: "text-element",
});
BasisTheory.tokens
.retrieve("ca9f3fd7-3906-4087-83aa-9a6129221297", {
apiKey: "<SESSION_API_KEY>", // api key is required and should belong to a session
})
.then((token) => {
textElement.setValue(token.data);
});
const cardElement = BasisTheory.createElement("card");
BasisTheory.tokens
.retrieve("ca9f3fd7-3906-4087-83aa-9a6129221297", {
apiKey: "<SESSION_API_KEY>", // api key is required and should belong to a session
})
.then((token) => {
cardElement.setValue(token.data);
});
// or
BasisTheory.tokens
.retrieve("ca9f3fd7-3906-4087-83aa-9a6129221297", {
apiKey: "<SESSION_API_KEY>", // api key is required and should belong to a session
})
.then((token) => {
cardElement.setValue({
number: token.data.number, // expects string
expiration_month: token.data.expiration_month, // expects number
expiration_year: token.data.expiration_year, // expects number
});
});
const cardNumberElement = BasisTheory.createElement("cardNumber", {
targetId: "card-number",
});
const cardExpirationDateElement = BasisTheory.createElement("cardExpirationDate", { targetId: "card-expiration-date" });
BasisTheory.tokens
.retrieve("ca9f3fd7-3906-4087-83aa-9a6129221297", {
apiKey: "<SESSION_API_KEY>", // api key is required and should belong to a session
})
.then((token) => {
cardNumberElement.setValue(token.data.number);
cardExpirationDateElement.setValue({
month: token.data.expiration_month,
year: token.data.expiration_year,
});
});
data
attribute in the token returned by the retrieve
method is not the actual data, but a a synthetic representation of the sensitive detokenized data.metadata
are directly accessible from the retrieve
response as they are considered non-sensitive.Proxy Service
This service wraps the proxy API endpoint to proxy a request to a third-party API.
Invoking Proxy
When a proxy is invoked from a Basis Theory instance configured with elements: true
, the API request is made from inside a Basis Theory hosted iframe
and the returned data remains within it, whether the proxy has Elements instances in its body
or not.
The examples below show how to invoke the proxy and use setValue
, but for more information on revealing and session keys, visit the Reveal Data from 3rd Party guide.
Elements can be used to proxy data securely by including them in the proxy body
as shown in the example.
const submitElement = BasisTheory.createElement("text", {
targetId: "submitElement",
});
const revealElement = BasisTheory.createElement("text", {
targetId: "revealElement",
});
BasisTheory.proxy
.post({
headers: {
"BT-PROXY-KEY": "e29a50980ca5", // replace with your pre-configured proxy key (if pre-configured)
},
body: {
sensitiveValue: submitElement,
nonSensitiveValue: "plainText",
},
apiKey: "<SESSION_API_KEY>",
})
.then((response) => {
revealElement.setValue(response.value);
});
Proxy Invocation Methods
The Elements proxy service supports all of the same HTTP methods that the ephemeral or pre-configured proxy APIs support. All proxy calls take the same options object as a parameter.
Signature | Description |
---|---|
get(proxyRequest: ProxyRequestOptions) | Performs a proxy GET request. |
post(proxyRequest: ProxyRequestOptions) | Performs a proxy POST request. |
put(proxyRequest: ProxyRequestOptions) | Performs a proxy PUT request. |
patch(proxyRequest: ProxyRequestOptions) | Performs a proxy PATCH request. |
delete(proxyRequest: ProxyRequestOptions) | Performs a proxy DELETE request. |
ProxyRequestOptions
Attribute | Type | Required | Description |
---|---|---|---|
path | string | false | String that gets added to the end of the proxied URL path. |
query | object | false | Key/Value pairs that are added as a query parameter to the proxied URL. |
headers | object | false | Key/Value pairs that are added as headers when invoking the proxied URL. |
body | object | false | Payload that gets sent to the proxied URL. Can contain Elements. |
apiKey | object | false | BasisTheory API Key for authentication |
correlationId | object | false | ID that can be used for request correlation |
idempotencyKey | object | false | Key used for request idempotency |
Access non-sensitive responses from Proxy calls Beta
Our Elements enable you to convert proxy responses into plain text, which is ideal for non-sensitive data handling. This enhancement streamlines your data processing workflows and facilitates an easier understanding of the returned data, bypassing decryption or tokenization.
This feature is currently invite-only. If you're interested, please get in touch for an invitation.
HTTP Client Service
Element values can be used in a request to a third-party API using our HTTP client service.
Post
The example below shows how to use the HTTP client service to make a POST request to a third-party API with an element in the payload.
const bt = await new BasisTheory().init("<API_KEY>", { elements: true });
bt.client.post(
"https://www.api.thirdpartydomain.com/resources",
{
sensitiveData: sensitiveDataElement,
nonSensitiveData: "plainText", // see warning on plain text data
otherData: {
someInteger: 20,
someBoolean: false,
},
someOtherData: ["plainText1", "plainText2"],
},
{
headers: {
"Content-Type": "application/json",
},
}
).then((response) => {
console.log(JSON.stringify(response)); // full plaintext response
});
Put
The example below shows how to use the HTTP client service to make a PUT request to a third-party API with an element in the payload.
const bt = await new BasisTheory().init("<API_KEY>", { elements: true });
bt.client.put(
"https://www.api.thirdpartydomain.com/resources/id",
{
sensitiveData: sensitiveDataElement,
nonSensitiveData: "plainText", // see warning on plain text data
otherData: {
someInteger: 20,
someBoolean: false,
},
someOtherData: ["plainText1", "plainText2"],
},
{
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
}
).then((response) => {
console.log(JSON.stringify(response)); // full plaintext response
});
Patch
The example below shows how to use the HTTP client service to make a PATCH request to a third-party API with an element in the payload.
const bt = await new BasisTheory().init("<API_KEY>", { elements: true });
bt.client.patch(
"https://www.api.thirdpartydomain.com/resources/id",
{
sensitiveData: sensitiveDataElement,
nonSensitiveData: "plainText", // see warning on plain text data
otherData: {
someInteger: 20,
someBoolean: false,
},
someOtherData: ["plainText1", "plainText2"],
},
{
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
}
).then((response) => {
console.log(JSON.stringify(response)); // full plaintext response
});
Get
The example below shows how to use the HTTP client service to make a GET request to a third-party API.
const bt = await new BasisTheory().init("<API_KEY>", { elements: true });
bt.client.get("https://www.api.thirdpartydomain.com/resources/id", {
headers: {
Accept: "application/json",
},
}).then((response) => {
console.log(JSON.stringify(response)); // full plaintext response
});
Delete
The example below shows how to use the HTTP client service to make a DELETE request to a third-party API.
const bt = await new BasisTheory().init("<API_KEY>", { elements: true });
bt.client.delete("https://www.api.thirdpartydomain.com/resources/id", {
headers: {
Accept: "application/json",
},
}).then((response) => {
console.log(JSON.stringify(response)); // full plaintext response
});
Errors
Basis Theory Service Errors
Basis Theory element services could throw an error based on client-side validations or if the server rejects the request.
import { BasisTheoryApiError, BasisTheoryValidationError } from "@basis-theory/basis-theory-js/common";
BasisTheory.tokenize({
card1: {
type: "card",
data: cardElement1,
},
card2: {
type: "card",
data: cardElement2,
},
ssn: textElement,
}).catch((error) => {
if (error instanceof BasisTheoryValidationError) {
// only applies to tokenization
// check error details
} else if (error instanceof BasisTheoryApiError) {
// check error data or status
}
});
HTTP Client Service Errors
HTTP client services could throw an error based on client-side validations or if the server rejects the request.
import { HttpClientError, BasisTheoryValidationError } from "@basis-theory/basis-theory-js/common";
const bt = await new BasisTheory().init("<API_KEY>", { elements: true });
bt.client.post({
sensitiveData: textElement,
}).catch((error) => {
if (error instanceof BasisTheoryValidationError) {
// check error details
} else if (error instanceof HttpClientError) {
// check error data, status, or headers
}
});
BasisTheoryValidationError
{
details: {
card1: {
number: {
type: 'invalid'
},
cvc: {
type: 'incomplete'
}
},
card2: {
}
},
validation: [] // deprecated
}
Attribute | Type | Description |
---|---|---|
name | string | Error name, always 'BasisTheoryValidationError' . |
details | object | Maps payload properties to their respective element's validation problems. |
BasisTheoryApiError
{
data: {
// API response body
},
status: 400
}
Attribute | Type | Description |
---|---|---|
name | string | Error name, always 'BasisTheoryApiError' . |
data | object | Response body sent from the server. |
status | number | Response HTTP status. |
name
property may be used instead of checking its instance type.HttpClientError
{
data: {...},
status: 400,
headers: {...}
}
Attribute | Type | Description |
---|---|---|
name | string | Error name, always 'HttpClientError' . |
data | object | Response body sent from the server. |
status | number | Response HTTP status. |
headers | object | Response HTTP headers. |