import crypto from 'crypto'
export default class Freekassa {
public ID: string | number | undefined
public SECRET_1: string | undefined
public SECRET_2: string | undefined
protected PAYMENT_FORM_LINK: string = 'https://pay.freekassa.ru/'
protected IPs: string[] = ['168.119.157.136', '168.119.60.227', '138.201.88.124']
constructor(
FREEKASSA_ID?: string | number,
FREEKASSA_SECRET_1?: string,
FREEKASSA_SECRET_2?: string
) {
this.ID = FREEKASSA_ID || process.env.FREEKASSA_ID
this.SECRET_1 = FREEKASSA_SECRET_1 || process.env.FREEKASSA_SECRET
this.SECRET_2 = FREEKASSA_SECRET_2 || process.env.FREEKASSA_SECRET_2
if (!this.ID || !this.SECRET_1 || !this.SECRET_2) throw new Error('Missing credentials')
}
public sign_payment_form(amount: number, currency: string, transaction_id: number) {
const _amount = this.validate_amount(amount)
console.log(_amount)
return crypto
.createHash('md5')
.update(`${this.ID}:${_amount}:${this.SECRET_1}:${currency}:${transaction_id}`)
.digest('hex')
}
public validate_amount(amount) {
if (amount % 1 === 0) {
return Math.trunc(amount)
} else {
const mod = amount.split('.')[1]
return parseFloat(`${Math.trunc(amount)}.${mod[0]}${mod[1] || 0}`)
}
}
public validate_ip(ip) {
return this.IPs.includes(ip)
}
public payment_form(
amount: number,
currency: string = 'RUB',
transaction_id: number,
meta?: object
) {
const amountValidated = this.validate_amount(amount)
const data = {
m: this.ID,
oa: amountValidated,
currency,
o: transaction_id,
s: this.sign_payment_form(amountValidated, currency, transaction_id),
...meta,
}
const params = Object.keys(data)
.map((k) => `${encodeURIComponent(k)}=${encodeURIComponent(data[k])}`)
.join('&')
return {
signature: data.s,
url: `${this.PAYMENT_FORM_LINK}?${params}`,
}
}
}