@one-cp/web-checkout
v2.0.7
Published
This is the One-CP Web Checkout package
Readme
One-CP Web Checkout SDK
The One-CP Web SDK is a lightweight, secure, and powerful JavaScript library that seamlessly integrates the One-CP Corporate Checkout experience directly into your web applications. Built with TypeScript and thoroughly tested (32/32 tests passing), it's designed to streamline corporate purchasing with an intuitive checkout process.
✨ Features
- 🚀 Easy Integration: Works with any JavaScript framework or vanilla HTML
- 🎨 Customizable UI: Full theming support with custom colors and branding
- 🌍 Multi-language: Built-in support for English and German
- 📱 Responsive Design: Optimized for desktop and mobile experiences
- 🔒 Secure: Built with security best practices and origin validation
- ⚡ Lightweight: Minimal bundle size with zero dependencies
- 🔧 TypeScript Ready: Full TypeScript support with comprehensive type definitions
- ✅ Battle-tested: 100% test coverage with comprehensive unit tests
📦 Installation
NPM/Yarn
npm install @one-cp/web-checkoutyarn add @one-cp/web-checkoutCDN
<script src="https://one-cp-public.s3.eu-central-1.amazonaws.com/init.min.js"></script>🚀 Quick Start
ES6/TypeScript
import { init } from '@one-cp/web-checkout';
const cleanup = init({
transactionID: 'your-transaction-id',
widgetID: 'your-widget-id',
config: {
env: 'production', // or 'sandbox'
mode: 'lightbox', // or 'inline'
lang: 'en' // or 'de'
},
onSuccess: (data) => {
console.log('Purchase completed!', data);
},
onError: (error) => {
console.error('Purchase failed:', error);
},
onClose: () => {
console.log('Checkout closed');
}
});
// Clean up when done (important for SPAs)
// cleanup();HTML/CDN
<!DOCTYPE html>
<html>
<head>
<title>One-CP Checkout</title>
</head>
<body>
<div id="checkout-container"></div>
<script src="https://one-cp-public.s3.eu-central-1.amazonaws.com/init.min.js"></script>
<script>
OneCP.init({
transactionID: 'your-transaction-id',
config: {
mode: 'inline',
containerID: 'checkout-container'
},
onSuccess: (data) => console.log('Success!', data)
});
</script>
</body>
</html>📋 API Reference
init(options: OneCPInit): void
Initializes the One-CP checkout widget.
Parameters
| Parameter | Type | Required | Description |
| --------------- | ------------------------------ | -------- | ---------------------------------------------- |
| transactionID | string | ✅ | Unique transaction identifier |
| widgetID | string | ❌ | Widget configuration ID |
| config | OneCPCheckoutConfig | ❌ | Checkout configuration options |
| onSuccess | (data: CheckoutInfo) => void | ❌ | Success callback |
| onError | (message: string) => void | ❌ | Error callback |
| onClose | () => void | ❌ | Close callback |
Configuration Options
| Property | Type | Default | Description |
| ------------------------ | ---------------------------- | ------------- | ------------------------------------------ |
| env | 'sandbox' \| 'production' | 'sandbox' | Environment configuration |
| mode | 'lightbox' \| 'inline' | 'lightbox' | Display mode |
| containerID | string | - | Container element ID (required for inline) |
| expand | boolean | false | Auto-expand checkout |
| viewOnly | boolean | false | Read-only mode |
| useTemplateData | boolean | false | Use template data (view-only mode) |
| lang | 'en' \| 'de' | 'en' | Interface language |
| redirectURL | string | - | Redirect URL after completion |
| colors | ColorConfig | - | Custom color theme |
| logoURL | string | - | Custom logo URL |
| hidePriceOverThumbnail | boolean | false | Hide price overlay |
| hideCo2Tag | boolean | false | Hide CO2 emissions tag |
Response Data Types
CheckoutInfo
interface CheckoutInfo {
reference: string;
payment: {
reference: string;
provider: string;
};
customer: {
firstName: string;
lastName: string;
email?: string;
phone?: string;
address?: Address;
};
beneficiary?: {
firstName: string;
lastName: string;
email: string;
};
billing: {
name?: string;
email: string;
address: Address;
externalIds: Record<string, string>;
identifiers: CompanyIdentifiers;
};
card?: PaymentCardData;
reporting?: Record<string, string | number>;
}CompanyIdentifiers
interface CompanyIdentifiers {
VATIN: string; // VAT Identification Number
BIC?: string; // Bank Identifier Code
DID?: string; // Data Universal Numbering System
GLN?: string; // Global Location Number
DUNS?: string; // Data Universal Numbering System
TIN?: string; // Taxpayer Identification Number
LEI?: string; // Legal Entity Identifier
IATA?: string; // International Air Transport Association code
}🎨 Customization
Color Theming
Customize the checkout appearance with a comprehensive color system:
init({
transactionID: 'your-id',
config: {
colors: {
'primary-color': '#0866b6',
'primary-color-white': '#ffffff',
'primary-color-light': '#f9f9fb',
'dark-primary-text': '#000000de',
'light-primary-text': '#ffffff',
'accent-color': '#88c7fd',
'danger-color': '#eb445a',
'danger-color-text': '#eb445a',
'medium-color-shade': '#b2b8cd',
'medium-color-gray': '#8d8d8d',
'tertiary-color-shade-tint': '#d8e4e3',
'lightbox-color': '#2e2f4690'
}
}
});Custom Branding
init({
transactionID: 'your-id',
config: {
logoURL: 'https://your-domain.com/logo.png',
hidePriceOverThumbnail: true,
hideCo2Tag: false
}
});🌐 Internationalization
The SDK supports multiple languages with automatic detection:
// Explicit language setting
init({
transactionID: 'your-id',
config: {
lang: 'de' // German interface
}
});
// Browser language detection (default)
init({
transactionID: 'your-id'
// Will use browser language or fall back to English
});Supported languages:
- English (
'en') - Default - German (
'de') - Deutsch
🔧 Advanced Usage
Single Page Applications (SPAs)
For SPAs, proper cleanup is essential to prevent memory leaks:
// React example
import { useEffect } from 'react';
import { init } from '@one-cp/web-checkout';
function CheckoutComponent({ transactionID }) {
useEffect(() => {
const cleanup = init({
transactionID,
onSuccess: (data) => {
// Handle success
}
});
// Cleanup on unmount
return cleanup;
}, [transactionID]);
return <div id="checkout-container" />;
}Multiple Instances
import { cleanupAllInstances } from '@one-cp/web-checkout';
// Initialize multiple checkouts
const cleanup1 = init({ transactionID: 'tx1' });
const cleanup2 = init({ transactionID: 'tx2' });
// Clean up all at once
cleanupAllInstances();Error Handling
init({
transactionID: 'your-id',
onError: (error) => {
// Handle specific error types
switch (error) {
case 'Transaction not found':
// Handle transaction errors
break;
case 'Payment failed':
// Handle payment errors
break;
default:
// Handle other errors
console.error('Checkout error:', error);
}
}
});🔒 Security Features
- Origin Validation: All messages are validated against trusted One-CP domains
- HTTPS Only: Secure communication in production environments
- Input Sanitization: All user inputs are properly sanitized
- Content Security Policy: Compatible with strict CSP configurations
🏗️ Framework Integration
React
import React, { useEffect, useRef } from 'react';
import { init } from '@one-cp/web-checkout';
interface CheckoutProps {
transactionID: string;
onSuccess?: (data: any) => void;
}
export const OneCPCheckout: React.FC<CheckoutProps> = ({
transactionID,
onSuccess
}) => {
const cleanupRef = useRef<(() => void) | null>(null);
useEffect(() => {
cleanupRef.current = init({
transactionID,
config: { mode: 'inline', containerID: 'checkout-container' },
onSuccess
});
return () => {
cleanupRef.current?.();
};
}, [transactionID, onSuccess]);
return <div id="checkout-container" style={{ minHeight: '600px' }} />;
};Vue.js
<template>
<div id="checkout-container" style="min-height: 600px;"></div>
</template>
<script>
import { init } from '@one-cp/web-checkout';
export default {
name: 'OneCPCheckout',
props: {
transactionID: {
type: String,
required: true
}
},
mounted() {
this.cleanup = init({
transactionID: this.transactionID,
config: {
mode: 'inline',
containerID: 'checkout-container'
},
onSuccess: (data) => {
this.$emit('success', data);
}
});
},
beforeUnmount() {
this.cleanup?.();
}
};
</script>Angular
import { Component, Input, OnDestroy, OnInit } from '@angular/core';
import { init } from '@one-cp/web-checkout';
@Component({
selector: 'app-checkout',
template: '<div id="checkout-container" style="min-height: 600px;"></div>'
})
export class CheckoutComponent implements OnInit, OnDestroy {
@Input() transactionID!: string;
private cleanup?: () => void;
ngOnInit() {
this.cleanup = init({
transactionID: this.transactionID,
config: { mode: 'inline', containerID: 'checkout-container' },
onSuccess: (data) => {
console.log('Success:', data);
}
});
}
ngOnDestroy() {
this.cleanup?.();
}
}🧪 Testing
The SDK includes comprehensive testing support:
# Run tests
npm test
# Run tests with coverage
npm run test:coverage
# Run tests in watch mode
npm run test:watchTest coverage: 94.96% (32/32 tests passing)
🔧 Development
Local Development
# Clone the repository
git clone https://github.com/One-Cp/one-cp-web-checkout.git
# Install dependencies
npm install
# Start development server
npm run dev
# Run tests
npm test
# Build for production
npm run buildBuilding
# Build library
npm run build
# Build examples
npm run build:examples📝 Migration Guide
From v1.x to v2.x
cleanup()function is now returned frominit()- TypeScript definitions are now included
- New
redirectURLconfiguration option - Enhanced error handling and validation
🤝 Contributing
We welcome contributions! Please see our Contributing Guide for details.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
🆘 Support
🗺️ Roadmap
- [ ] React Native support
- [ ] Vue 3 composition API helpers
- [ ] Accessibility improvements (WCAG 2.1 AA compliance)
Made with ❤️ by the One-CP Team
