paywant-typescript-sdk
Version:
Paywant API TypeScript/JavaScript client library
364 lines (269 loc) • 8.4 kB
Markdown
# 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
```bash
npm i paywant-typescript-sdk
```
## Quick Start
### Basic Usage
```typescript
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
```typescript
async function createPayment() {
// Create payment request
const request = sdk.createPaymentRequest();
// Create buyer
const buyer = sdk.createBuyer();
buyer.setUserAccountName('username');
buyer.setUserEmail('customer@email.com');
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
```typescript
async function createStore() {
const request = sdk.createStoreRequest();
const buyer = sdk.createBuyer();
buyer.setUserAccountName('username');
buyer.setUserEmail('customer@email.com');
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)
```typescript
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.
```typescript
class PaywantSDK {
constructor(apiKey: string, secretKey: string, serviceBaseUrl?: string)
createPaymentRequest(): PaymentCreate
createStoreRequest(): StoreCreate
createIPNHandler(): IPNHandler
createBuyer(): Buyer
createProduct(): Product
createPaymentChannel(): PaymentChannel
}
```
### Models
#### Buyer
```typescript
class Buyer {
setUserID(userID: string): this
setUserAccountName(userAccountName: string): this
setUserEmail(userEmail: string): this
getUserID(): string
getUserAccountName(): string
getUserEmail(): string
}
```
#### Product
```typescript
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
```typescript
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
```typescript
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
```typescript
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
```typescript
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:
```typescript
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:
```typescript
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_IP`
- `HTTP_X_FORWARDED_FOR`
- `HTTP_X_FORWARDED`
- `HTTP_FORWARDED_FOR`
- `HTTP_FORWARDED`
- `REMOTE_ADDR`
- `REMOTE_PORT`
## Error Handling
All API methods return boolean success indicators. Use `getResponse()` and `getError()` to access results:
```typescript
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 creation
- `examples/payment.ts` - Payment processing
- `examples/ipn.ts` - IPN handling
## Building
```bash
# Install dependencies
npm install
# Build the library
npm run build
# Run tests
npm test
# Lint code
npm run lint
```
## Browser Integration
After successful payment creation, integrate the payment page:
```html
<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:
1. **Async/await**: All API calls return Promises
2. **Method naming**: Uses camelCase instead of snake_case for methods
3. **Type safety**: Full TypeScript type definitions included
4. **Modern HTTP**: Uses axios instead of cURL
## License
MIT License
## Support
For technical support and documentation, visit [Paywant Developer Portal](https://www.paywant.com)
## Contributing
Contributions are welcome! Please read the contributing guidelines and submit pull requests to the GitHub repository.