UNPKG

@buckaroo/buckaroo_sdk

Version:
1,593 lines (1,544 loc) 120 kB
import * as IpAddress from 'ip-address'; import md5 from 'crypto-js/md5'; import hmacSHA256 from 'crypto-js/hmac-sha256'; import Base64 from 'crypto-js/enc-base64'; import crypto from 'crypto'; import axios from 'axios'; import os from 'os'; function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread2(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var s = Object.getOwnPropertySymbols(e); for (r = 0; r < s.length; r++) o = s[r], t.includes(o) || {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; } function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (e.includes(n)) continue; t[n] = r[n]; } return t; } function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } class Model { constructor(...args) { this.initialize(...args); } initialize(data) { if (data instanceof Object && !Array.isArray(data)) { if (data.constructor === this.constructor) { this.setDataProperties(data); } else this.setOwnProperties(data); } return this; } set(name, value, hidden = false) { this.defineProperty(name, value, hidden); return this; } get(prop) { var _this$has; return (_this$has = this.has(prop)) === null || _this$has === void 0 || (_this$has = _this$has.get) === null || _this$has === void 0 ? void 0 : _this$has.call(this); } has(prop, model = this) { return getObjectProperty(model, prop, Model.prototype); } getData(callBack) { return JSON.parse(JSON.stringify(this), callBack); } setOwnProperties(data = {}, properties = this.getAllPropertyDescriptors()) { for (const key in properties) { if (properties[key].set) { var _data$key, _properties$key$get; let value = (_data$key = data[key]) !== null && _data$key !== void 0 ? _data$key : (_properties$key$get = properties[key].get) === null || _properties$key$get === void 0 ? void 0 : _properties$key$get.call(this); if (value !== undefined) this[key] = value; } } return this; } setDataProperties(data = {}) { for (const dataKey in data) { if (data.hasOwnProperty(dataKey) && data[dataKey] !== undefined) this.set(dataKey, data[dataKey]); } return this; } privateName(name) { return Str.ucfirst(name); } publicName(name) { return Str.lcfirst(name); } getAllPropertyDescriptors(descriptors = {}, root = Model.prototype) { // Loop through the prototype chain let currentObj = Object.getPrototypeOf(this); while (currentObj !== root) { const currentDescriptors = Object.getOwnPropertyDescriptors(currentObj); // Merge the descriptors into the result descriptors = _objectSpread2(_objectSpread2({}, currentDescriptors), descriptors); // Move up the prototype chain currentObj = Object.getPrototypeOf(currentObj); } return descriptors; } defineProperty(name, value, hidden = false) { var _this$has$set, _this$has2; let privateName = this.privateName(name); Object.defineProperty(this, privateName, { value, writable: true, enumerable: !hidden, configurable: true }); let publicName = this.publicName(name); Object.defineProperty(this, publicName, { get: () => value, set: (_this$has$set = (_this$has2 = this.has(publicName)) === null || _this$has2 === void 0 ? void 0 : _this$has2.set) !== null && _this$has$set !== void 0 ? _this$has$set : value => this.set(publicName, value, hidden), enumerable: false, configurable: true }); } } class JsonModel extends Model { constructor(data) { super(data); } initialize(data) { return this.setDataProperties(data); } set(key, value) { Object.defineProperty(this, Str.lcfirst(key), { get: this.get.bind(this, value), enumerable: true }); return this; } get(value) { if (Array.isArray(value)) { return value.map(v => new JsonModel(v)); } if (value instanceof Object) { return new JsonModel(value); } if (value === null) { return undefined; } return value; } } function getObjectProperty(object, property, root = null) { if (object !== root) { var _Object$getOwnPropert; return (_Object$getOwnPropert = Object.getOwnPropertyDescriptor(object, property)) !== null && _Object$getOwnPropert !== void 0 ? _Object$getOwnPropert : getObjectProperty(Object.getPrototypeOf(object), property, root); } } let Address$6 = class Address extends Model { set street(street) { this.set('street', street); } set houseNumber(houseNumber) { this.set('houseNumber', houseNumber); } set houseNumberAdditional(houseNumberAdditional) { this.set('houseNumberAdditional', houseNumberAdditional); } set zipcode(zipcode) { this.set('zipcode', zipcode); } set city(city) { this.set('city', city); } set state(state) { this.set('state', state); } set country(country) { this.set('country', country); } }; let Article$3 = class Article extends Model { set identifier(identifier) { this.set('identifier', identifier); } set type(type) { this.set('type', type); } set brand(brand) { this.set('brand', brand); } set manufacturer(manufacturer) { this.set('manufacturer', manufacturer); } set unitCode(unitCode) { this.set('unitCode', unitCode); } set price(price) { this.set('price', price); } set quantity(quantity) { this.set('quantity', quantity); } set vatPercentage(vatPercentage) { this.set('vatPercentage', vatPercentage); } set vatCategory(vatCategory) { this.set('vatCategory', vatCategory); } set description(description) { this.set('description', description); } }; let BankAccount$2 = class BankAccount extends Model { set accountName(accountName) { this.set('accountName', accountName); } set bic(bic) { this.set('bic', bic); } set iban(iban) { this.set('iban', iban); } }; let Debtor$2 = class Debtor extends Model { set code(value) { this.set('code', value); } }; class Email extends Model { constructor(data) { super(data); } get email() { return ''; } set email(email) { this.set('email', email); } } let Phone$4 = class Phone extends Model { set landline(landline) { this.set('landline', landline); } set mobile(mobile) { this.set('mobile', mobile); } set fax(fax) { this.set('fax', fax); } }; var Endpoints; (function (Endpoints) { Endpoints["LIVE"] = "https://checkout.buckaroo.nl"; Endpoints["TEST"] = "https://testcheckout.buckaroo.nl"; })(Endpoints || (Endpoints = {})); var RequestTypes; (function (RequestTypes) { RequestTypes["Data"] = "/json/DataRequest"; RequestTypes["Transaction"] = "/json/Transaction"; RequestTypes["BatchData"] = "/json/batch/DataRequests"; RequestTypes["BatchTransaction"] = "/json/batch/Transactions"; })(RequestTypes || (RequestTypes = {})); var Endpoints$1 = Endpoints; var CreditManagementInstallmentInterval; (function (CreditManagementInstallmentInterval) { CreditManagementInstallmentInterval["DAY"] = "Day"; CreditManagementInstallmentInterval["TWODAYS"] = "TwoDays"; CreditManagementInstallmentInterval["WEEK"] = "Week"; CreditManagementInstallmentInterval["TWOWEEKS"] = "TwoWeeks"; CreditManagementInstallmentInterval["HALFMONTH"] = "HalfMonth"; CreditManagementInstallmentInterval["MONTH"] = "Month"; CreditManagementInstallmentInterval["TWOMONTHS"] = "TwoMonths"; CreditManagementInstallmentInterval["QUARTERYEAR"] = "QuarterYear"; CreditManagementInstallmentInterval["HALFYEAR"] = "HalfYear"; CreditManagementInstallmentInterval["YEAR"] = "Year"; })(CreditManagementInstallmentInterval || (CreditManagementInstallmentInterval = {})); var CreditManagementInstallmentInterval$1 = CreditManagementInstallmentInterval; var Gender; (function (Gender) { Gender[Gender["UNKNOWN"] = 0] = "UNKNOWN"; Gender[Gender["MALE"] = 1] = "MALE"; Gender[Gender["FEMALE"] = 2] = "FEMALE"; Gender[Gender["NOT_APPLICABLE"] = 9] = "NOT_APPLICABLE"; })(Gender || (Gender = {})); var Gender$1 = Gender; var HttpMethods; (function (HttpMethods) { HttpMethods["GET"] = "GET"; HttpMethods["POST"] = "POST"; })(HttpMethods || (HttpMethods = {})); var HttpMethods$1 = HttpMethods; class IPProtocolVersion { static getVersion(ipAddress = '0.0.0.0') { if (IpAddress.Address4.isValid(ipAddress)) { return IPProtocolVersion.IPV4; } if (IpAddress.Address6.isValid(ipAddress)) { return IPProtocolVersion.IPV6; } throw new Error(`Invalid IP address: ${ipAddress}`); } } _defineProperty(IPProtocolVersion, "IPV4", 0); _defineProperty(IPProtocolVersion, "IPV6", 1); class ClientIP { constructor(ipAddress = getIPAddress()) { _defineProperty(this, "type", void 0); _defineProperty(this, "address", void 0); this.type = IPProtocolVersion.getVersion(ipAddress); this.address = ipAddress; } } var ResponseStatus; (function (ResponseStatus) { ResponseStatus["STATUSCODE_SUCCESS"] = "190"; ResponseStatus["STATUSCODE_FAILED"] = "490"; ResponseStatus["STATUSCODE_VALIDATION_FAILURE"] = "491"; ResponseStatus["STATUSCODE_TECHNICAL_ERROR"] = "492"; ResponseStatus["STATUSCODE_REJECTED"] = "690"; ResponseStatus["STATUSCODE_WAITING_ON_USER_INPUT"] = "790"; ResponseStatus["STATUSCODE_PENDING_PROCESSING"] = "791"; ResponseStatus["STATUSCODE_WAITING_ON_CONSUMER"] = "792"; ResponseStatus["STATUSCODE_PAYMENT_ON_HOLD"] = "793"; ResponseStatus["STATUSCODE_CANCELLED_BY_USER"] = "890"; ResponseStatus["STATUSCODE_CANCELLED_BY_MERCHANT"] = "891"; ResponseStatus["AUTHORIZE_TYPE_CANCEL"] = "I014"; ResponseStatus["AUTHORIZE_TYPE_ACCEPT"] = "I013"; ResponseStatus["AUTHORIZE_TYPE_GROUP_TRANSACTION"] = "I150"; })(ResponseStatus || (ResponseStatus = {})); var ResponseStatus$1 = ResponseStatus; var RecipientCategory; (function (RecipientCategory) { RecipientCategory["PERSON"] = "PERSON"; RecipientCategory["COMPANY"] = "COMPANY"; })(RecipientCategory || (RecipientCategory = {})); var RecipientCategory$1 = RecipientCategory; let Customer$8 = class Customer extends Model { set address(address) { this.set('address', new Address$6(address)); } set email(email) { this.set('email', email); } set phone(phone) { this.set('phone', new Phone$4(phone)); } set recipient(recipient) { this.set('recipient', recipient.category === RecipientCategory$1.COMPANY ? new Company$1(recipient) : new Person(recipient)); } }; let Recipient$2 = class Recipient extends Model { set birthDate(value) { this.set('birthDate', value); } set careOf(value) { this.set('careOf', value); } set category(value) { this.set('category', value); } set culture(value) { this.set('culture', value); } set firstName(value) { this.set('firstName', value); } set gender(value) { this.set('gender', value); } set initials(value) { this.set('initials', value); } set lastName(value) { this.set('lastName', value); } set lastNamePrefix(value) { this.set('lastNamePrefix', value); } set placeOfBirth(value) { this.set('placeOfBirth', value); } set title(value) { this.set('title', value); } }; class Person extends Recipient$2 { constructor(data) { super(data); } set name(value) { this.set('name', value); } set category(value) { this.set('category', value); } } let Company$1 = class Company extends Recipient$2 { constructor(data) { super(data); } set category(value) { this.set('category', value); } set chamberOfCommerce(value) { this.set('chamberOfCommerce', value); } set companyName(value) { this.set('companyName', value); } set culture(value) { this.set('culture', value); } set vatApplicable(value) { this.set('vatApplicable', value); } set vatNumber(value) { this.set('vatNumber', value); } }; class Headers { constructor() { _defineProperty(this, "_headers", this.getDefaultHeaders()); } get headers() { return this._headers; } setSoftwareHeader(value = {}) { this._headers.Software = JSON.stringify({ PlatformName: value.platformName || 'Node SDK', PlatformVersion: value.platformVersion || '1.4.0', ModuleSupplier: value.moduleSupplier || 'Buckaroo', ModuleName: value.moduleName || 'BuckarooPayments', ModuleVersion: value.moduleVersion || '1.0' }); return this; } setHeaders(headers) { Object.keys(headers).forEach(key => { this._headers[key] = headers[key]; }); return this; } removeHeaders(headers) { Object.keys(headers).forEach(key => { delete this._headers[key]; }); return this; } getDefaultHeaders() { return { 'Content-type': 'application/json; charset=utf-8', Accept: 'application/json', Culture: 'nl-NL', Authorization: '', Channel: 'Web', Software: JSON.stringify({ PlatformName: 'Node SDK', PlatformVersion: '1.4.0', ModuleSupplier: 'Buckaroo', ModuleName: 'BuckarooPayments', ModuleVersion: '1.0' }) }; } } class TransactionData extends Model { constructor(data) { super(data); } set clientUserAgent(value) { this.set('clientUserAgent', value); } set order(order) { this.set('order', order); } set invoice(invoice) { this.set('invoice', invoice); } set description(description) { this.set('description', description); } set amountCredit(amountCredit) { this.set('amountCredit', amountCredit); } set amountDebit(amountDebit) { this.set('amountDebit', amountDebit); } set currency(currency) { this.set('currency', currency); } set clientIP(ipAddress) { this.set('clientIP', new ClientIP(ipAddress)); } set additionalParameters(value) { this.set('additionalParameters', { AdditionalParameter: DataFormatter.parametersMap(value) }); } set customParameters(value) { this.set('customParameters', { List: DataFormatter.parametersMap(value) }); } set pushURL(pushURL) { this.set('pushURL', pushURL); } set continueOnIncomplete(value) { this.set('continueOnIncomplete', value ? 1 : 0); } set culture(value) { this.set('culture', value); } set originalTransactionKey(value) { this.set('originalTransactionKey', value); } set originalTransactionReference(value) { this.set('originalTransactionReference', value); } set pushURLFailure(value) { this.set('pushURLFailure', value); } set returnURL(value) { this.set('returnURL', value); } set returnURLCancel(value) { this.set('returnURLCancel', value); } set returnURLError(value) { this.set('returnURLError', value); } set returnURLReject(value) { this.set('returnURLReject', value); } set servicesExcludedForClient(services) { this.set('servicesExcludedForClient', Array.isArray(services) ? services === null || services === void 0 ? void 0 : services.join(',') : services); } get servicesSelectableByClient() { return ''; } set servicesSelectableByClient(services) { this.set('servicesSelectableByClient', Array.isArray(services) ? services === null || services === void 0 ? void 0 : services.join(',') : services); } set startRecurrent(value) { this.set('startRecurrent', value); } getServiceList() { return this.get('services'); } setServiceList(services) { return this.set('services', services); } } class DataRequestData extends TransactionData { set additionalParameters(parameters) { this.set('additionalParameters', { List: DataFormatter.parametersMap(parameters) }); } set services(data) { this.set('services', data); } } class SpecificationRequestData extends Model { constructor(data) { super({ services: data }); } set services(data) { this.set('services', data.map(service => { return { Name: service.name, Version: service.version }; })); } } class Hmac { constructor() { _defineProperty(this, "_data", void 0); _defineProperty(this, "_url", void 0); _defineProperty(this, "_nonce", void 0); _defineProperty(this, "_time", void 0); _defineProperty(this, "_method", void 0); } get data() { return this._data ? JSON.stringify(this._data) : ''; } set data(data) { try { let jsonData = JSON.parse(data); if (Object.keys(jsonData).length > 0) { this._data = jsonData; } } catch (e) {} } get url() { return this._url ? encodeURIComponent(this._url.href.replace(this._url.protocol, '').replace(/^[^:/.]*[:/]+/i, '').replace(/(^\w+:|^)\/\//, '')).toLowerCase() : undefined; } set url(url) { if (url) this._url = new URL(url); } get nonce() { return this._nonce || 'nonce_' + Math.floor(Math.random() * 9999999 + 1); } set nonce(nonce) { this._nonce = nonce; } get time() { return this._time || String(Math.round(Date.now() / 1000)); } set time(time) { this._time = time; } get method() { return this._method || 'POST'; } set method(method) { this._method = method; } get base64Data() { if (this._data) { return Base64.stringify(md5(this.data)); } return ''; } generate(credentials, nonce, time) { this._nonce = nonce || this.nonce; this._time = time || this.time; let hashString = this.getHashString(credentials.websiteKey); let hashData = this.hashData(hashString, credentials.secretKey); return `hmac ${credentials.websiteKey}:${hashData}:${this._nonce}:${this._time}`; } validate(credentials, authHeader, url, data, method) { let header = authHeader.split(':'); let providedHash = header[1]; this.nonce = header[2]; this.time = header[3]; this.method = method; this.url = url; this.data = data; let hash = this.hashData(this.getHashString(credentials.websiteKey), credentials.secretKey); return crypto.timingSafeEqual(Buffer.from(hash), Buffer.from(providedHash)); } getHashString(websiteKey) { return websiteKey + this.method + this.url + this.time + this.nonce + this.base64Data; } hashData(hashString, secretKey) { return hmacSHA256(hashString, secretKey).toString(Base64); } } class HttpsClient { constructor(agent, timeout) { _defineProperty(this, "_options", {}); _defineProperty(this, "_axiosInstance", void 0); this._options.timeout = timeout !== null && timeout !== void 0 ? timeout : 10000; this._options.maxRedirects = 10; this._options.withCredentials = true; if (agent) { this._options.httpsAgent = agent; } this._axiosInstance = axios.create(this._options); } sendRequest(url, data, options, responseClass) { var _this = this; return _asyncToGenerator(function* () { try { const config = _objectSpread2(_objectSpread2({ url: url.toString() }, _this._options), options); if (options.method !== HttpMethods$1.GET) { config.data = data; } const response = yield _this._axiosInstance.request(config); return new responseClass(response, response.data); } catch (error) { if (axios.isAxiosError(error)) { var _error$response$data, _error$response; throw (_error$response$data = (_error$response = error.response) === null || _error$response === void 0 ? void 0 : _error$response.data) !== null && _error$response$data !== void 0 ? _error$response$data : error; } throw error; } })(); } } class Request extends Headers { constructor(path, method, data, responseHandler) { super(); _defineProperty(this, "_path", void 0); _defineProperty(this, "_data", void 0); _defineProperty(this, "_httpMethod", void 0); _defineProperty(this, "_responseHandler", void 0); this._path = path; this._data = data; this._httpMethod = method || HttpMethods$1.GET; this._responseHandler = responseHandler; } get data() { return this._data; } get httpMethod() { return this._httpMethod; } get url() { return new URL(Endpoints$1[Buckaroo.Client.config.mode] + (this._path || '')); } get responseHandler() { return this._responseHandler || HttpClientResponse; } static Transaction(payload) { return new Request(RequestTypes.Transaction, HttpMethods$1.POST, new TransactionData(payload), TransactionResponse); } static DataRequest(payload) { return new Request(RequestTypes.Data, HttpMethods$1.POST, new DataRequestData(payload), TransactionResponse); } static Specification(type, data) { if (Array.isArray(data)) { return new Request(type + `/Specifications`, HttpMethods$1.POST, new SpecificationRequestData(data), SpecificationRequestResponse); } return new Request(type + `/Specification/${data === null || data === void 0 ? void 0 : data.name}?serviceVersion=${data === null || data === void 0 ? void 0 : data.version}`, HttpMethods$1.GET, undefined, SpecificationRequestResponse); } static BatchTransaction(payload = []) { return new Request(RequestTypes.BatchTransaction, HttpMethods$1.POST, payload.map(data => new TransactionData(data)), BatchRequestResponse); } static BatchDataRequest(data = []) { return new Request(RequestTypes.BatchData, HttpMethods$1.POST, data, BatchRequestResponse); } request(options = {}) { var _ref; let data = (_ref = this._httpMethod === HttpMethods$1.GET ? {} : this.data) !== null && _ref !== void 0 ? _ref : {}; this.setAuthorizationHeader(data); return Buckaroo.Client.httpClient.sendRequest(this.url, data, _objectSpread2({ method: this._httpMethod, headers: this.headers }, options), this.responseHandler); } setAuthorizationHeader(data, credentials = Buckaroo.Client.credentials) { let hmac = new Hmac(); hmac.data = JSON.stringify(data); hmac.method = this.httpMethod; hmac.url = this.url.toString(); this.headers.Authorization = hmac.generate(credentials); return this; } } class Credentials { constructor(secretKey, websiteKey) { _defineProperty(this, "secretKey", void 0); _defineProperty(this, "websiteKey", void 0); if (!secretKey || !websiteKey) throw new Error('Missing required credentials.'); this.secretKey = secretKey; this.websiteKey = websiteKey; } confirm() { return Request.Specification(RequestTypes.Transaction, { name: 'ideal', version: 2 }).request().then(response => { return response.httpResponse.status === 200; }).catch(() => { return false; }); } } const _excluded = ["brq_signature", "BRQ_SIGNATURE"]; class ReplyHandler { constructor(credentials, data, auth_header, uri, httpMethod) { _defineProperty(this, "_data", void 0); _defineProperty(this, "uri", void 0); _defineProperty(this, "auth_header", void 0); _defineProperty(this, "credentials", void 0); _defineProperty(this, "_isValid", false); _defineProperty(this, "strategy", 'JSON'); _defineProperty(this, "method", void 0); this._data = this.formatStringData(data); this.credentials = credentials; this.uri = uri; this.auth_header = auth_header; this.method = httpMethod; } isValid() { return this._isValid; } validate() { if (this.strategy === 'HTTP') { let _this$_data = this._data, { brq_signature, BRQ_SIGNATURE } = _this$_data, data = _objectWithoutProperties(_this$_data, _excluded); this._isValid = this.validateHttp(data, brq_signature || BRQ_SIGNATURE); return this; } if (this.strategy === 'JSON' && this.auth_header && this.uri) { this._isValid = this.validateJson(this.auth_header, this.uri, JSON.stringify(this._data)); return this; } throw new Error('Invalid response data'); } formatStringData(value) { try { let data = JSON.parse(value); this.strategy = 'JSON'; return data; } catch (e) { let objData = {}; new URLSearchParams(value).forEach((value, name) => { objData[name] = value; }); this.strategy = 'HTTP'; return objData; } } validateJson(auth_header, url, data) { return new Hmac().validate(this.credentials, auth_header, url, data, this.method || HttpMethods$1.POST); } validateHttp(data, signature) { const stringData = Object.keys(data).map(key => `${key}=${data[key]}`).join('') + this.credentials.secretKey; const hash = crypto.createHash('sha1').update(stringData).digest('hex'); return crypto.timingSafeEqual(Buffer.from(hash), Buffer.from(signature)); } } class HttpClientResponse { constructor(httpResponse) { _defineProperty(this, "_httpResponse", void 0); _defineProperty(this, "_data", void 0); _defineProperty(this, "_rawData", void 0); this._httpResponse = httpResponse; this._rawData = httpResponse.data; this._data = new JsonModel(httpResponse.data); } get httpResponse() { return this._httpResponse; } get rawData() { return this._rawData; } get data() { return this._data; } validateResponse(credentials) { var _this$_rawData; return new ReplyHandler(credentials, JSON.parse((_this$_rawData = this._rawData) !== null && _this$_rawData !== void 0 ? _this$_rawData : {}), this.httpResponse.headers['authorization'], this.httpResponse.request.url, this.httpResponse.request.method).validate().isValid(); } } class BatchRequestResponse extends HttpClientResponse { get data() { return this._data; } } class SpecificationRequestResponse extends HttpClientResponse { get data() { return this._data; } getActionRequestParameters(actionName) { var _this$data$actions; let actions = (_this$data$actions = this.data.actions) === null || _this$data$actions === void 0 || (_this$data$actions = _this$data$actions.find(action => { if (Str.ciEquals(action.name, actionName)) { return action; } })) === null || _this$data$actions === void 0 ? void 0 : _this$data$actions.requestParameters; if (actions) { actions.sort((a, b) => a.name.localeCompare(b.name)); } return actions; } } class TransactionResponse extends HttpClientResponse { get data() { return this._data; } getStatusCode() { return this.data.status.code.code.toString(); } getSubStatusCode() { return this.data.status.subCode.code.toString(); } isSuccess() { return this.getStatusCode() === ResponseStatus$1.STATUSCODE_SUCCESS; } isFailed() { return this.getStatusCode() === ResponseStatus$1.STATUSCODE_FAILED; } isCanceled() { return this.getStatusCode() === ResponseStatus$1.STATUSCODE_CANCELLED_BY_USER || this.getStatusCode() === ResponseStatus$1.STATUSCODE_CANCELLED_BY_MERCHANT; } isAwaitingConsumer() { return this.getStatusCode() === ResponseStatus$1.STATUSCODE_WAITING_ON_CONSUMER; } isPendingProcessing() { return this.getStatusCode() === ResponseStatus$1.STATUSCODE_PENDING_PROCESSING; } isWaitingOnUserInput() { return this.getStatusCode() === ResponseStatus$1.STATUSCODE_WAITING_ON_USER_INPUT; } isRejected() { return this.getStatusCode() === ResponseStatus$1.STATUSCODE_REJECTED; } isValidationFailure() { return this.getStatusCode() === ResponseStatus$1.STATUSCODE_VALIDATION_FAILURE; } hasRedirect() { var _this$data$requiredAc, _this$data$requiredAc2; return ((_this$data$requiredAc = this.data.requiredAction) === null || _this$data$requiredAc === void 0 ? void 0 : _this$data$requiredAc.redirectURL.length) > 0 && ((_this$data$requiredAc2 = this.data.requiredAction) === null || _this$data$requiredAc2 === void 0 ? void 0 : _this$data$requiredAc2.name) === 'Redirect'; } getRedirectUrl() { var _this$data$requiredAc3; if (this.hasRedirect()) return (_this$data$requiredAc3 = this.data.requiredAction) === null || _this$data$requiredAc3 === void 0 ? void 0 : _this$data$requiredAc3.redirectURL; return ''; } getServices() { return this.data.services; } getMethod() { var _this$data$services; return (_this$data$services = this.data.services) === null || _this$data$services === void 0 ? void 0 : _this$data$services[0].name; } getServiceAction() { var _this$data$services2; return (_this$data$services2 = this.data.services) === null || _this$data$services2 === void 0 ? void 0 : _this$data$services2[0].action; } getCustomParameters() { var _this$data$customPara, _this$data$customPara2; return DataFormatter.parametersReverseMap((_this$data$customPara = (_this$data$customPara2 = this.data.customParameters) === null || _this$data$customPara2 === void 0 ? void 0 : _this$data$customPara2.list) !== null && _this$data$customPara !== void 0 ? _this$data$customPara : []); } getAdditionalParameters() { var _ref, _this$data$additional, _this$data$additional2, _this$data$additional3; return DataFormatter.parametersReverseMap((_ref = (_this$data$additional = (_this$data$additional2 = this.data.additionalParameters) === null || _this$data$additional2 === void 0 ? void 0 : _this$data$additional2.additionalParameter) !== null && _this$data$additional !== void 0 ? _this$data$additional : (_this$data$additional3 = this.data.additionalParameters) === null || _this$data$additional3 === void 0 ? void 0 : _this$data$additional3['list']) !== null && _ref !== void 0 ? _ref : []); } getTransactionKey() { return this.data.key; } getPaymentKey() { return this.data.paymentKey; } getAmountDebit() { return this.data.amountDebit; } getAmountCredit() { return this.data.amountCredit; } hasError() { var _this$data$requestErr, _this$data$requestErr2, _this$data$requestErr3, _this$data$requestErr4, _this$data$requestErr5, _this$data$requestErr6, _this$data$requestErr7, _this$data$requestErr8, _this$data$requestErr9, _this$data$requestErr10; return this.data.requestErrors && Object.keys(this.data.requestErrors).length > 0 && (((_this$data$requestErr = (_this$data$requestErr2 = this.data.requestErrors.channelErrors) === null || _this$data$requestErr2 === void 0 ? void 0 : _this$data$requestErr2.length) !== null && _this$data$requestErr !== void 0 ? _this$data$requestErr : 0) > 0 || ((_this$data$requestErr3 = (_this$data$requestErr4 = this.data.requestErrors.serviceErrors) === null || _this$data$requestErr4 === void 0 ? void 0 : _this$data$requestErr4.length) !== null && _this$data$requestErr3 !== void 0 ? _this$data$requestErr3 : 0) > 0 || ((_this$data$requestErr5 = (_this$data$requestErr6 = this.data.requestErrors.actionErrors) === null || _this$data$requestErr6 === void 0 ? void 0 : _this$data$requestErr6.length) !== null && _this$data$requestErr5 !== void 0 ? _this$data$requestErr5 : 0) > 0 || ((_this$data$requestErr7 = (_this$data$requestErr8 = this.data.requestErrors.parameterErrors) === null || _this$data$requestErr8 === void 0 ? void 0 : _this$data$requestErr8.length) !== null && _this$data$requestErr7 !== void 0 ? _this$data$requestErr7 : 0) > 0 || ((_this$data$requestErr9 = (_this$data$requestErr10 = this.data.requestErrors.customParameterErrors) === null || _this$data$requestErr10 === void 0 ? void 0 : _this$data$requestErr10.length) !== null && _this$data$requestErr9 !== void 0 ? _this$data$requestErr9 : 0) > 0); } getErrorMessage() { return this.data.status.code.description; } } class Parameter extends Model { set name(value) { this.set('name', Str.ucfirst(value)); } set value(value) { this.set('value', value); } set groupType(value) { this.set('groupType', value); } set groupID(value) { this.set('groupID', value); } } class Service extends Model { constructor(data) { super(data); } set action(value) { this.set('action', value); } set name(value) { this.set('name', value); } set version(value) { this.set('version', value); } set parameters(value) { this.set('parameters', value.map(parameter => new Parameter(parameter))); } } class ServiceList extends Model { constructor(...list) { super({ list: list }); } get list() { return this.get('serviceList'); } set list(services) { this.set('serviceList', services.map(service => new Service(service))); } addService(service) { if (this.getService(service.name)) { this.list[this.list.findIndex(s => s.name === service.name)] = new Service(service); } else this.list.push(new Service(service)); } getService(name) { return this.list.find(service => service.name.toLowerCase() === name.toLowerCase()); } } class ServiceParameter extends Model { toParameterList() { return DataFormatter.serviceParametersMap(this.getData(), this.getGroups(), this.getCountable()); } getGroups(groups = {}) { return groups; } getCountable(countable = []) { return countable; } getAllPropertyDescriptors(descriptors = {}, root = ServiceParameter.prototype) { return super.getAllPropertyDescriptors(descriptors, root); } } let Pay$m = class Pay extends ServiceParameter { set issuer(value) { this.set('issuer', value); } set shippingCosts(value) { this.set('shippingCosts', value); } }; class PaymentMethod { constructor(serviceCode) { _defineProperty(this, "_serviceCode", void 0); _defineProperty(this, "_serviceVersion", 0); _defineProperty(this, "_payloadClass", TransactionData); _defineProperty(this, "_payload", void 0); _defineProperty(this, "_requiredFields", []); this._payload = this.createDefaultPayload(); this.setServiceCode(serviceCode !== null && serviceCode !== void 0 ? serviceCode : this._serviceCode); } set payloadClass(value) { this._payloadClass = value; this._payload = this.createDefaultPayload(); } createDefaultPayload() { var _this$_payload; return new this._payloadClass((_this$_payload = this._payload) !== null && _this$_payload !== void 0 ? _this$_payload : Buckaroo.Client.config); } get serviceVersion() { return this._serviceVersion; } set serviceVersion(value) { this._serviceVersion = value; } get serviceCode() { var _this$_serviceCode; return (_this$_serviceCode = this._serviceCode) !== null && _this$_serviceCode !== void 0 ? _this$_serviceCode : 'noservice'; } setServiceCode(value) { this._serviceCode = value; return this; } setPayload(payload) { this.setRequiredFields(); this._payload.initialize(payload); } setServiceVersion(value) { this._serviceVersion = value; return this; } getPayload() { return this._payload.getData(); } getServiceList() { return this._payload.getServiceList(); } combine(data) { if (typeof data === 'string') { const method = Buckaroo.Client.method(data); method.setPayload(this._payload); return method; } this.setPayload(data instanceof PaymentMethod ? data.getPayload() : data); return this; } specification(type = RequestTypes.Data, serviceVersion = this.serviceVersion) { return Request.Specification(type, { name: this.serviceCode, version: serviceVersion }); } setRequiredFields(requiredFields = this._requiredFields) { for (const fieldKey of requiredFields) { var _this$_payload$fieldK; let field = (_this$_payload$fieldK = this._payload[fieldKey]) !== null && _this$_payload$fieldK !== void 0 ? _this$_payload$fieldK : Buckaroo.Client.config[fieldKey]; if (field === undefined) { throw new Error(`Missing required config parameter ${String(fieldKey)}`); } this._payload[fieldKey] = field; } return this; } setServiceList(action, serviceParameters, serviceCode = this.serviceCode, serviceVersion = this.serviceVersion) { const service = { name: serviceCode, action: action, version: serviceVersion, parameters: serviceParameters instanceof ServiceParameter ? serviceParameters.toParameterList() : serviceParameters }; if (this.getServiceList() instanceof ServiceList) { this.getServiceList().addService(service); } else { this._payload.setServiceList(new ServiceList(service)); } return this; } transactionRequest(payload) { this.setPayload(payload); return Request.Transaction(this._payload); } dataRequest(payload) { this.payloadClass = DataRequestData; this.setPayload(payload); return Request.DataRequest(this._payload); } } class PayablePaymentMethod extends PaymentMethod { constructor(...args) { super(...args); _defineProperty(this, "_requiredFields", ['currency']); } pay(payload, serviceParameters) { this.setPayPayload(payload); this.setServiceList('Pay', serviceParameters); return this.transactionRequest(); } payRemainder(payload, serviceParameters) { this.setPayPayload(payload); this.setServiceList('PayRemainder', serviceParameters); return this.transactionRequest(); } refund(payload, serviceParameters) { this.setPayload(payload); this.setServiceList('Refund', serviceParameters); return this.transactionRequest(); } setPayPayload(payload) { var _payload$invoice, _payload$order; payload.invoice = (_payload$invoice = payload.invoice) !== null && _payload$invoice !== void 0 ? _payload$invoice : uniqid(); payload.order = (_payload$order = payload.order) !== null && _payload$order !== void 0 ? _payload$order : uniqid(); super.setPayload(payload); } } class ActiveSubscriptions extends Request { constructor() { super(RequestTypes.Data, HttpMethods$1.POST, new DataRequestData(), TransactionResponse); _defineProperty(this, "_serviceCode", 'GetActiveSubscriptions'); } get() { var _this = this; return _asyncToGenerator(function* () { _this.data.setServiceList(new ServiceList({ name: _this._serviceCode, version: 1, action: _this._serviceCode })); return _this.request().then(response => { return _this.format(response.data); }); })(); } format(data) { var _data$services; let activeSubscriptions = []; const xmlData = (_data$services = data.services) === null || _data$services === void 0 ? void 0 : _data$services[0].parameters[0].value; if (typeof xmlData === 'string') { let parseString = require('xml2js').parseString; parseString(xmlData, function (err, result) { activeSubscriptions = result['ArrayOfServiceCurrencies']['ServiceCurrencies'].map(service => { return { serviceCode: service['ServiceCode'][0], currencies: service['Currencies'][0]['string'] }; }); }); } return activeSubscriptions; } } class TransactionService { constructor(key) { _defineProperty(this, "_key", void 0); this._key = key; } status() { return new Request(`${RequestTypes.Transaction}/Status/${this._key}`, HttpMethods$1.GET, undefined, TransactionResponse).request(); } refundInfo() { return new Request(`${RequestTypes.Transaction}/RefundInfo/${this._key}`, HttpMethods$1.GET).request(); } cancelInfo() { return new Request(`${RequestTypes.Transaction}/Cancel/${this._key}`, HttpMethods$1.GET).request(); } } class Ideal extends PayablePaymentMethod { constructor(...args) { super(...args); _defineProperty(this, "_serviceVersion", 2); } defaultServiceCode() { return 'ideal'; } pay(data) { return super.pay(data, new Pay$m(data)); } payRemainder(payload) { return super.payRemainder(payload, new Pay$m(payload)); } issuers() { return this.specification(RequestTypes.Transaction).request().then(response => { var _response$getActionRe; return (_response$getActionRe = response.getActionRequestParameters('Pay')) === null || _response$getActionRe === void 0 || (_response$getActionRe = _response$getActionRe.find(item => item.name === 'issuer')) === null || _response$getActionRe === void 0 || (_response$getActionRe = _response$getActionRe.listItemDescriptions) === null || _response$getActionRe === void 0 ? void 0 : _response$getActionRe.map(item => { return { [item.value]: item.description }; }); }); } instantRefund(data) { return super.refund(data); } payFastCheckout(data) { this.setPayPayload(data); this._payload.order = ''; this.setServiceList('PayFastCheckout', new Pay$m(data)); return this.transactionRequest(); } } let Pay$l = class Pay extends ServiceParameter { set issuer(value) { this.set('issuer', value); } }; class IdealProcessing extends PayablePaymentMethod { constructor(...args) { super(...args); _defineProperty(this, "_serviceVersion", 2); } defaultServiceCode() { return 'idealprocessing'; } pay(data) { return super.pay(data, new Pay$l(data)); } payRemainder(payload) { return super.payRemainder(payload, new Pay$l(payload)); } issuers() { return this.specification(RequestTypes.Transaction).request().then(response => { var _response$getActionRe; return (_response$getActionRe = response.getActionRequestParameters('Pay')) === null || _response$getActionRe === void 0 || (_response$getActionRe = _response$getActionRe.find(item => item.name === 'issuer')) === null || _response$getActionRe === void 0 || (_response$getActionRe = _response$getActionRe.listItemDescriptions) === null || _response$getActionRe === void 0 ? void 0 : _response$getActionRe.map(item => { return { [item.value]: item.description }; }); }); } } class AfterPayArticle extends Article$3 { constructor(article) { super(article); } get price() { return this.get('grossUnitPrice'); } set price(price) { this.set('grossUnitPrice', price); } set imageUrl(imageUrl) { this.set('imageUrl', imageUrl); } set url(url) { this.set('url', url); } set refundType(refundType) { this.set('refundType', refundType); } set marketPlaceSellerId(marketPlaceSellerId) { this.set('marketPlaceSellerId', marketPlaceSellerId); } } let Phone$3 = class Phone extends Phone$4 { get mobile() { return this.get('mobilePhone'); } set mobile(phone) { this.set('mobilePhone', phone); } get landline() { return this.get('phone'); } set landline(phone) { this.set('phone', phone); } }; let Address$5 = class Address extends Address$6 { get houseNumber() { return this.get('streetNumber'); } set houseNumber(phone) { this.set('streetNumber', phone); } get houseNumberAdditional() { return this.get('streetNumberAdditional'); } set houseNumberAdditional(phone) { this.set('streetNumberAdditional', phone); } get zipcode() { return this.get('postalCode'); } set zipcode(phone) { this.set('postalCode', phone); } }; class AfterPayCompany extends Company$1 { set title(title) { this.set('salutation', title); } set chamberOfCommerce(chamberOfCommerce) { this.set('identificationNumber', chamberOfCommerce); } } class AfterPayPerson extends Person { constructor(data) { super(data); } set customerNumber(customerNumber) { this.set('customerNumber', customerNumber); } set identificationNumber(identificationNumber) { this.set('identificationNumber', identificationNumber); } set conversationLanguage(conversationLanguage) { this.set('conversationLanguage', conversationLanguage); } } let Customer$7 = class Customer extends Model { set recipient(recipient) { this.set('recipient', recipient.category === RecipientCategory$1.COMPANY ? new AfterPayCompany(recipient) : new AfterPayPerson(recipient)); } set address(address) { this.set('address', new Address$5(address)); } set email(email) { this.set('email', email); } set phone(phone) { this.set('phone', new Phone$3(phone)); } }; let Pay$k = class Pay extends ServiceParameter { set shipping(shipping) { this.set('shipping', new Customer$7(shipping)); } set billing(billing) { this.set('billing', new Customer$7(billing)); if (this.get('shipping') === undefined) { this.shipping = billing; } } set articles(articles) { this.set('articles', articles.map(article => new AfterPayArticle(article))); } set bankAccount(bankAccount) { this.set('bankAccount', bankAccount); } set bankCode(bankCode) { this.set('bankCode', bankCode); } set merchantImageUrl(merchantImageUrl) { this.set('merchantImageUrl', merchantImageUrl); } set summaryImageUrl(summaryImageUrl) { this.set('summaryImageUrl', summaryImageUrl); } set ourReference(ourReference) { this.set('ourReference', ourReference); } getGroups() { return super.getGroups({ Billing: 'BillingCustomer', Shipping: 'ShippingCustomer', Articles: 'Article' }); } getCountable() { return super.getCountable(['Articles']); } }; let Refund$2 = class Refund extends ServiceParameter { set articles(articles) { this.set('articles', articles.map(article => new AfterPayArticle(article))); } getGroups() { return super.getGroups({ Articles: 'Article' }); } getCountable() { return super.getCountable(['Articles']); } }; class Afterpay extends PayablePaymentMethod { constructor(...args) { super(...args); _defineProperty(this, "_serviceVersion", 1); } defaultServiceCode() { return 'afterpay'; } pay(payload) { return super.pay(payload, new Pay$k(payload)); } refund(payload) { return super.refund(payload, new Refund$2(payload)); } authorize(payload) { this.setServiceList('Authorize', new Pay$k(payload)); return this.transactionRequest(payload); } cancelAuthorize(payload) { this.setServiceList('CancelAuthorize'); return super.transactionRequest(payload); } capture(payload) { this.setServiceList('Capture', new Pay$k(payload)); return super.transactionRequest(payload); } payRemainder(payload) { return super.payRemainder(payload, new Pay$k(payload)); } authorizeRemainder(payload) { this.setServiceList('AuthorizeRemainder', new Pay$k(payload)); return super.transactionRequest(payload); } } let Article$2 = class Article extends Article$3 { get identifier() { return this.get('articleId'); } set identifier(identifier) { this.set('articleId', identifier); } get quantity() { return this.get('articleQuantity'); } set quantity(quantity) { this.set('articleQuantity', quantity); } get price() { return this.get('articleUnitprice'); } set price(price) { this.set('articleUnitprice', price); } get vatCategory() { return this.get('articleVatcategory'); } set vatCategory(vatCategory) { this.set('articleVatcategory', vatCategory); } get description() { return this.get('articleDescription'); } set description(description) { this.set('articleDescription', description); } }; let Address$4 = class Address extends Model { set prefix(value) { this.set('prefix', value, true); } set street(value) { this.set(`${this.get('prefix')}Street`, value); } set houseNumber(value) { this.set(`${this.get('prefix')}HouseNumber`, value); } set city(value) { this.set(`${this.get('prefix')}City`, value); } set houseNumberAdditional(value) { this.set(`${this.get('prefix')}HouseNumberSuffix`, value); } set zipcode(value) { this.set(`${this.get('prefix')}PostalCode`, value); } set country(value) { if (this.get('prefix') === 'shipping' && value === 'NL') { this.set(`${this.get('prefix')}CountryCode`,