voko-sdk
Version:
Process payments with ease
82 lines (81 loc) • 2.67 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.VokoPaymentRequest = void 0;
const types_1 = require("../types");
const phone_validator_1 = require("../../utils/phone-validator");
class VokoPaymentRequest {
amount;
currency;
phoneNumber;
email;
fullName;
reference;
description;
callbackUrl;
metadata;
paymentMethod;
operator;
accountNumber;
otp;
timestamp;
constructor(data) {
this.amount = this.validateAmount(data.amount);
this.currency = data.currency || types_1.Currency.TZS;
this.phoneNumber = this.normalizePhoneNumber(data.phoneNumber);
this.email = data.email;
this.fullName = data.fullName;
this.reference = data.reference;
this.description = data.description;
this.callbackUrl = data.callbackUrl;
this.metadata = data.metadata || {};
this.paymentMethod = data.paymentMethod;
this.operator = data.operator;
this.accountNumber = data.accountNumber;
this.otp = data.otp;
this.timestamp = new Date().toISOString();
this.validate();
}
validateAmount(amount) {
if (!amount || amount <= 0) {
throw new Error('Amount must be greater than 0');
}
return Math.round(amount * 100) / 100;
}
normalizePhoneNumber(phone) {
return phone_validator_1.PhoneValidator.normalize(phone);
}
validate() {
if (this.phoneNumber && !phone_validator_1.PhoneValidator.isValid(this.phoneNumber)) {
throw new Error('Invalid phone number format');
}
if (this.email && !this.isValidEmail(this.email)) {
throw new Error('Invalid email format');
}
if (!this.reference || this.reference.trim().length === 0) {
throw new Error('Reference is required');
}
}
isValidEmail(email) {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
}
toJSON() {
return {
amount: this.amount,
currency: this.currency,
phoneNumber: this.phoneNumber,
email: this.email,
fullName: this.fullName,
reference: this.reference,
description: this.description,
callbackUrl: this.callbackUrl,
metadata: this.metadata,
paymentMethod: this.paymentMethod,
operator: this.operator,
accountNumber: this.accountNumber,
otp: this.otp,
timestamp: this.timestamp,
};
}
}
exports.VokoPaymentRequest = VokoPaymentRequest;