@trap_stevo/merchtide
Version:
Empowering the future of digital commerce, this API delivers the ultimate solution for building and managing online superstores. Seamlessly integrating product management, payment processing, and order tracking, it offers unmatched flexibility and scalabi
882 lines (877 loc) • 82.2 kB
JavaScript
"use strict";
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator["return"] && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, "catch": function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, 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 _objectSpread(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 _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 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 _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
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 _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); }
function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
var EventEmitter = require("events");
var _require = require("./HUDManagers/UniversalUtilityManager"),
validEmail = _require.validEmail,
cleanData = _require.cleanData;
var PaymentUtilityManager = require("./HUDManagers/PaymentUtilityManager");
var PayCoreManager = require("./HUDManagers/PayCoreManager");
var ProductManager = require("./HUDManagers/ProductManager");
var OrderManager = require("./HUDManagers/OrderManager");
var MerchTide = /*#__PURE__*/function (_EventEmitter) {
function MerchTide() {
var _this;
_classCallCheck(this, MerchTide);
_this = _callSuper(this, MerchTide);
_this.purchUtilities = PaymentUtilityManager;
_this.productManager = ProductManager;
_this.orderManager = OrderManager;
_this.payCoreManager = PayCoreManager;
return _this;
}
// --- Payment Processor Management ---
/**
* Initializes a payment core (e.g., Stripe).
* @param {string} name - The name of the payment processor.
* @param {object} config - Configuration details for the payment processor.
* @returns {boolean} True if initialization succeeds.
*/
_inherits(MerchTide, _EventEmitter);
return _createClass(MerchTide, [{
key: "initializePayCore",
value: function initializePayCore(name, config) {
return this.payCoreManager.initializePayCore(name, config);
}
/**
* Retrieves a payment core (e.g., Stripe).
* @param {string} name - The name of the payment processor.
* @returns {object} Payment processor.
*/
}, {
key: "getPayCore",
value: function getPayCore(name) {
return this.payCoreManager.getPayCore(name);
}
/**
* Registers a product with the specified payment core and appends additional properties.
* @param {string} coreName - The payment core name (e.g., Stripe, PayPal).
* @param {number} productID - The ID of the product to register.
* @param {object} priceDetails - Details about the price (e.g., currency, interval, etc.).
* @param {object} additionalDetails - Additional details to register with the product.
* @returns {object} The updated product with payment core IDs.
*/
}, {
key: "registerProductWithPayCore",
value: (function () {
var _registerProductWithPayCore = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(coreName, productID, priceDetails) {
var _existingProducts$dat, _existingPrices$data;
var additionalDetails,
core,
product,
registeredProduct,
registeredPrice,
existingProducts,
existingPrices,
priceData,
updatedProduct,
_args = arguments;
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
additionalDetails = _args.length > 3 && _args[3] !== undefined ? _args[3] : {};
core = this.payCoreManager.getPayCore(coreName);
if (core) {
_context.next = 4;
break;
}
throw new Error("Payment core '".concat(coreName, "' not initialized."));
case 4:
product = this.productManager.getProductByID(productID);
if (product) {
_context.next = 7;
break;
}
throw new Error("Product not found.");
case 7:
if (!(product["".concat(coreName, "ProductID")] && product["".concat(coreName, "PriceID")])) {
_context.next = 10;
break;
}
console.log("Product already registered with ".concat(coreName, ". Skipping creation."));
return _context.abrupt("return", product);
case 10:
_context.t0 = coreName.toLowerCase();
_context.next = _context.t0 === "stripe" ? 13 : _context.t0 === "paypal" ? 35 : 42;
break;
case 13:
_context.next = 15;
return core.products.search({
query: "name:'".concat(product.name, "'")
});
case 15:
existingProducts = _context.sent;
if (!((existingProducts === null || existingProducts === void 0 || (_existingProducts$dat = existingProducts.data) === null || _existingProducts$dat === void 0 ? void 0 : _existingProducts$dat.length) > 0)) {
_context.next = 21;
break;
}
registeredProduct = existingProducts.data[0];
console.log("Found existing Stripe product ~ ".concat(registeredProduct.id));
_context.next = 24;
break;
case 21:
_context.next = 23;
return core.products.create(_objectSpread({
name: product.name,
description: product.description
}, additionalDetails));
case 23:
registeredProduct = _context.sent;
case 24:
_context.next = 26;
return core.prices.list({
product: registeredProduct.id,
active: true
});
case 26:
existingPrices = _context.sent;
if ((existingPrices === null || existingPrices === void 0 || (_existingPrices$data = existingPrices.data) === null || _existingPrices$data === void 0 ? void 0 : _existingPrices$data.length) > 0) {
registeredPrice = existingPrices.data.find(function (p) {
return p.unit_amount === priceDetails.unitAmount && p.currency === (priceDetails.currency || "usd") && JSON.stringify(p.recurring) === JSON.stringify(priceDetails.recurring || null);
});
if (registeredPrice) {
console.log("Found existing Stripe price: ".concat(registeredPrice.id));
}
}
if (registeredPrice) {
_context.next = 34;
break;
}
priceData = {
unit_amount: priceDetails.unitAmount,
currency: priceDetails.currency || "usd",
product: registeredProduct.id
};
if (priceDetails.recurring) {
priceData.recurring = priceDetails.recurring;
}
_context.next = 33;
return core.prices.create(priceData);
case 33:
registeredPrice = _context.sent;
case 34:
return _context.abrupt("break", 43);
case 35:
_context.next = 37;
return core.createProduct(_objectSpread({
name: product.name,
description: product.description
}, additionalDetails));
case 37:
registeredProduct = _context.sent;
_context.next = 40;
return core.createPlan({
billing_cycles: priceDetails.recurring || null,
currency: priceDetails.currency || "usd",
amount: priceDetails.unitAmount / 100,
product_id: registeredProduct.id
});
case 40:
registeredPrice = _context.sent;
return _context.abrupt("break", 43);
case 42:
throw new Error("Unsupported payment core '".concat(coreName, "'."));
case 43:
updatedProduct = this.productManager.updateProduct(productID, _defineProperty(_defineProperty({}, "".concat(coreName, "ProductID"), registeredProduct.id), "".concat(coreName, "PriceID"), registeredPrice.id));
this.emit("product-registered", updatedProduct);
return _context.abrupt("return", updatedProduct);
case 46:
case "end":
return _context.stop();
}
}, _callee, this);
}));
function registerProductWithPayCore(_x, _x2, _x3) {
return _registerProductWithPayCore.apply(this, arguments);
}
return registerProductWithPayCore;
}()
/**
* Updates the pricing details of a registered product in the PayCore.
* @param {string} coreName - The payment processor name (e.g., "stripe", "paypal").
* @param {number} productID - The product ID in MerchTide.
* @param {object} newPriceDetails - The new pricing details (currency, unit amount, recurring details).
* @returns {object} The updated product with new pricing.
*/
)
}, {
key: "updateProductPricingInPayCore",
value: (function () {
var _updateProductPricingInPayCore = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(coreName, productID, newPriceDetails) {
var core, product, updatedPrice, productUpdatedPricing, updatedProduct;
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
while (1) switch (_context2.prev = _context2.next) {
case 0:
core = this.payCoreManager.getPayCore(coreName);
if (core) {
_context2.next = 3;
break;
}
throw new Error("Payment core '".concat(coreName, "' not initialized."));
case 3:
product = this.productManager.getProductByID(productID);
if (product) {
_context2.next = 6;
break;
}
throw new Error("Product not found.");
case 6:
_context2.t0 = coreName.toLowerCase();
_context2.next = _context2.t0 === "stripe" ? 9 : _context2.t0 === "paypal" ? 21 : 27;
break;
case 9:
if (product.stripeProductID) {
_context2.next = 11;
break;
}
throw new Error("Product not registered with Stripe.");
case 11:
productUpdatedPricing = {
unit_amount: newPriceDetails.unitAmount,
currency: newPriceDetails.currency || "usd",
product: product.stripeProductID
};
if (newPriceDetails.recurring) {
productUpdatedPricing.recurring = newPriceDetails.recurring;
}
_context2.next = 15;
return core.prices.create(productUpdatedPricing);
case 15:
updatedPrice = _context2.sent;
if (!product.stripePriceID) {
_context2.next = 19;
break;
}
_context2.next = 19;
return core.prices.update(product.stripePriceID, {
active: false
});
case 19:
product.stripePriceID = updatedPrice.id;
return _context2.abrupt("break", 28);
case 21:
if (product.paypalPlanID) {
_context2.next = 23;
break;
}
throw new Error("Product not registered with PayPal.");
case 23:
_context2.next = 25;
return core.plans.update(product.paypalPlanID, {
billing_cycles: newPriceDetails.recurring || null,
currency_code: newPriceDetails.currency || "usd",
amount: (newPriceDetails.unitAmount / 100).toFixed(2)
});
case 25:
updatedPrice = _context2.sent;
return _context2.abrupt("break", 28);
case 27:
throw new Error("Unsupported payment core '".concat(coreName, "'."));
case 28:
updatedProduct = this.productManager.updateProduct(productID, _defineProperty({}, "".concat(coreName, "PriceID"), updatedPrice.id));
this.emit("product-price-updated", updatedProduct);
return _context2.abrupt("return", updatedProduct);
case 31:
case "end":
return _context2.stop();
}
}, _callee2, this);
}));
function updateProductPricingInPayCore(_x4, _x5, _x6) {
return _updateProductPricingInPayCore.apply(this, arguments);
}
return updateProductPricingInPayCore;
}())
}, {
key: "processPaymentWithCore",
value: function () {
var _processPaymentWithCore = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3(core, coreName, paymentData) {
var eventID,
paymentEventDetails,
paymentProcessedDetails,
result,
stripePaymentData,
paymentMethodType,
_paymentData$automati,
_paymentData$automati2,
finalAmount,
paypalPurchaseUnit,
_args3 = arguments;
return _regeneratorRuntime().wrap(function _callee3$(_context3) {
while (1) switch (_context3.prev = _context3.next) {
case 0:
eventID = _args3.length > 3 && _args3[3] !== undefined ? _args3[3] : "payment-created";
paymentEventDetails = _args3.length > 4 && _args3[4] !== undefined ? _args3[4] : {};
paymentProcessedDetails = _args3.length > 5 && _args3[5] !== undefined ? _args3[5] : {};
if (core) {
_context3.next = 5;
break;
}
throw new Error("Payment core '".concat(coreName, "' not initialized."));
case 5:
_context3.t0 = coreName.toLowerCase();
_context3.next = _context3.t0 === "stripe" ? 8 : _context3.t0 === "paypal" ? 17 : 24;
break;
case 8:
stripePaymentData = {
currency: paymentData.currencySymbol || "usd",
amount: paymentData.finalAmount,
confirm: true,
metadata: paymentData.metadata || {}
};
if (paymentData.receiptEmail && validEmail(paymentData.receiptEmail)) {
stripePaymentData.receipt_email = paymentData.receiptEmail;
}
if (paymentData.payment_method && paymentData.payment_method.startsWith("pm_")) {
stripePaymentData.payment_method = paymentData.payment_method;
if (paymentData.customerID) {
stripePaymentData.customer = paymentData.customerID;
}
} else if (paymentData.payment_method) {
paymentMethodType = paymentData.paymentMethodType || "card";
stripePaymentData.payment_method_data = _objectSpread(_objectSpread({
type: paymentMethodType
}, paymentMethodType === "card" ? {
card: {
number: paymentData.payment_method
}
} : {}), {}, {
billing_details: stripePaymentBillingData
}, paymentData.paymentMethodDataConfigurations || {});
}
if (paymentData.automaticPaymentMethods) {
stripePaymentData.automatic_payment_methods = {
enabled: (_paymentData$automati = paymentData.automaticPaymentMethods.enabled) !== null && _paymentData$automati !== void 0 ? _paymentData$automati : true,
allow_redirects: (_paymentData$automati2 = paymentData.automaticPaymentMethods.allowRedirects) !== null && _paymentData$automati2 !== void 0 ? _paymentData$automati2 : "never",
preferred_methods: paymentData.automaticPaymentMethods.preferredMethods || undefined
};
}
if (paymentData.returnUrl) {
stripePaymentData.return_url = paymentData.returnUrl;
}
_context3.next = 15;
return core.paymentIntents.create(stripePaymentData);
case 15:
result = _context3.sent;
return _context3.abrupt("break", 25);
case 17:
finalAmount = paymentData.finalAmount;
paypalPurchaseUnit = {
amount: {
currency_code: paymentData.currencySymbol || "USD",
value: (finalAmount / 100).toFixed(2)
},
custom_id: paymentData.metadata ? JSON.stringify(paymentData.metadata) : undefined
};
if (paymentData.billingAddress) {
paypalPurchaseUnit.shipping = {
name: {
full_name: paymentData.billingAddress.name
},
address: {
address_line_1: paymentData.billingAddress.line1 || undefined,
address_line_2: paymentData.billingAddress.line2 || undefined,
admin_area_2: paymentData.billingAddress.city || undefined,
admin_area_1: paymentData.billingAddress.state || undefined,
postal_code: paymentData.billingAddress.postalCode || undefined,
country_code: paymentData.billingAddress.country || undefined
}
};
}
_context3.next = 22;
return core.orders.create(_objectSpread({
intent: "CAPTURE",
purchase_units: [paypalPurchaseUnit]
}, paymentData.returnUrl && {
return_url: paymentData.returnUrl
}));
case 22:
result = _context3.sent;
return _context3.abrupt("break", 25);
case 24:
throw new Error("Unsupported payment core '".concat(coreName, "'."));
case 25:
this.emit(eventID, _objectSpread({
coreName: coreName,
paymentData: paymentData,
result: result
}, paymentEventDetails || {}));
return _context3.abrupt("return", _objectSpread({
paymentDetails: result,
totalPaid: paymentData.finalAmount
}, paymentProcessedDetails || {}));
case 27:
case "end":
return _context3.stop();
}
}, _callee3, this);
}));
function processPaymentWithCore(_x7, _x8, _x9) {
return _processPaymentWithCore.apply(this, arguments);
}
return processPaymentWithCore;
}() // --- Payment Management ---
/**
* Creates a payment intent.
* @param {string} coreName - The payment core name.
* @param {object} data - Payment intent details.
* @param {string} eventID - The event id to broadcast the payment results to.
* @param {object} paymentEventDetails - Payment details returned in a payment event.
* @param {object} paymentProcessedDetails - Payment details returned upon payment success.
* @returns {object} The payment intent.
*/
}, {
key: "createPayment",
value: function () {
var _createPayment = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee4(coreName, data) {
var eventID,
paymentEventDetails,
paymentProcessedDetails,
core,
product,
finalAmount,
quantity,
subtotal,
taxAmount,
_args4 = arguments;
return _regeneratorRuntime().wrap(function _callee4$(_context4) {
while (1) switch (_context4.prev = _context4.next) {
case 0:
eventID = _args4.length > 2 && _args4[2] !== undefined ? _args4[2] : "payment-created";
paymentEventDetails = _args4.length > 3 && _args4[3] !== undefined ? _args4[3] : {};
paymentProcessedDetails = _args4.length > 4 && _args4[4] !== undefined ? _args4[4] : {};
core = this.payCoreManager.getPayCore(coreName);
if (core) {
_context4.next = 6;
break;
}
throw new Error("Payment core '".concat(coreName, "' not initialized."));
case 6:
product = this.productManager.getProductByID(data.productID);
if (!(!product || !product.unitPrice)) {
_context4.next = 9;
break;
}
throw new Error("Product not found or missing unit price.");
case 9:
if (!data.quantity) {
_context4.next = 16;
break;
}
quantity = data.quantity;
taxAmount = data.taxAmount ? PaymentUtilityManager.convertToCents(data.taxAmount, data.currencySymbol || "usd") : 0;
subtotal = quantity * product.unitPrice;
finalAmount = subtotal + taxAmount;
_context4.next = 30;
break;
case 16:
if (!data.amount) {
_context4.next = 29;
break;
}
if (!isNaN(data.amount)) {
_context4.next = 19;
break;
}
throw new Error("Invalid amount provided.");
case 19:
taxAmount = data.taxAmount ? PaymentUtilityManager.convertToCents(data.taxAmount, data.currencySymbol || "usd") : 0;
subtotal = PaymentUtilityManager.convertToCents(data.amount, data.currencySymbol || "usd");
if (!(subtotal < taxAmount)) {
_context4.next = 23;
break;
}
throw new Error("Invalid amount ~ Tax exceeds total payment.");
case 23:
finalAmount = subtotal + taxAmount;
quantity = Math.floor(subtotal / product.unitPrice);
if (!(quantity <= 0)) {
_context4.next = 27;
break;
}
throw new Error("Invalid amount ~ Not enough to purchase even one unit.");
case 27:
_context4.next = 30;
break;
case 29:
throw new Error("Must provide an 'amount' or 'quantity' (Usage ~ data.amount or data.quantity).");
case 30:
_context4.next = 32;
return this.processPaymentWithCore(core, coreName, _objectSpread(_objectSpread({}, data), {}, {
finalAmount: finalAmount,
payment_method: data.payment_method,
currencySymbol: data.currencySymbol,
billingAddress: data.billingAddress,
automaticPaymentMethods: data.automaticPaymentMethods,
returnUrl: data.returnUrl
}), eventID, _objectSpread({
subtotalPaid: subtotal,
totalPaid: finalAmount,
taxPaid: taxAmount,
quantity: quantity
}, paymentEventDetails || {}), _objectSpread({
quantityPurchased: quantity,
subtotalPaid: subtotal,
taxPaid: taxAmount
}, paymentProcessedDetails || {}));
case 32:
return _context4.abrupt("return", _context4.sent);
case 33:
case "end":
return _context4.stop();
}
}, _callee4, this);
}));
function createPayment(_x10, _x11) {
return _createPayment.apply(this, arguments);
}
return createPayment;
}()
/**
* Issues a refund for a payment.
* @param {string} coreName - The payment core name.
* @param {object} data - Refund details.
* @returns {object} The refund.
*/
}, {
key: "createRefund",
value: (function () {
var _createRefund = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee5(coreName, data) {
var core, result;
return _regeneratorRuntime().wrap(function _callee5$(_context5) {
while (1) switch (_context5.prev = _context5.next) {
case 0:
core = this.payCoreManager.getPayCore(coreName);
if (core) {
_context5.next = 3;
break;
}
throw new Error("Payment core '".concat(coreName, "' not initialized."));
case 3:
_context5.t0 = coreName.toLowerCase();
_context5.next = _context5.t0 === "stripe" ? 6 : _context5.t0 === "paypal" ? 10 : 14;
break;
case 6:
_context5.next = 8;
return core.refunds.create(data);
case 8:
result = _context5.sent;
return _context5.abrupt("break", 15);
case 10:
_context5.next = 12;
return core.refunds.create({
transaction_id: data.transactionID,
amount: {
currency_code: data.currencySymbol || "USD",
value: data.amount ? (data.amount / 100).toFixed(2) : undefined
}
});
case 12:
result = _context5.sent;
return _context5.abrupt("break", 15);
case 14:
throw new Error("Unsupported payment core '".concat(coreName, "'."));
case 15:
this.emit("refund-created", {
coreName: coreName,
data: data,
result: result
});
return _context5.abrupt("return", result);
case 17:
case "end":
return _context5.stop();
}
}, _callee5, this);
}));
function createRefund(_x12, _x13) {
return _createRefund.apply(this, arguments);
}
return createRefund;
}()
/**
* Creates a subscription for a customer.
* @param {string} coreName - The payment core name.
* @param {object} data - Subscription details.
* @param {string} data.customerID - The Stripe customer ID.
* @param {string} data.priceID - The Stripe price ID (from the product pricing setup).
* @param {string} [data.trialEnd] - Optional trial end timestamp.
* @returns {object} The created subscription.
*/
)
}, {
key: "createSubscription",
value: (function () {
var _createSubscription = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee6(coreName, data) {
var core, result, stripeProduct, subscriptionData, payPalProduct;
return _regeneratorRuntime().wrap(function _callee6$(_context6) {
while (1) switch (_context6.prev = _context6.next) {
case 0:
core = this.payCoreManager.getPayCore(coreName);
if (core) {
_context6.next = 3;
break;
}
throw new Error("Payment core '".concat(coreName, "' not initialized."));
case 3:
if (data.customerID) {
_context6.next = 5;
break;
}
throw new Error("Customer ID required for subscriptions (Usage ~ data.customerID).");
case 5:
_context6.next = 7;
return this.validateCustomer(core, data.customerID);
case 7:
_context6.t0 = coreName.toLowerCase();
_context6.next = _context6.t0 === "stripe" ? 10 : _context6.t0 === "paypal" ? 18 : 25;
break;
case 10:
stripeProduct = this.productManager.getProductByID(data.productID);
if (!(!stripeProduct || !stripeProduct.stripePriceID)) {
_context6.next = 13;
break;
}
throw new Error("Product not registered.");
case 13:
subscriptionData = _objectSpread({
customer: data.customerID,
items: [{
price: stripeProduct.stripePriceID
}]
}, data.trialEnd && {
trial_end: data.trialEnd
});
_context6.next = 16;
return core.subscriptions.create(subscriptionData);
case 16:
result = _context6.sent;
return _context6.abrupt("break", 26);
case 18:
payPalProduct = this.productManager.getProductByID(data.productID);
if (!(!payPalProduct || !payPalProduct.paypalPriceID)) {
_context6.next = 21;
break;
}
throw new Error("Product not registered.");
case 21:
_context6.next = 23;
return core.subscriptions.create(_objectSpread({
plan_id: payPalProduct.paypalPriceID,
subscriber: {
name: {
given_name: data.customerFirstName,
surname: data.customerLastName
},
email_address: data.customerEmail
}
}, data.trialEnd && {
start_time: new Date(data.trialEnd * 1000).toISOString()
}));
case 23:
result = _context6.sent;
return _context6.abrupt("break", 26);
case 25:
throw new Error("Unsupported payment core '".concat(coreName, "'."));
case 26:
this.emit("subscription-created", {
coreName: coreName,
data: data,
result: result
});
return _context6.abrupt("return", result);
case 28:
case "end":
return _context6.stop();
}
}, _callee6, this);
}));
function createSubscription(_x14, _x15) {
return _createSubscription.apply(this, arguments);
}
return createSubscription;
}()
/**
* Reactivates a subscription set to cancel at the end of the billing period.
* This removes the `cancel_at_period_end` flag so that the subscription continues beyond the current cycle.
*
* @param {string} coreName - The payment core name (e.g., "stripe").
* @param {string} subscriptionID - The ID of the canceled subscription.
* @returns {object} The updated subscription details.
*/
)
}, {
key: "reactivateSubscription",
value: (function () {
var _reactivateSubscription = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee7(coreName, subscriptionID) {
var core, subscription, paypalSubscription;
return _regeneratorRuntime().wrap(function _callee7$(_context7) {
while (1) switch (_context7.prev = _context7.next) {
case 0:
core = merchTide.payCoreManager.getPayCore(coreName);
if (core) {
_context7.next = 3;
break;
}
throw new Error("Payment core '".concat(coreName, "' not initialized."));
case 3:
_context7.prev = 3;
_context7.t0 = coreName.toLowerCase();
_context7.next = _context7.t0 === "stripe" ? 7 : _context7.t0 === "paypal" ? 22 : 39;
break;
case 7:
_context7.next = 9;
return core.subscriptions.retrieve(subscriptionID);
case 9:
subscription = _context7.sent;
if (subscription) {
_context7.next = 12;
break;
}
throw new Error("Subscription ~ ".concat(subscriptionID, " not found."));
case 12:
if (!subscription.cancel_at_period_end) {
_context7.next = 19;
break;
}
_context7.next = 15;
return core.subscriptions.update(subscriptionID, {
cancel_at_period_end: false
});
case 15:
result = _context7.sent;
console.log("Subscription ~ ".concat(subscriptionID, " reactivated successfully!"));
_context7.next = 21;
break;
case 19:
console.log("Subscription ~ ".concat(subscriptionID, " already active!"));
result = subscription;
case 21:
return _context7.abrupt("break", 40);
case 22:
_context7.next = 24;
return core.subscriptions.get(subscriptionID);
case 24:
paypalSubscription = _context7.sent;
if (paypalSubscription) {
_context7.next = 27;
break;
}
throw new Error("Subscription ~ ".concat(subscriptionID, " not found."));
case 27:
if (!(paypalSubscription.status === "SUSPENDED" || paypalSubscription.status === "CANCELLED")) {
_context7.next = 36;
break;
}
_context7.next = 30;
return core.subscriptions.activate(subscriptionID);
case 30:
_context7.next = 32;
return core.subscriptions.get(subscriptionID);
case 32:
result = _context7.sent;
console.log("Subscription ~ ".concat(subscriptionID, " reactivated successfully!"));
_context7.next = 38;
break;
case 36:
console.log("Subscription ~ ".concat(subscriptionID, " already active!"));
result = paypalSubscription;
case 38:
return _context7.abrupt("break", 40);
case 39:
throw new Error("Unsupported payment core '".concat(coreName, "'."));
case 40:
return _context7.abrupt("return", result);
case 43:
_context7.prev = 43;
_context7.t1 = _context7["catch"](3);
console.error("Subscription Reactivation Error ~", _context7.t1);
throw _context7.t1;
case 47:
case "end":
return _context7.stop();
}
}, _callee7, null, [[3, 43]]);
}));
function reactivateSubscription(_x16, _x17) {
return _reactivateSubscription.apply(this, arguments);
}
return reactivateSubscription;
}()
/**
* Refunds the latest invoice of a canceled subscription.
* @param {string} coreName - The payment core name (e.g., "stripe").
* @param {string} subscriptionID - The ID of the canceled subscription.
* @param {number} refundAmount - (Optional) The amount to refund. A full refund will get issued if not provided.
* @returns {object} Refund details.
*/
)
}, {
key: "refundSubscription",
value: (function () {
var _refundSubscription = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee8(coreName, subscriptionID) {
var refundAmount,
core,
result,
subscription,
invoice,
charge,
amountToRefund,
refund,
_subscription,
transactionID,
_amountToRefund,
_refund,
_args8 = arguments;
return _regeneratorRuntime().wrap(function _callee8$(_context8) {
while (1) switch (_context8.prev = _context8.next) {
case 0:
refundAmount = _args8.length > 2 && _args8[2] !== undefined ? _args8[2] : null;
core = this.payCoreManager.getPayCore(coreName);
if (core) {
_context8.next = 4;
break;
}
throw new Error("Payment core '".concat(coreName, "' not initialized."));
case 4:
_context8.t0 = coreName.toLowerCase();
_context8.next = _context8.t0 === "stripe" ? 7 : _context8.t0 === "paypal" ? 36 : 58;
break;
case 7:
_context8.prev = 7;
_context8.next = 10;
return core.subscriptions.retrieve(subscriptionID);
case 10:
subscription = _context8.sent;
if (subscription.latest_invoice) {
_context8.next = 13;
break;
}
throw new Error("No invoice found for subscription ~ ".concat(subscriptionID));
case 13:
_context8.next = 15;
return core.invoices.retrieve(subscription.latest_invoice);
case 15:
invoice = _context8.sent;
if (invoice.charge) {
_context8.next = 18;
break;
}
throw new Error("No charge found on invoice ~ ".concat(invoice.i