UNPKG

medusa-plugin-culqi-card

Version:

Medusa plugin for processing credit card payments with Culqi

851 lines (845 loc) 42.3 kB
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray")); var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")); var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits")); var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")); var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")); var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty")); var _medusa = require("@medusajs/medusa"); var _medusaCoreUtils = require("medusa-core-utils"); var _culqi = require("../types/culqi"); var _culqiClient = _interopRequireDefault(require("../helpers/culqi-client")); var _culqi2 = require("../helpers/culqi"); function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { (0, _defineProperty2["default"])(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = (0, _getPrototypeOf2["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2["default"])(this, result); }; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } var CulqiCardPaymentService = /*#__PURE__*/function (_AbstractPaymentServi) { (0, _inherits2["default"])(CulqiCardPaymentService, _AbstractPaymentServi); var _super = _createSuper(CulqiCardPaymentService); function CulqiCardPaymentService(_ref, options) { var _this; var manager = _ref.manager, customerService = _ref.customerService, cartService = _ref.cartService, culqiLogService = _ref.culqiLogService; (0, _classCallCheck2["default"])(this, CulqiCardPaymentService); _this = _super.call(this, arguments[0]); _this.manager_ = manager; _this.customerService_ = customerService; _this.cartService_ = cartService; _this.culqiClient_ = new _culqiClient["default"](culqiLogService); _this.capture_ = process.env.CULQI_CAPTURE === 'true'; return _this; } (0, _createClass2["default"])(CulqiCardPaymentService, [{ key: "updatePaymentDetails", value: function () { var _updatePaymentDetails = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(paymentSessionData, data) { var same_as_shipping_address, billing_address, card_id, card_token, save_card, culqiCustomerId, isRecurringOrder, antifraudDetailsFromBillingAddress, customer, shippingAddress, billingAddress, updatedSessionData, updatedCulqiCustomer, lastUsedCardId, promises, updateCustomerRequest, cardId, responses; return _regenerator["default"].wrap(function _callee$(_context) { while (1) switch (_context.prev = _context.next) { case 0: same_as_shipping_address = data.same_as_shipping_address, billing_address = data.billing_address, card_id = data.card_id, card_token = data.card_token, save_card = data.save_card; culqiCustomerId = paymentSessionData.customer_id; isRecurringOrder = paymentSessionData.is_recurring_order; antifraudDetailsFromBillingAddress = paymentSessionData.antifraud_details_from_billing_address; customer = paymentSessionData.customer; shippingAddress = paymentSessionData.shipping_address; billingAddress = same_as_shipping_address ? shippingAddress : billing_address; updatedSessionData = _objectSpread({}, paymentSessionData); updatedCulqiCustomer = false; promises = []; if (!(!card_id && !card_token)) { _context.next = 12; break; } throw new _medusaCoreUtils.MedusaError(_medusaCoreUtils.MedusaError.Types.INVALID_ARGUMENT, 'Card id or card token is required'); case 12: if (!(!same_as_shipping_address && !billing_address)) { _context.next = 14; break; } throw new _medusaCoreUtils.MedusaError(_medusaCoreUtils.MedusaError.Types.INVALID_ARGUMENT, 'Billing address is required'); case 14: if (!(isRecurringOrder && !card_id && !save_card)) { _context.next = 16; break; } throw new _medusaCoreUtils.MedusaError(_medusaCoreUtils.MedusaError.Types.INVALID_ARGUMENT, 'Saving a card is required for recurring orders'); case 16: /* * this condition is only met when billing address is * different from shipping address, or the billing address * is set back to the shipping address after being set to * a different address * */ if (!same_as_shipping_address || antifraudDetailsFromBillingAddress) { /* * update anti-fraud details if billing address is updated * */ updatedSessionData.antifraud_details = (0, _culqi2.getChargeAntiFraudDetails)({ address: billingAddress }); updatedSessionData.antifraud_details_from_billing_address = !same_as_shipping_address; /* * if guest customer and billing address is updated, * then update Culqi customer with billing address info * */ if (!(customer !== null && customer !== void 0 && customer.has_account)) { updateCustomerRequest = { first_name: billingAddress.first_name, last_name: billingAddress.last_name, address: billingAddress.address_1, address_city: billingAddress.city, country_code: billingAddress.country_code, phone_number: billingAddress.phone }; updatedCulqiCustomer = true; promises.push(this.culqiClient_.updateCustomerAsync(culqiCustomerId, updateCustomerRequest)); } } if (!card_id) { _context.next = 22; break; } updatedSessionData.source_id = card_id; lastUsedCardId = card_id; _context.next = 31; break; case 22: if (!save_card) { _context.next = 30; break; } _context.next = 25; return (0, _culqi2.createCard)({ culqiClient: this.culqiClient_, customerId: culqiCustomerId, cardToken: card_token, billingAddress: billingAddress }); case 25: cardId = _context.sent; updatedSessionData.source_id = cardId; lastUsedCardId = cardId; _context.next = 31; break; case 30: updatedSessionData.source_id = card_token; case 31: // update customer's last used card id if (lastUsedCardId && customer) { promises.push(this.customerService_.update(customer.id, { metadata: _objectSpread(_objectSpread({}, customer.metadata), {}, { last_used_culqi_card_id: lastUsedCardId }) })); } _context.next = 34; return Promise.allSettled(promises); case 34: responses = _context.sent; responses.forEach(function (response, idx) { if (updatedCulqiCustomer && idx === 0) { var updateCulqiCustomerSuccessful = false; if (response.status === 'fulfilled') { var _ref2 = response.value, _ref3 = (0, _slicedToArray2["default"])(_ref2, 2), _ = _ref3[0], error = _ref3[1]; updateCulqiCustomerSuccessful = !error; } if (!updateCulqiCustomerSuccessful) { /* * continue with the flow, but log the error * about Culqi customer not being updated * */ } } else { if (response.status === 'rejected') { /* * continue with the flow, but log the error * about customer's last used card id not being updated * */ } } }); return _context.abrupt("return", updatedSessionData); case 37: case "end": return _context.stop(); } }, _callee, this); })); function updatePaymentDetails(_x, _x2) { return _updatePaymentDetails.apply(this, arguments); } return updatePaymentDetails; }() }, { key: "updateBillingDetails", value: function updateBillingDetails(paymentSessionData, data) { var billing_type = data.billing_type, invoice_owner_identifier = data.invoice_owner_identifier; if (!billing_type) { throw new _medusaCoreUtils.MedusaError(_medusaCoreUtils.MedusaError.Types.INVALID_ARGUMENT, 'Billing Type is required'); } if (billing_type === 'invoice' && !invoice_owner_identifier) { throw new _medusaCoreUtils.MedusaError(_medusaCoreUtils.MedusaError.Types.INVALID_ARGUMENT, 'Invoice Owner Identifier is required'); } var updatedSessionData = _objectSpread(_objectSpread({}, paymentSessionData), {}, { billing_type: billing_type }); if (billing_type === 'invoice') { updatedSessionData.invoice_owner_identifier = invoice_owner_identifier; } return updatedSessionData; } /** * initiate payment * @summary This method is called during checkout when Payment Sessions are initialized to present payment options to the customer. It is used to allow you to make any necessary calls to the third-party provider to initialize the payment. * @param {Cart & PaymentContext} context - The context of the payment * @returns {Promise} - The result of the operation */ }, { key: "createPayment", value: function () { var _createPayment = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(context) { var _customer$metadata; var customer, cart, currency_code, amount, email, shipping_address, sessionData, customerMetadata, findOptions, _yield$getOrCreateCul, _yield$getOrCreateCul2, culqiCustomerId, _, error; return _regenerator["default"].wrap(function _callee2$(_context2) { while (1) switch (_context2.prev = _context2.next) { case 0: customer = context.customer, cart = context.cart, currency_code = context.currency_code, amount = context.amount; email = cart.email, shipping_address = cart.shipping_address; sessionData = { currency: currency_code, amount: amount, email: email, customer: customer, shipping_address: shipping_address, antifraud_details: (0, _culqi2.getChargeAntiFraudDetails)({ address: shipping_address, customer: customer, customerTakesPriority: true }), is_recurring_order: cart.context.is_recurring_order }; customerMetadata = {}; findOptions = { culqiClient: this.culqiClient_, customer: customer, email: email, address: shipping_address }; _context2.next = 7; return (0, _culqi2.getOrCreateCulqiCustomer)(findOptions); case 7: _yield$getOrCreateCul = _context2.sent; _yield$getOrCreateCul2 = (0, _slicedToArray2["default"])(_yield$getOrCreateCul, 3); culqiCustomerId = _yield$getOrCreateCul2[0]; _ = _yield$getOrCreateCul2[1]; error = _yield$getOrCreateCul2[2]; if (!error) { _context2.next = 14; break; } throw new _medusaCoreUtils.MedusaError(_medusaCoreUtils.MedusaError.Types.UNEXPECTED_STATE, error.merchant_message); case 14: sessionData.customer_id = culqiCustomerId; // if needed, save new Culqi customer id in customer metadata if (!(customer !== null && customer !== void 0 && (_customer$metadata = customer.metadata) !== null && _customer$metadata !== void 0 && _customer$metadata.culqi_customer_id)) { customerMetadata.culqi_customer_id = culqiCustomerId; } return _context2.abrupt("return", { update_requests: { customer_metadata: customerMetadata }, session_data: sessionData }); case 17: case "end": return _context2.stop(); } }, _callee2, this); })); function createPayment(_x3) { return _createPayment.apply(this, arguments); } return createPayment; }() /** * update payment data * @summary This method is used to update the data field of a Payment Session. Particularly, it is called when a request is sent to the Update Payment Session endpoint. This endpoint receives a data object in the body of the request that should be used to update the existing data field of the Payment Session. * @param {PaymentSessionData} paymentSessionData - The data of the payment session * @param {Data} data - The data to update the payment session with * @returns {Promise} - The result of the operation */ }, { key: "updatePaymentData", value: function () { var _updatePaymentData = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3(paymentSessionData, data) { var card_id, card_token, billing_type, updatedSessionData; return _regenerator["default"].wrap(function _callee3$(_context3) { while (1) switch (_context3.prev = _context3.next) { case 0: card_id = data.card_id, card_token = data.card_token, billing_type = data.billing_type; if (!(!card_id && !card_token && !billing_type)) { _context3.next = 3; break; } throw new _medusaCoreUtils.MedusaError(_medusaCoreUtils.MedusaError.Types.INVALID_ARGUMENT, 'Card id or card token is required'); case 3: updatedSessionData = _objectSpread({}, paymentSessionData); if (!(card_id || card_token)) { _context3.next = 8; break; } _context3.next = 7; return this.updatePaymentDetails(paymentSessionData, data); case 7: updatedSessionData = _context3.sent; case 8: if (billing_type) { updatedSessionData = this.updateBillingDetails(updatedSessionData, data); } return _context3.abrupt("return", updatedSessionData); case 10: case "end": return _context3.stop(); } }, _callee3, this); })); function updatePaymentData(_x4, _x5) { return _updatePaymentData.apply(this, arguments); } return updatePaymentData; }() /** * update payment * @summary This method is used to perform any necessary updates on the payment. This method is called whenever the cart or any of its related data is updated. For example, when a line item is added to the cart or when a shipping method is selected. * @param {PaymentSessionData} paymentSessionData - The data of the payment session * @param {Cart & PaymentContext} context - The context of the payment * @returns {Promise} - The result of the operation */ }, { key: "updatePayment", value: function () { var _updatePayment = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee4(paymentSessionData, context) { var oldEmail, oldCustomer, customer, cart, currency_code, amount, email, shipping_address, updatedSessionData, findOptions, _yield$getOrCreateCul3, _yield$getOrCreateCul4, culqiCustomerId, _, error, _oldCustomer$metadata, oldCulqiCustomerId; return _regenerator["default"].wrap(function _callee4$(_context4) { while (1) switch (_context4.prev = _context4.next) { case 0: oldEmail = paymentSessionData.email; oldCustomer = paymentSessionData.customer; customer = context.customer, cart = context.cart, currency_code = context.currency_code, amount = context.amount; email = cart.email, shipping_address = cart.shipping_address; updatedSessionData = _objectSpread(_objectSpread({}, paymentSessionData), {}, { currency: currency_code, amount: amount, email: email, customer: customer, shipping_address: shipping_address, antifraud_details: (0, _culqi2.getChargeAntiFraudDetails)({ address: shipping_address, customer: customer, customerTakesPriority: true }), antifraud_details_from_billing_address: false, is_recurring_order: cart.context.is_recurring_order }); // if email or customer have changed, update Culqi customer id if (!(oldEmail !== email || (oldCustomer === null || oldCustomer === void 0 ? void 0 : oldCustomer.id) !== (customer === null || customer === void 0 ? void 0 : customer.id))) { _context4.next = 23; break; } findOptions = { culqiClient: this.culqiClient_, customer: customer, email: email, address: shipping_address }; _context4.next = 9; return (0, _culqi2.getOrCreateCulqiCustomer)(findOptions); case 9: _yield$getOrCreateCul3 = _context4.sent; _yield$getOrCreateCul4 = (0, _slicedToArray2["default"])(_yield$getOrCreateCul3, 3); culqiCustomerId = _yield$getOrCreateCul4[0]; _ = _yield$getOrCreateCul4[1]; error = _yield$getOrCreateCul4[2]; if (!error) { _context4.next = 16; break; } throw new _medusaCoreUtils.MedusaError(_medusaCoreUtils.MedusaError.Types.UNEXPECTED_STATE, error.merchant_message); case 16: updatedSessionData.customer_id = culqiCustomerId; if (customer) { customer.metadata = _objectSpread(_objectSpread({}, customer.metadata || {}), {}, { culqi_customer_id: culqiCustomerId }); updatedSessionData.customer = customer; } /* * At this stage, the new customer does not exist yet in the database. * Subscriber will handle saving the Culqi customer id in the customer metadata. * */ // remove newly created customer (from previous payment session) if (!(oldCustomer && !oldCustomer.has_account)) { _context4.next = 23; break; } oldCulqiCustomerId = (_oldCustomer$metadata = oldCustomer.metadata) === null || _oldCustomer$metadata === void 0 ? void 0 : _oldCustomer$metadata.culqi_customer_id; if (!oldCulqiCustomerId) { _context4.next = 23; break; } _context4.next = 23; return this.culqiClient_.deleteCustomerAsync(oldCulqiCustomerId); case 23: return _context4.abrupt("return", updatedSessionData); case 24: case "end": return _context4.stop(); } }, _callee4, this); })); function updatePayment(_x6, _x7) { return _updatePayment.apply(this, arguments); } return updatePayment; }() /** * authorize payment * @summary This method is used to authorize payment using the Payment Session for an order. This is called when the cart is completed and before the order is created. * @param {PaymentSession} paymentSession - The payment session to authorize * @param {Data} context - The context of the payment * @returns {Promise} - The result of the operation */ }, { key: "authorizePayment", value: function () { var _authorizePayment = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee5(paymentSession, context) { var currency, email, antifraudDetails, sourceId, isRecurringOrder, cart, lineItems, chargeMetadata, chargeRequest, paymentSessionData, paymentSessionStatus, _yield$this$culqiClie, _yield$this$culqiClie2, charge, error; return _regenerator["default"].wrap(function _callee5$(_context5) { while (1) switch (_context5.prev = _context5.next) { case 0: currency = paymentSession.data.currency; email = paymentSession.data.email; antifraudDetails = paymentSession.data.antifraud_details; sourceId = paymentSession.data.source_id; isRecurringOrder = paymentSession.data.is_recurring_order; _context5.next = 7; return this.cartService_.retrieve(paymentSession.cart_id, { relations: ['items'] }); case 7: cart = _context5.sent; // TODO: check how to handle renewal orders or product-only changes (recurring orders) lineItems = cart.items.map(function (item) { return { id: item.variant_id, name: item.title, quantity: item.quantity, price: item.unit_price / 100 }; }); chargeMetadata = { lineItems: lineItems }; chargeRequest = { amount: paymentSession.amount, currency_code: currency.toUpperCase(), capture: this.capture_, description: "Medusa Order for cart ".concat(paymentSession.cart_id), email: email, antifraud_details: antifraudDetails, source_id: sourceId, metadata: chargeMetadata }; paymentSessionData = { captured: false, source_id: sourceId }; paymentSessionStatus = _medusa.PaymentSessionStatus.PENDING; _context5.next = 15; return this.culqiClient_.createChargeAsync(chargeRequest); case 15: _yield$this$culqiClie = _context5.sent; _yield$this$culqiClie2 = (0, _slicedToArray2["default"])(_yield$this$culqiClie, 2); charge = _yield$this$culqiClie2[0]; error = _yield$this$culqiClie2[1]; if (error) { if (isRecurringOrder) { paymentSessionData.recurring_payment_failed = true; } paymentSessionData.outcome_type = 'error'; paymentSessionStatus = _medusa.PaymentSessionStatus.ERROR; } else { paymentSessionData.charge_id = charge.id; paymentSessionData.outcome_type = charge.outcome.type; paymentSessionData.reference_code = charge.reference_code; paymentSessionData.captured = charge.capture; if (charge.outcome.type === 'venta_exitosa') { paymentSessionData.authorization_code = charge.authorization_code; paymentSessionData.authorization_result = charge.outcome.merchant_message; if (charge.capture) { paymentSessionData.capture_result = charge.outcome.merchant_message; } paymentSessionStatus = _medusa.PaymentSessionStatus.AUTHORIZED; } } if (paymentSession.data.billing_type) { paymentSessionData.billing_type = paymentSession.data.billing_type; if (paymentSessionData.billing_type === 'invoice') { paymentSessionData.invoice_owner_identifier = paymentSession.data.invoice_owner_identifier; } } return _context5.abrupt("return", { data: paymentSessionData, status: paymentSessionStatus }); case 22: case "end": return _context5.stop(); } }, _callee5, this); })); function authorizePayment(_x8, _x9) { return _authorizePayment.apply(this, arguments); } return authorizePayment; }() /** * get payment data * @summary After the payment is authorized using authorizePayment, a Payment instance will be created. The data field of the Payment instance will be set to the value returned from the getPaymentData method in the Payment Provider. * @param {PaymentSession} paymentSession - The payment session to get data for * @returns {Promise} - The result of the operation */ }, { key: "getPaymentData", value: function () { var _getPaymentData = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee6(paymentSession) { return _regenerator["default"].wrap(function _callee6$(_context6) { while (1) switch (_context6.prev = _context6.next) { case 0: return _context6.abrupt("return", { source_id: paymentSession.data.source_id, charge_id: paymentSession.data.charge_id, outcome_type: paymentSession.data.outcome_type, reference_code: paymentSession.data.reference_code, captured: paymentSession.data.capture, authorization_code: paymentSession.data.authorization_code, authorization_result: paymentSession.data.authorization_result, capture_result: paymentSession.data.capture_result }); case 1: case "end": return _context6.stop(); } }, _callee6); })); function getPaymentData(_x10) { return _getPaymentData.apply(this, arguments); } return getPaymentData; }() /** * capture payment * @summary This method is used to capture the payment amount of an order. This is typically triggered manually by the store operator from the admin. * @param {Payment} payment - The payment to capture * @returns {Promise} - The result of the operation */ }, { key: "capturePayment", value: function () { var _capturePayment = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee7(payment) { var chargeId, captured, updatedPaymentData, _yield$this$culqiClie3, _yield$this$culqiClie4, charge, error; return _regenerator["default"].wrap(function _callee7$(_context7) { while (1) switch (_context7.prev = _context7.next) { case 0: chargeId = payment.data.charge_id; captured = payment.data.captured; updatedPaymentData = _objectSpread({}, payment.data); if (captured) { _context7.next = 17; break; } _context7.next = 6; return this.culqiClient_.captureChargeAsync(chargeId); case 6: _yield$this$culqiClie3 = _context7.sent; _yield$this$culqiClie4 = (0, _slicedToArray2["default"])(_yield$this$culqiClie3, 2); charge = _yield$this$culqiClie4[0]; error = _yield$this$culqiClie4[1]; if (!error) { _context7.next = 16; break; } if (!(error.type === 'parameter_error')) { _context7.next = 13; break; } throw new _medusaCoreUtils.MedusaError(_medusaCoreUtils.MedusaError.Types.NOT_FOUND, 'Charge not found'); case 13: if (!(error.type === 'authentication_error')) { _context7.next = 15; break; } throw new _medusaCoreUtils.MedusaError(_medusaCoreUtils.MedusaError.Types.UNAUTHORIZED, 'Invalid Culqi API Key'); case 15: throw new _medusaCoreUtils.MedusaError(_medusaCoreUtils.MedusaError.Types.UNEXPECTED_STATE, "Error capturing charge: ".concat(chargeId)); case 16: if (charge.outcome.type === 'venta_exitosa') { updatedPaymentData.captured = true; updatedPaymentData.capture_result = charge.outcome.merchant_message; } case 17: return _context7.abrupt("return", updatedPaymentData); case 18: case "end": return _context7.stop(); } }, _callee7, this); })); function capturePayment(_x11) { return _capturePayment.apply(this, arguments); } return capturePayment; }() /** * refund payment * @summary This method is used to refund an order’s payment. This is typically triggered manually by the store operator from the admin. The refund amount might be the total order amount or part of it. * @param {Payment} payment - The payment to refund * @param {number} refundAmount - The amount to refund * @returns {Promise} - The result of the operation */ }, { key: "refundPayment", value: function () { var _refundPayment = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee8(payment, refundAmount) { var chargeId, createRefundRequest, _yield$this$culqiClie5, _yield$this$culqiClie6, _, error; return _regenerator["default"].wrap(function _callee8$(_context8) { while (1) switch (_context8.prev = _context8.next) { case 0: chargeId = payment.data.charge_id; createRefundRequest = { amount: refundAmount, charge_id: chargeId, reason: _culqi.RefundReason.REQUESTED_BY_CUSTOMER }; _context8.next = 4; return this.culqiClient_.createRefundAsync(createRefundRequest); case 4: _yield$this$culqiClie5 = _context8.sent; _yield$this$culqiClie6 = (0, _slicedToArray2["default"])(_yield$this$culqiClie5, 2); _ = _yield$this$culqiClie6[0]; error = _yield$this$culqiClie6[1]; if (!error) { _context8.next = 17; break; } if (!(error.type === 'parameter_error')) { _context8.next = 14; break; } if (!(error.param === 'charge_id')) { _context8.next = 12; break; } throw new _medusaCoreUtils.MedusaError(_medusaCoreUtils.MedusaError.Types.NOT_FOUND, 'Charge not found'); case 12: if (!(error.param === 'amount')) { _context8.next = 14; break; } throw new _medusaCoreUtils.MedusaError(_medusaCoreUtils.MedusaError.Types.INVALID_DATA, 'Amount cannot be greater than the remaining amount'); case 14: if (!(error.type === 'authentication_error')) { _context8.next = 16; break; } throw new _medusaCoreUtils.MedusaError(_medusaCoreUtils.MedusaError.Types.UNAUTHORIZED, 'Invalid Culqi API Key'); case 16: throw new _medusaCoreUtils.MedusaError(_medusaCoreUtils.MedusaError.Types.UNEXPECTED_STATE, "Error refunding charge: ".concat(chargeId)); case 17: return _context8.abrupt("return", _objectSpread({}, payment.data)); case 18: case "end": return _context8.stop(); } }, _callee8, this); })); function refundPayment(_x12, _x13) { return _refundPayment.apply(this, arguments); } return refundPayment; }() /** * cancel payment * @summary This method is used to cancel an order’s payment. This method is typically triggered by one of the following situations: * * 1. Before an order is placed and after the payment is authorized, an inventory check is done on products to ensure that products are still available for purchase. If the inventory check fails for any of the products, the payment is canceled. * 2. If the store operator cancels the order from the admin. * @param {Payment} payment - The payment to cancel * @returns {Promise} - The result of the operation */ }, { key: "cancelPayment", value: function () { var _cancelPayment = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee9(payment) { return _regenerator["default"].wrap(function _callee9$(_context9) { while (1) switch (_context9.prev = _context9.next) { case 0: return _context9.abrupt("return", payment.data); case 1: case "end": return _context9.stop(); } }, _callee9); })); function cancelPayment(_x14) { return _cancelPayment.apply(this, arguments); } return cancelPayment; }() /** * retrieve payment * @summary This method is used to provide a uniform way of retrieving the payment information from the third-party provider. * @param {PaymentData} paymentData - The payment data to retrieve * @returns {Promise} - The result of the operation */ }, { key: "retrievePayment", value: function () { var _retrievePayment = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee10(paymentData) { var chargeId, _yield$this$culqiClie7, _yield$this$culqiClie8, charge, error; return _regenerator["default"].wrap(function _callee10$(_context10) { while (1) switch (_context10.prev = _context10.next) { case 0: chargeId = paymentData.charge_id; _context10.next = 3; return this.culqiClient_.getChargeAsync(chargeId); case 3: _yield$this$culqiClie7 = _context10.sent; _yield$this$culqiClie8 = (0, _slicedToArray2["default"])(_yield$this$culqiClie7, 2); charge = _yield$this$culqiClie8[0]; error = _yield$this$culqiClie8[1]; if (!error) { _context10.next = 13; break; } if (!(error.type === 'parameter_error')) { _context10.next = 10; break; } throw new _medusaCoreUtils.MedusaError(_medusaCoreUtils.MedusaError.Types.NOT_FOUND, 'Charge not found'); case 10: if (!(error.type === 'authentication_error')) { _context10.next = 12; break; } throw new _medusaCoreUtils.MedusaError(_medusaCoreUtils.MedusaError.Types.UNAUTHORIZED, 'Invalid Culqi API Key'); case 12: throw new _medusaCoreUtils.MedusaError(_medusaCoreUtils.MedusaError.Types.UNEXPECTED_STATE, "Error retrieving charge: ".concat(chargeId)); case 13: return _context10.abrupt("return", charge); case 14: case "end": return _context10.stop(); } }, _callee10, this); })); function retrievePayment(_x15) { return _retrievePayment.apply(this, arguments); } return retrievePayment; }() /** * get status * @summary This method is used to get the status of a Payment or a Payment Session. * This method returns a string that represents the status. The status must be one of the following values: * * - authorized: The payment was successfully authorized. * - pending: The payment is still pending. This is the default status of a Payment Session. * - requires_more: The payment requires more actions from the customer. For example, if the customer must complete a 3DS check before the payment is authorized. * - error: If an error occurred with the payment. * - canceled: If the payment was canceled. * @param {Data} data - The data to get the status for * @returns {Promise} - The result of the operation */ }, { key: "getStatus", value: function () { var _getStatus = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee11(data) { var outcomeType; return _regenerator["default"].wrap(function _callee11$(_context11) { while (1) switch (_context11.prev = _context11.next) { case 0: outcomeType = data.outcome_type; if (!(outcomeType === 'error')) { _context11.next = 3; break; } return _context11.abrupt("return", _medusa.PaymentSessionStatus.ERROR); case 3: if (!(outcomeType === 'venta_exitosa')) { _context11.next = 5; break; } return _context11.abrupt("return", _medusa.PaymentSessionStatus.AUTHORIZED); case 5: return _context11.abrupt("return", _medusa.PaymentSessionStatus.PENDING); case 6: case "end": return _context11.stop(); } }, _callee11); })); function getStatus(_x16) { return _getStatus.apply(this, arguments); } return getStatus; }() /** * delete payment * @summary This method is used to perform any actions necessary before a Payment Session is deleted. The Payment Session is deleted in one of the following cases: * * 1. When a request is sent to delete the Payment Session. * 2. When the Payment Session is refreshed. The Payment Session is deleted so that a newer one is initialized instead. * 3. When the Payment Provider is no longer available. This generally happens when the store operator removes it from the available Payment Provider in the admin. * 4. When the region of the store is changed based on the cart information and the Payment Provider is not available in the new region. * @param {PaymentSession} paymentSession - The payment session to delete * @returns {Promise} - The result of the operation */ }, { key: "deletePayment", value: function () { var _deletePayment = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee12(paymentSession) { return _regenerator["default"].wrap(function _callee12$(_context12) { while (1) switch (_context12.prev = _context12.next) { case 0: case "end": return _context12.stop(); } }, _callee12); })); function deletePayment(_x17) { return _deletePayment.apply(this, arguments); } return deletePayment; }() }]); return CulqiCardPaymentService; }(_medusa.AbstractPaymentService); (0, _defineProperty2["default"])(CulqiCardPaymentService, "identifier", 'culqi_card'); var _default = CulqiCardPaymentService; exports["default"] = _default;