@chargx/sdk
v0.29.0
Published
SDK for ChargX payment provider
Readme
Chargx payment gateway SDK
A React hook to simplify integrating Chargx payments into your React application. This SDK handles loading the Chargx js script, performing secure transactions, and interacting with loyalty point features.
🚀 Features
- Handles pre-transaction setup
- Dispatches secure payment data (card or bank)
- Processes transactions
- Checks customer loyalty points
📦 Installation
npm install @chargx/sdk --save🧹 Usage
1. Import and Initialize Hook
import {
usePayment,
type AuthData,
type PretransactResponse,
} from "@chargx/sdk";
const {
pretransact,
load,
transact,
dispatchData,
checkCustomerLoyaltyPoints,
scriptLoaded,
scriptError,
} = usePayment("your-publishable-key-here", "https://api-endpoint");2. Init lib on Component Mount
Call this once on mount to retrieve authData and determine the environment. Store authData in your component state for later use:
const [authData, setAuthData] = useState<AuthData | undefined>();
useEffect(() => {
pretransact().then((response: PretransactResponse) => {
setAuthData(response.authData);
load(response.isProduction ? "PRODUCTION" : "SANDBOX");
});
}, []);authDatais required fordispatchDataisProductionis used to load the appropriate script version
3. Submit Payment
Call dispatchData() and transact() inside your form submission handler:
const cardData = {
cardNumber: "4111111111111111",
cardCode: "123",
month: "12",
year: "29",
};
const billingAddress = {
street: "...",
unit: "...",
city: "...",
state: "...",
zipCode: "...",
countryCode: "...",
phone: "...",
};
const orderId = "order id from your app" // for logging purpose
const handleSubmit = async () => {
try {
const response = await dispatchData({
cardData,
authData: authData as AuthData,
});
const opaqueData = response.opaqueData ? {
dataDescriptor: response.opaqueData.dataDescriptor,
dataValue: response.opaqueData.dataValue,
} : { token: response.token };
await transact({
currency: "USD",
amount: amount,
type: "fiat",
opaqueData,
customer: {
name: cardholderName,
email,
},
deductLoyaltyPoints: pointsToDeduct,
billingAddress, // optionally pass builling address
orderId // optionally pass order id from your system
});
console.log("Payment successful!");
} catch (dispatchErrors) {
console.error("dispatchErrors", dispatchErrors);
}
};4. Check Customer Loyalty Points (Optional)
You can call this when the customer enters their email, e.g. on blur of the email input field:
const fetchLoyaltyPoints = async (email: string) => {
const loyaltyPoints = await checkCustomerLoyaltyPoints({ email });
};
await transact({
...
deductLoyaltyPoints: loyaltyPoints,
});🧬 API Reference
pretransact() => Promise<PretransactResponse>
Initializes the session. Returns:
authData: required to securely send card/bank dataisProduction: boolean used to decide environment for script loading
load(environment: "PRODUCTION" | "SANDBOX") => void
Dynamically loads the underlying js scripts. Must be called after pretransact().
dispatchData(secureData: SecureData) => Promise<DispatchDataResponse>
Sends card/bank data securely to payment processor. Requires authData from pretransact().
transact(payload: TransactPayload) => Promise<any>
Finalizes the transaction on your server using opaque data received from dispatchData().
checkCustomerLoyaltyPoints({ email: string }) => Promise<CustomerLoyaltyPoints>
Fetches customer loyalty points by email.
State Flags
| Variable | Description |
| -------------- | ------------------------------- |
| scriptLoaded | true if the script is loaded |
| scriptError | true if script loading failed |
🛠 Requirements
- An active ChargX account
- Your publishable API key (can be obtained via ChargxX dashboard)
