paywant-typescript-sdk
v1.0.4
Published
Paywant API TypeScript/JavaScript client library
Downloads
22
Maintainers
Readme
Paywant TypeScript SDK (Unofficial)
An unofficial TypeScript/JavaScript client library for the Paywant payment processing API, converted from the official PHP SDK.
Note: This is an unofficial community-maintained SDK. For official support, please refer to Paywant's official documentation.
Features
- Full TypeScript support with type definitions
- Modern async/await API using axios for HTTP requests
- Complete feature parity with the PHP SDK
- Browser and Node.js compatible
- Comprehensive examples and documentation
Installation
npm i paywant-typescript-sdkQuick Start
Basic Usage
import { PaywantSDK } from 'paywant-typescript-sdk';
// Initialize SDK
const sdk = new PaywantSDK(
'YOUR_API_KEY',
'YOUR_SECRET_KEY',
'https://secure.paywant.com'
);Creating a Payment
async function createPayment() {
// Create payment request
const request = sdk.createPaymentRequest();
// Create buyer
const buyer = sdk.createBuyer();
buyer.setUserAccountName('username');
buyer.setUserEmail('[email protected]');
buyer.setUserID('1');
// Create product
const product = sdk.createProduct();
product.setName('Order #123');
product.setAmount(10.54); // Amount in TRY
product.setExtraData(123); // Your order ID
product.setCommissionType(Product.TAKE_ALL);
// Set payment channels
const paymentChannels = sdk.createPaymentChannel();
paymentChannels.addPaymentChannel(PaymentChannel.ALL_CHANNELS);
product.setPaymentChannel(paymentChannels);
// Configure request
request.setBuyer(buyer);
request.setProductData(product);
request.setRedirectUrl('https://yoursite.com/success');
// Execute request
const success = await request.execute();
if (success) {
const response = request.getResponse(true);
console.log('Payment URL:', response.message);
return response.message; // Use this URL for payment iframe/redirect
} else {
console.error('Error:', request.getError());
}
}Creating a Store Token
async function createStore() {
const request = sdk.createStoreRequest();
const buyer = sdk.createBuyer();
buyer.setUserAccountName('username');
buyer.setUserEmail('[email protected]');
buyer.setUserID('1');
request.setBuyer(buyer);
const success = await request.execute();
if (success) {
const response = request.getResponse(true);
return response.message; // Payment URL
}
}Handling IPN (Instant Payment Notifications)
import { IPNHandler, IPNData } from '@paywant/typescript-sdk';
// Create IPN handler
const ipnHandler = new IPNHandler('YOUR_API_KEY', 'YOUR_SECRET_KEY');
// In your Express.js route
app.post('/paywant-ipn', (req, res) => {
const ipnData: IPNData = req.body;
// Verify IPN authenticity
const isValid = ipnHandler.verifyIPN(ipnData);
if (isValid) {
// Process the payment
console.log('Transaction ID:', ipnData.transactionID);
console.log('Order ID:', ipnData.extraData);
console.log('Status:', ipnData.status);
// Update your database, send emails, etc.
res.status(200).send('OK');
} else {
res.status(400).send('Invalid hash');
}
});API Reference
PaywantSDK
Main SDK class that provides factory methods for creating service instances.
class PaywantSDK {
constructor(apiKey: string, secretKey: string, serviceBaseUrl?: string)
createPaymentRequest(): PaymentCreate
createStoreRequest(): StoreCreate
createIPNHandler(): IPNHandler
createBuyer(): Buyer
createProduct(): Product
createPaymentChannel(): PaymentChannel
}Models
Buyer
class Buyer {
setUserID(userID: string): this
setUserAccountName(userAccountName: string): this
setUserEmail(userEmail: string): this
getUserID(): string
getUserAccountName(): string
getUserEmail(): string
}Product
class Product {
static readonly TAKE_ALL = 1
static readonly TAKE_PARTIAL = 2
static readonly REFLECT_TO_CUSTOMER = 3
setName(name: string): this
setAmount(amount: number): this // Amount in main currency unit
setExtraData(extraData: number): this
setPaymentChannel(paymentChannel: PaymentChannel): this
setCommissionType(commissionType: number): this
setCurrency(currency: string): this
}PaymentChannel
class PaymentChannel {
static readonly ALL_CHANNELS = 0
static readonly MOBILE_OPERATOR = 1
static readonly CREDIT_CARD = 2
static readonly LOCAL_TR_BANK = 3
static readonly MIKROCARD = 5
static readonly GLOBAL_PAYMENT = 10
addPaymentChannel(paymentChannelId: number): void
getPaymentChannels(): string
clearPaymentChannels(): void
}Services
PaymentCreate
class PaymentCreate extends Request {
setBuyer(buyer: Buyer): this
setProductData(productData: Product): this
setRedirectUrl(redirectUrl: string): this
setFailRedirectUrl(failRedirectUrl: string): this
setCallbackUrl(callbackUrl: string): this
setLanguage(language: string): this
setProApi(proApi: boolean): this
execute(): Promise<boolean>
}StoreCreate
class StoreCreate extends Request {
setBuyer(buyer: Buyer): this
setRedirectUrl(redirectUrl: string): this
setFailRedirectUrl(failRedirectUrl: string): this
setCallbackUrl(callbackUrl: string): this
setLanguage(language: string): this
execute(): Promise<boolean>
}IPNHandler
class IPNHandler {
constructor(apiKey: string, apiSecret: string)
verifyIPN(ipnData: IPNData): boolean
verifyIPNAsync(ipnData: IPNData): Promise<boolean>
processIPN(ipnData: IPNData): IPNProcessResult
}Environment Support
Node.js
The SDK works out of the box in Node.js environments:
import { PaywantSDK } from 'paywant-typescript-sdk';
// or
const { PaywantSDK } = require('paywant-typescript-sdk');Browser
For browser usage, you may need to handle CORS and use the async hash methods:
import { PaywantSDK, Helper } from 'paywant-typescript-sdk';
// Use async hash methods in browser environments
const hash = await Helper.createHashAsync(data, key);Configuration
Environment Variables
You can set these environment variables for IP detection in Node.js:
HTTP_CLIENT_IPHTTP_X_FORWARDED_FORHTTP_X_FORWARDEDHTTP_FORWARDED_FORHTTP_FORWARDEDREMOTE_ADDRREMOTE_PORT
Error Handling
All API methods return boolean success indicators. Use getResponse() and getError() to access results:
const success = await request.execute();
if (success) {
const response = request.getResponse(true); // Parse as JSON
console.log('Success:', response);
} else {
const error = request.getError(true); // Parse as JSON
console.error('Error:', error);
}Examples
See the examples/ directory for complete working examples:
examples/store.ts- Store token creationexamples/payment.ts- Payment processingexamples/ipn.ts- IPN handling
Building
# Install dependencies
npm install
# Build the library
npm run build
# Run tests
npm test
# Lint code
npm run lintBrowser Integration
After successful payment creation, integrate the payment page:
<div id="paywant-area">
<script src="//secure.paywant.com/public/js/paywant.js"></script>
<iframe
src="PAYMENT_URL_FROM_RESPONSE"
id="paywantIframe"
frameborder="0"
scrolling="no"
style="width: 100%;">
</iframe>
<script type="text/javascript">
setTimeout(function() {
iFrameResize({ log: false }, '#paywantIframe');
}, 1000);
</script>
</div>Migration from PHP SDK
This TypeScript SDK maintains API compatibility with the PHP SDK. Key differences:
- Async/await: All API calls return Promises
- Method naming: Uses camelCase instead of snake_case for methods
- Type safety: Full TypeScript type definitions included
- Modern HTTP: Uses axios instead of cURL
License
MIT License
Support
For technical support and documentation, visit Paywant Developer Portal
Contributing
Contributions are welcome! Please read the contributing guidelines and submit pull requests to the GitHub repository.
