UNPKG

@the-any-thing/mollie-api-client-inline-pem

Version:
1,450 lines (1,228 loc) 97.5 kB
import axios from 'axios'; import fs from 'fs'; import https from 'https'; import path from 'path'; import { get, has, cloneDeep } from 'lodash'; import { parse } from 'url'; import querystring from 'qs'; function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread2(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } var version = "3.2.0-2"; var commonHelpers = { /** * Converts this object to a plain one. */ toPlainObject: function toPlainObject() { // Previously, we used Lodash' toPlainObject here. However, back then we used classes for our models instead of // interfaces. This should have the same effect on the new object as _.toPlainObject had on the old ones: returning // a plain object with no prototype. return Object.assign({}, this); } }; /** * OrderLine Response object. */ /* eslint-disable @typescript-eslint/camelcase */ let OrderLineType; /* eslint-enable @typescript-eslint/camelcase */ (function (OrderLineType) { OrderLineType["physical"] = "physical"; OrderLineType["discount"] = "discount"; OrderLineType["digital"] = "digital"; OrderLineType["shipping_fee"] = "shipping_fee"; OrderLineType["store_credit"] = "store_credit"; OrderLineType["gift_card"] = "gift_card"; OrderLineType["surcharge"] = "surcharge"; })(OrderLineType || (OrderLineType = {})); function injectPrototypes(input) { return Object.assign(Object.create(commonHelpers), input); } /** * The `Refund` model * * {@link IRefund} */ /** * Refund statuses * * @enum queued - The refund will be processed once you have enough balance. You can still cancel this refund. * @enum pending - The refund will be processed soon (usually the next business day). You can still cancel this refund. * @enum processing - The refund is being processed. Cancellation is no longer possible. * @enum refunded - The refund has been paid out to your customer. * @enum failed - The refund has failed during processing. */ let RefundStatus; (function (RefundStatus) { RefundStatus["queued"] = "queued"; RefundStatus["pending"] = "pending"; RefundStatus["processing"] = "processing"; RefundStatus["refunded"] = "refunded"; RefundStatus["failed"] = "failed"; })(RefundStatus || (RefundStatus = {})); let RefundEmbed; /** * Payment Refund _links object * * @param payment - The API resource URL of the payment the refund belongs to. * @param settlement - The API resource URL of the settlement this payment has been settled with. Not present if not yet settled. * @param order - The API resource URL of the order the refund belongs to. Not present if the refund does not belong to an order. */ (function (RefundEmbed) { RefundEmbed["payment"] = "payment"; })(RefundEmbed || (RefundEmbed = {})); var refundHelpers = _objectSpread2({}, commonHelpers, { /** * The refund is queued until there is enough balance to process te refund. * You can still cancel the refund. */ isQueued: function isQueued() { return this.status === RefundStatus.queued; }, /** * The refund will be sent to the bank on the next business day. You can still cancel the refund. */ isPending: function isPending() { return this.status === RefundStatus.pending; }, /** * The refund has been sent to the bank. The refund amount will be transferred to the consumer * account as soon as possible. */ isProcessing: function isProcessing() { return this.status === RefundStatus.processing; }, /** * The refund amount has been transferred to the consumer. */ isRefunded: function isRefunded() { return this.status === RefundStatus.refunded; }, /** * The refund has failed during processing. */ isFailed: function isFailed() { return this.status === RefundStatus.failed; } }); function injectPrototypes$1(input) { let lines; if (input.lines != undefined) { lines = input.lines.map(injectPrototypes); } return Object.assign(Object.create(refundHelpers), input, { lines }); } /* eslint-disable @typescript-eslint/camelcase */ let Locale; /* eslint-enable @typescript-eslint/camelcase */ (function (Locale) { Locale["en_US"] = "en_US"; Locale["nl_NL"] = "nl_NL"; Locale["nl_BE"] = "nl_BE"; Locale["fr_FR"] = "fr_FR"; Locale["fr_BE"] = "fr_BE"; Locale["de_DE"] = "de_DE"; Locale["de_AT"] = "de_AT"; Locale["de_CH"] = "de_CH"; Locale["es_ES"] = "es_ES"; Locale["ca_ES"] = "ca_ES"; Locale["pt_PT"] = "pt_PT"; Locale["it_IT"] = "it_IT"; Locale["nb_NO"] = "nb_NO"; Locale["sv_SE"] = "sv_SE"; Locale["fi_FI"] = "fi_FI"; Locale["da_DK"] = "da_DK"; Locale["is_IS"] = "is_IS"; Locale["hu_HU"] = "hu_HU"; Locale["pl_PL"] = "pl_PL"; Locale["lv_LV"] = "lv_LV"; Locale["lt_LT"] = "lt_LT"; })(Locale || (Locale = {})); let PaymentMethod; (function (PaymentMethod) { PaymentMethod["applepay"] = "applepay"; PaymentMethod["bancontact"] = "bancontact"; PaymentMethod["banktransfer"] = "banktransfer"; PaymentMethod["belfius"] = "belfius"; PaymentMethod["creditcard"] = "creditcard"; PaymentMethod["directdebit"] = "directdebit"; PaymentMethod["eps"] = "eps"; PaymentMethod["giftcard"] = "giftcard"; PaymentMethod["giropay"] = "giropay"; PaymentMethod["ideal"] = "ideal"; PaymentMethod["inghomepay"] = "inghomepay"; PaymentMethod["kbc"] = "kbc"; PaymentMethod["klarnapaylater"] = "klarnapaylater"; PaymentMethod["klarnasliceit"] = "klarnasliceit"; PaymentMethod["paypal"] = "paypal"; PaymentMethod["paysafecard"] = "paysafecard"; PaymentMethod["przelewy24"] = "przelewy24"; PaymentMethod["sofort"] = "sofort"; })(PaymentMethod || (PaymentMethod = {})); let HistoricPaymentMethod; (function (HistoricPaymentMethod) { HistoricPaymentMethod["bitcoin"] = "bitcoin"; })(HistoricPaymentMethod || (HistoricPaymentMethod = {})); let ApiMode; (function (ApiMode) { ApiMode["test"] = "test"; ApiMode["live"] = "live"; })(ApiMode || (ApiMode = {})); let SequenceType; (function (SequenceType) { SequenceType["oneoff"] = "oneoff"; SequenceType["first"] = "first"; SequenceType["recurring"] = "recurring"; })(SequenceType || (SequenceType = {})); /** * Payment Response Object. * * @param resource - Indicates the response contains a payment object. * Will always contain `payment` for this endpoint. * @param id - The identifier uniquely referring to this payment. * Mollie assigns this identifier at payment creation time. * For example `tr_7UhSN1zuXS`. Its ID will always be used * by Mollie to refer to a certain payment. * @param mode - The mode used to create this payment. Mode determines * whether a payment is real (live mode) or a test payment. * @param createdAt - The payment’s date and time of creation, in ISO * 8601 format. * @param status - The payment’s status. Please refer to the documentation * regarding statuses for more info about which statuses * occur at what point. * @param isCancelable - Whether or not the payment can be canceled. * @param authorizedAt - The date and time the payment became authorized, * in ISO 8601 format. This parameter is omitted if * the payment is not authorized (yet). * @param paidAt - The date and time the payment became paid, in ISO 8601 * format. This parameter is omitted if the payment is not * completed (yet). * @param canceledAt - The date and time the payment was canceled, in * ISO 8601 format. This parameter is omitted if the * payment is not canceled (yet). * @param expiresAt - The date and time the payment will expire, in * ISO 8601 format. * @param expiredAt - The date and time the payment was expired, in * ISO 8601 format. This parameter is omitted if the * payment did not expire (yet). * @param failedAt - The date and time the payment failed, in ISO 8601 format. * This parameter is omitted if the payment did not fail (yet). * @param amount - The amount of the payment, e.g. `{"currency":"EUR", "value":"100.00"}` * for a €100.00 payment. * @param amountRefunded - The total amount that is already refunded. Only * available when refunds are available for this payment. * For some payment methods, this amount may be higher than * the payment amount, for example to allow reimbursement of * the costs for a return shipment to the customer. * @param amountRemaining - The remaining amount that can be refunded. Only available * when refunds are available for this payment. * @param amountCaptured - The total amount that is already captured for this payment. * Only available when this payment supports captures. * @param description - A short description of the payment. The description is visible * in the Dashboard and will be shown on the customer’s bank or card * statement when possible. * @param redirectUrl - The URL your customer will be redirected to after completing or * canceling the payment process. (The URL will be `null` for * recurring payments.)` * @param webhookUrl - The URL Mollie will call as soon an important status change * takes place. * @param method - The payment method used for this payment, either forced on creation * by specifying the method parameter, or chosen by the customer on our * payment method selection screen. If the payment is only partially paid * with a gift card, the method remains `giftcard`. * @param metadata - The optional metadata you provided upon payment creation. Metadata * can for example be used to link an order to a payment. * @param locale - The customer’s locale, either forced on creation by specifying the locale * parameter, or detected by us during checkout. Will be a full locale, for * example `nl_NL`. * @param countryCode - This optional field contains your customer’s ISO 3166-1 alpha-2 * country code, detected by us during checkout. For example: `BE`. * This field is omitted if the country code was not detected. * @param profileId - The identifier referring to the profile this payment was created on. * For example, `pfl_QkEhN94Ba`. * @param settlementAmount - This optional field will contain the amount that will be settled * to your account, converted to the currency your account is settled * in. It follows the same syntax as the amount property. Any amounts * not settled by Mollie will not be reflected in this amount, * e.g. PayPal or gift cards. * @param settlementId - The identifier referring to the settlement this payment was settled with. * For example, `stl_BkEjN2eBb`. * @param customerId - If a customer was specified upon payment creation, the customer’s token * will be available here as well. For example, `cst_XPn78q9CfT`. * @param sequenceType - Indicates which type of payment this is in a recurring sequence. Set to * first for first payments that allow the customer to agree to automatic * recurring charges taking place on their account in the future. * Set to recurring for payments where the customer’s card is charged * automatically. Set to `oneoff` by default, which indicates the payment * is a regular non-recurring payment. * @param mandateId - If the payment is a first or recurring payment, this field will hold the * ID of the mandate. * @param subscriptionId - When implementing the Subscriptions API, any recurring charges * resulting from the subscription will hold the ID of the subscription * that triggered the payment. * @param orderId - If the payment was created for an order, the ID of that order will * be part of the response. * @param applicationFee - The application fee, if the payment was created with one. * @param _links - An object with several URL objects relevant to the payment. Every URL * object will contain an `href` and a `type` field. * */ /** * Payment _links object * * @param checkout - The URL your customer should visit to make the payment. * This is where you should redirect the consumer to. * Recurring payments don’t have a checkout URL. * @param changePaymentState - Recurring payments do not have a checkout URL, * because these payments are executed without any * user interaction. This link is only included for * test mode recurring payments, and allows you to * set the final payment state for such payments. * @param refunds - The API resource URL of the refunds that belong to this payment. * @param chargebacks - The API resource URL of the chargebacks that belong to * this payment. * @param captures - The API resource URL of the captures that belong to this payment. * @param settlement - The API resource URL of the settlement this payment has been * settled with. Not present if not yet settled. * @param documentation - The URL to the payment retrieval endpoint documentation. * @param mandate - The API resource URL of the mandate linked to this payment. * Not present if a one-off payment. * @param subscription - The API resource URL of the subscription this payment is * part of. Not present if not a subscription payment. * @param customer - The API resource URL of the customer this payment belongs to. * Not present if not linked to a customer. * @param order - The API resource URL of the order this payment was created for. * Not present if not created for an order. * * @see https://docs.mollie.com/reference/v2/payments-api/get-payment */ /** * Bancontact details * * @param cardNumber - Only available if the payment is completed - The last four digits of the card number. * @param cardFingerprint - Only available if the payment is completed - Unique alphanumeric representation of card, * usable for identifying returning customers. * @param qrCode - Only available if requested during payment creation - The QR code that can be scanned by the mobile * Bancontact application. This enables the desktop to mobile feature. * @param consumerName - Only available if the payment is completed – The consumer’s name. * @param consumerAccount - Only available if the payment is completed – The consumer’s bank account. This may be an * IBAN, or it may be a domestic account number. * @param consumerBic - Only available if the payment is completed – The consumer’s bank’s BIC / SWIFT code. */ /** * For bank transfer payments, the `_links` object * will contain some additional URL objects relevant to the payment. * * @param status - A link to a hosted payment page where your customer * can check the status of their payment. * @param payOnline - A link to a hosted payment page where your customer * can finish the payment using an alternative payment * method also activated on your website profile. */ /** * Bank transfer details * * @param bankName - The name of the bank the consumer should wire the amount to. * @param bankAccount - The IBAN the consumer should wire the amount to. * @param bankBic - The BIC of the bank the consumer should wire the amount to. * @param transferReference - The reference the consumer should use when wiring the amount. Note you should not apply * any formatting here; show it to the consumer as-is. * @param consumerName - Only available if the payment has been completed – The consumer’s name. * @param consumerAccount - Only available if the payment has been completed – The consumer’s bank account. This may be * an IBAN, or it may be a domestic account number. * @param consumerBic - Only available if the payment has been completed – The consumer’s bank’s BIC / SWIFT code. * @param billingEmail - Only available if filled out in the API or by the consumer – The email address which the * consumer asked the payment instructions to be sent to. * @param _links - See {@link IBankTransferLinks} */ /** * Belfius Payment Button details * * @param consumerName - Only available one banking day after the payment has been completed – The consumer’s name. * @param consumerAccount - Only available one banking day after the payment has been completed – The consumer’s IBAN. * @param consumerBic - Only available one banking day after the payment has been completed – `GKCCBEBB`. */ /** * Bitcoin details * * @param bitcoinAddress - Only available if the payment has been completed * – The bitcoin address the bitcoins were * transferred to. * @param bitcoinAmount - The amount transferred in XBT. * @param bitcoinUri - A URI that is understood by Bitcoin wallet clients * and will cause such clients to prepare the transaction. * Follows the * {@link https://github.com/bitcoin/bips/blob/master/bip-0021.mediawiki BIP 21 URI scheme}. * @param qrCode - Only available if requested during payment creation * - The QR code that can be scanned by Bitcoin wallet * clients and will cause such clients to prepare the * transaction. */ /** * Credit Card Details * * @param cardHolder - Only available if the payment has been completed * - The card holder’s name. * @param cardNumber - Only available if the payment has been completed * - The last four digits of the card number. * @param cardFingerprint - Only available if the payment has been completed * - Unique alphanumeric representation of card, * usable for identifying returning customers. * @param cardAudience - Only available if the payment has been completed * and if the data is available * - The card’s target audience. * @param cardLabel - Only available if the payment has been completed * - The card’s label. Note that not all labels can be * processed through Mollie. * @param cardCountryCode - Only available if the payment has been completed * - The ISO 3166-1 alpha-2 country code of the country * the card was issued in. For example: `BE`. * @param cardSecurity - Only available if the payment has been completed * – The type of security used during payment processing. * @param feeRegion - Only available if the payment has been completed * – The fee region for the payment: `intra-eu` for consumer * cards from the EU, and other for all other cards. * @param failureReason - Only available for failed payments. Contains a * failure reason code. */ /** * Gift Card Details * * @param voucherNumber - The voucher number, with the last four digits masked. When multiple gift cards are used, this * is the first voucher number. Example: `606436353088147****`. * @param giftcards - A list of details of all giftcards that are used for this payment. Each object will contain the * following properties. * @param remainderAmount - Only available if another payment method was used to pay the remainder amount – The amount * that was paid with another payment method for the remainder amount. * @param remainderMethod - Only available if another payment method was used to pay the remainder amount – The payment * method that was used to pay the remainder amount. */ /** * iDEAL details * * @param consumerName - Only available if the payment has been completed * – The consumer’s name. * @param consumerAccount - Only available if the payment has been completed * – The consumer’s IBAN. * @param consumerBic - Only available if the payment has been completed * – The consumer’s bank’s BIC. */ /** * ING Home'Pay details * * @param consumerName - Only available one banking day after the payment has been completed * – The consumer’s name. * @param consumerAccount - Only available one banking day after the payment has been completed * – The consumer’s IBAN. * @param consumerBic - Only available one banking day after the payment has been completed * – `BBRUBEBB`. */ /** * KBC/CBC Payment Button details * * @param consumerName - Only available one banking day after the payment has been completed – The consumer’s name. * @param consumerAccount - Only available one banking day after the payment has been completed – The consumer’s IBAN. * @param consumerBic - Only available one banking day after the payment has been completed – The consumer’s bank’s BIC. */ /** * For some industries, additional purchase information can be sent to Klarna to increase the authorization rate. You * can submit your extra data in this field if you have agreed upon this with Klarna. This field should be an object * containing any of the allowed keys and sub objects described at the * [Klarna Developer Documentation](https://developers.klarna.com/api/#payments-api__create-a-new-credit-sessionattachment__body) * under `attachment.body`. * * Note that Klarna needs to do some work to make sure this information is incorporated in their risk decisions, so * there is no point in sending it without making agreements with Klarna first. * * Please reach out to your account manager at Mollie to enable this feature with Klarna. */ /** * PayPal details * * @param consumerName - Only available if the payment has been completed – The consumer’s first and last name. * @param consumerAccount - Only available if the payment has been completed – The consumer’s email address. * @param paypalReference - PayPal’s reference for the transaction, for instance `9AL35361CF606152E`. */ /** * paysafecard details * * @param customerReference - The consumer identification supplied when the payment was created. */ /** * SEPA Direct Debit details * * @param transferReference - Transfer reference used by Mollie to identify this payment. * @param creditorIdentifier - The creditor identifier indicates who is authorized to execute the payment. In this case, * it is a reference to Mollie. * @param consumerName - The consumer’s name. * @param consumerAccount - The consumer’s IBAN. * @param consumerBic - The consumer’s bank’s BIC. * @param dueDate - Estimated date the payment is debited from the consumer’s bank account, in `YYYY-MM-DD` format. * @param signatureDate - Only available if the payment has been verified – Date the payment has been signed by the * consumer, in `YYYY-MM-DD` format. * @param bankReasonCode - Only available if the payment has failed – The official reason why this payment has failed. * A detailed description of each reason is available on the website of the European Payments Council. * @param bankReason - Only available if the payment has failed – A textual desciption of the failure reason. * @param endToEndIdentifier - Only available for batch transactions – The original end-to-end identifier that you’ve * specified in your batch. * @param mandateReference - Only available for batch transactions – The original mandate reference that you’ve * specified in your batch. * @param batchReference - Only available for batch transactions – The original batch reference that you’ve * specified in your batch. * @param fileReference - Only available for batch transactions – The original file reference that you’ve specified * in your batch. */ /** * Sofort Banking details * * @param consumerName - Only available if the payment has been completed – The consumer’s name. * @param consumerAccount - Only available if the payment has been completed – The consumer’s IBAN. * @param consumerBic - Only available if the payment has been completed – The consumer’s bank’s BIC. */ /** * QR Code * * @param height - Height of the image in pixels. * @param width - Width of the image in pixels. * @param src - The URI you can use to display the QR code. * Note that we can send both data URIs as well * as links to HTTPS images. You should support both. */ let PaymentStatus; (function (PaymentStatus) { PaymentStatus["open"] = "open"; PaymentStatus["canceled"] = "canceled"; PaymentStatus["pending"] = "pending"; PaymentStatus["authorized"] = "authorized"; PaymentStatus["expired"] = "expired"; PaymentStatus["failed"] = "failed"; PaymentStatus["paid"] = "paid"; })(PaymentStatus || (PaymentStatus = {})); let PaymentEmbed; /** * Gift Card * * @param issuer - The ID of the gift card brand that was used during the payment. * @param amount - The amount in EUR that was paid with this gift card. * @param voucherNumber - The voucher number, with the last four digits masked. Example: `606436353088147****` */ (function (PaymentEmbed) { PaymentEmbed["refunds"] = "refunds"; PaymentEmbed["chargebacks"] = "chargebacks"; })(PaymentEmbed || (PaymentEmbed = {})); var paymentHelpers = _objectSpread2({}, commonHelpers, { /** * If the payment is open */ isOpen: function isOpen() { return this.status === PaymentStatus.open; }, /** * If the payment is authorized */ isAuthorized: function isAuthorized() { return this.status === PaymentStatus.authorized; }, /** * If the payment is paid */ isPaid: function isPaid() { return this.paidAt != undefined; }, /** * If the payment is canceled */ isCanceled: function isCanceled() { return this.status == PaymentStatus.canceled; }, /** * If the payment is expired */ isExpired: function isExpired() { return this.status == PaymentStatus.expired; }, /** * If the payment is refundable * * @since 2.0.0-rc.2 */ isRefundable: function isRefundable() { return this.amountRemaining !== null; }, /** * Get the payment URL */ getPaymentUrl: function getPaymentUrl() { return get(this._links, 'checkout.href', null); }, /** * Returns whether the payment has failed and cannot be completed with a different payment method. */ isFailed: function isFailed() { return this.status == PaymentStatus.failed; }, /** * Returns whether the payment is in this temporary status that can occur when the actual payment process has been * started, but has not completed yet. */ isPending: function isPending() { return this.status == PaymentStatus.pending; }, /** * Returns whether there are refunds which belong to the payment. */ hasRefunds: function hasRefunds() { return this._links.refunds != undefined; }, /** * Returns whether there are chargebacks which belong to the payment. */ hasChargebacks: function hasChargebacks() { return this._links.chargebacks != undefined; }, /** * Returns whether `sequenceType` is set to `'first'`. If a `'first'` payment has been completed successfully, the * consumer's account may be charged automatically using recurring payments. */ hasSequenceTypeFirst: function hasSequenceTypeFirst() { return this.sequenceType == SequenceType.first; }, /** * Returns whether `sequenceType` is set to `'recurring'`. This type of payment is processed without involving the * consumer. */ hasSequenceTypeRecurring: function hasSequenceTypeRecurring() { return this.sequenceType == SequenceType.recurring; }, /** * Returns the URL your customer should visit to make the payment. This is where you should redirect the consumer to. * * Recurring payments don’t have a checkout URL. */ getCheckoutUrl: function getCheckoutUrl() { if (this._links.checkout == undefined) { return null; } return this._links.checkout.href; }, canBeRefunded: function canBeRefunded() { return this.amountRemaining != undefined; }, canBePartiallyRefunded: function canBePartiallyRefunded() { return this.amountRemaining != undefined; }, /** * Returns the total amount that is already refunded. For some payment methods, this amount may be higher than the * payment amount, for example to allow reimbursement of the costs for a return shipment to the customer. */ getAmountRefunded: function getAmountRefunded() { if (this.amountRefunded == undefined) { return { // Perhaps this zero-value should depend on the currency. If the currency is JPY (¥), for instance, the value // should probably be "0"; not "0.00". value: '0.00', currency: this.amount.currency }; } return this.amountRefunded; }, /** * Returns the remaining amount that can be refunded. */ getAmountRemaining: function getAmountRemaining() { if (this.amountRemaining == undefined) { return { // Perhaps this zero-value should depend on the currency. If the currency is JPY (¥), for instance, the value // should probably be "0"; not "0.00". value: '0.00', currency: this.amount.currency }; } return this.amountRemaining; } }); function injectPrototypes$2(input) { let _embedded; if (input._embedded != undefined) { _embedded = {}; if (input._embedded.chargebacks != undefined) { _embedded.chargebacks = input._embedded.chargebacks.map(injectPrototypes$3); } if (input._embedded.refunds != undefined) { _embedded.refunds = input._embedded.refunds.map(injectPrototypes$1); } } return Object.assign(Object.create(paymentHelpers), input, { _embedded }); } /** * Chargeback Response object. * * @param resource - Indicates the response contains a Chargeback object. * Will always contain `chargeback` for this endpoint. * @param id - The chargeback’s unique identifier, for example `chb_n9z0tp`. * @param amount - The amount charged back by the consumer. * @param settlementAmount - This optional field will contain the amount that will be deducted from your account, * converted to the currency your account is settled in. It follows the same syntax as * the `amount` property. Note that for chargebacks, the `value` key of `settlementAmount` * will be negative. Any amounts not settled by Mollie will not be reflected in this amount, * e.g. PayPal chargebacks. * @param createdAt - The date and time the chargeback was issued, in ISO 8601 format. * @param reversedAt - The date and time the chargeback was reversed if applicable, in ISO 8601 format. * @param paymentId - The unique identifier of the payment this chargeback was issued for. For example: `tr_7UhSN1zuXS`. * The full payment object can be retrieved via the `payment` URL in the `_links` object. * @param _links - An object with several URL objects relevant to the chargeback. * * @see https://docs.mollie.com/reference/v2/chargebacks-api/get-chargeback */ let ChargebackEmbed; (function (ChargebackEmbed) { ChargebackEmbed["payment"] = "payment"; })(ChargebackEmbed || (ChargebackEmbed = {})); function injectPrototypes$3(input) { let _embedded; if (input._embedded != undefined) { _embedded = {}; if (input._embedded.payments != undefined) { _embedded.payments = input._embedded.payments.map(injectPrototypes$2); } } return Object.assign(Object.create(commonHelpers), input); } class ApiError extends Error { constructor(message, title, status, field, links) { super(message); this.title = title; this.status = status; this.field = field; this.links = links; this.name = 'ApiError'; } /** * Get the error message * * @since 3.0.0 */ getMessage() { return this.message; } /** * Get the field name that contains an error * * @since 3.0.0 */ getField() { return this.field; } /** * Get the API status code * * @since 3.0.0 */ getStatusCode() { return this.status; } /** * Get the documentation URL * * @since 3.0.0 */ getDocumentationUrl() { return this.getUrl('documentation'); } /** * Get the dashboard URL * * @since 3.0.0 */ getDashboardUrl() { return this.getUrl('dashboard'); } /** * Check if the link exists * * @since 3.0.0 */ hasLink(key) { return has(this.links, key); } /*** * Retrieve a link by name * * @since 3.0.0 */ getLink(key) { return get(this.links, key); } /** * @since 3.0.0 */ getUrl(key) { return get(this.getLink(key), 'href'); } toString() { return `ApiError: ${this.message}`; } /** * Creates and returns an `ApiError` from the passed response. * * @since 3.0.0 */ static createFromResponse(response) { return new ApiError(get(response, 'data.detail', 'Received an error without a message'), get(response, 'data.title'), get(response, 'data.status'), get(response, 'data.field'), cloneDeep(get(response, 'data._links'))); } } /** * Returns an array of the passed object's own enumerable string-keyed property `[key, value]` pairs. * * If support for Node.js < 7.0.0 is ever dropped, this function can be removed in favour of `Object.entries`. */ var getEntries = (() => { if (Object.entries != undefined) { return Object.entries; } return function getEntries(input) { return Object.keys(input).map(key => [key, input[key]]); }; })(); function stringifyQuery(input) { return querystring.stringify(getEntries(input).reduce((result, [key, value]) => { if (Array.isArray(value)) { result[key] = value.join(); } /* if (Array.isArray(value) == false) */ else { result[key] = value; } return result; }, {}), { addQueryPrefix: true }); } class Resource { constructor(httpClient) { var _this = this; this.httpClient = httpClient; _defineProperty(this, "network", void 0); /* eslint-disable no-var */ this.network = { post: function () { var _ref = _asyncToGenerator(function* (url, data) { try { var response = yield httpClient.post(url, data); } catch (error) { if (error.response != undefined) { throw ApiError.createFromResponse(error.response); } throw new ApiError(error.message); } if (response.status == 204) { return true; } return _this.injectPrototypes(response.data); }); return function post(_x, _x2) { return _ref.apply(this, arguments); }; }(), get: function () { var _ref2 = _asyncToGenerator(function* (url, query = {}) { try { var response = yield httpClient.get(`${url}${stringifyQuery(query)}`); } catch (error) { if (error.response != undefined) { throw ApiError.createFromResponse(error.response); } throw new ApiError(error.message); } return _this.injectPrototypes(response.data); }); return function get(_x3) { return _ref2.apply(this, arguments); }; }(), list: function () { var _ref3 = _asyncToGenerator(function* (url, resourceName, query = {}) { try { var response = yield httpClient.get(`${url}${stringifyQuery(query)}`); } catch (error) { if (error.response != undefined) { throw ApiError.createFromResponse(error.response); } throw new ApiError(error.message); } try { var { _embedded: embedded, _links: links, count } = response.data; } catch (error) { throw new ApiError('Received unexpected response from the server'); } return Object.assign(embedded[resourceName].map(_this.injectPrototypes), { links, count }); }); return function list(_x4, _x5) { return _ref3.apply(this, arguments); }; }(), patch: function () { var _ref4 = _asyncToGenerator(function* (url, data) { try { var response = yield httpClient.patch(url, data); } catch (error) { if (error.response != undefined) { throw ApiError.createFromResponse(error.response); } throw new ApiError(error.message); } return _this.injectPrototypes(response.data); }); return function patch(_x6, _x7) { return _ref4.apply(this, arguments); }; }(), delete: function () { var _ref5 = _asyncToGenerator(function* (url, context) { try { var response = yield httpClient.delete(url, { data: context }); } catch (error) { if (error.response != undefined) { throw ApiError.createFromResponse(error.response); } throw new ApiError(error.message); } if (response.status == 204) { return true; } return _this.injectPrototypes(response.data); }); return function _delete(_x8, _x9) { return _ref5.apply(this, arguments); }; }() }; /* eslint-enable no-var */ } /** * Injects `nextPage`, `nextPageCursor`, `previousPage`, and `previousPageCursor` into the passed list. */ injectPaginationHelpers(input, list, selfParameters) { const { links } = input; let nextPage; let nextPageCursor; if (links.next != null) { const { query } = parse(links.next.href, true); nextPage = list.bind(this, _objectSpread2({}, selfParameters, {}, query)); nextPageCursor = query.from; } let previousPage; let previousPageCursor; if (links.previous != null) { const { query } = parse(links.previous.href, true); previousPage = list.bind(this, _objectSpread2({}, selfParameters, {}, query)); previousPageCursor = query.from; } return Object.assign(input, { nextPage, nextPageCursor, previousPage, previousPageCursor }); } /** * Injects prototypes ‒ where necessary ‒ into the response received from the Mollie server. */ injectPrototypes(input) { return input; } } class ParentedResource extends Resource { constructor(...args) { super(...args); _defineProperty(this, "defaultParentId", void 0); } /** * Returns the passed parent identifier, or `defaultParentId` as set by `withParent` if the former is `undefined`. */ getParentId(input) { if (input == undefined) { return this.defaultParentId; } return input; } /** * Sets the default parent identifier for future calls to the methods of this resource to the identifier of the * passed parent object. If `undefined` or `null` or an otherwise falsy value is passed, or an object with a falsy * identifier, this method is a no-op. * * @since 1.1.1 * * @deprecated 2.0.0. This method is not supported by the v2 API. */ withParent(parent) { if (parent && parent.id) { this.defaultParentId = parent.id; } return this; } } /** * Allows a promise-style method to be called callback-style. * * Behaves in one of two ways, depending on the type of the last argument: * * If called with a function as the last argument, that argument is considered to be the callback. This function * calls the passed method, forwarding the original arguments (save for the callback). A settlement of the promise * returned during that call will be forwarded to the callback. This function then returns `true`. * * If called with a last argument which is not a function, this function returns `false`. */ function renege(thisArgument, method, ...originalArguments) { const candidate = originalArguments.pop(); if (typeof candidate == 'function') { method.apply(thisArgument, originalArguments).then(result => void candidate(null, result), candidate); return true; } return false; } class ChargebacksResource extends ParentedResource { constructor(...args) { super(...args); _defineProperty(this, "injectPrototypes", injectPrototypes$3); _defineProperty(this, "all", this.list); _defineProperty(this, "page", this.list); } getResourceUrl() { return 'chargebacks'; } list(parameters = {}) { if (renege(this, this.list, ...arguments)) return; return this.network.list(this.getResourceUrl(), 'chargebacks', parameters).then(result => this.injectPaginationHelpers(result, this.list, parameters)); } } /** * Mandate Response object * * @see https://docs.mollie.com/reference/v2/mandates-api/get-mandate */ let MandateMethod; (function (MandateMethod) { MandateMethod["directdebit"] = "directdebit"; MandateMethod["creditcard"] = "creditcard"; MandateMethod["paypal"] = "paypal"; })(MandateMethod || (MandateMethod = {})); let MandateStatus; (function (MandateStatus) { MandateStatus["valid"] = "valid"; MandateStatus["invalid"] = "invalid"; MandateStatus["pending"] = "pending"; })(MandateStatus || (MandateStatus = {})); var mandateHelpers = _objectSpread2({}, commonHelpers, { /** * If the mandate is valid */ isValid: function isValid() { return this.status === MandateStatus.valid; } }); function injectPrototypes$4(input) { return Object.assign(Object.create(mandateHelpers), input); } const prefixes = new Map([['capture', 'cpt_'], ['chargeback', 'chb_'], ['customer', 'cst_'], ['mandate', 'mdt_'], ['order', 'ord_'], ['orderline', 'odl_'], ['organization', 'org_'], ['payment', 'tr_'], ['profile', 'pfl_'], ['refund', 're_'], ['shipment', 'shp_'], ['subscription', 'sub_']]); /** * Returns whether the passed identifier seems plausible (`true`); or is definitely invalid (`false`). */ function checkId(value, resource) { if (typeof value != 'string') { return false; } // Examples of permission identifiers are 'payments.read' and 'refunds.write'. This function currently relies on the // API to return an error if the identifier is unexpected, instead of returning a client-side check. if (resource == 'permission') { return true; } // eslint-disable-next-line @typescript-eslint/no-non-null-assertion return value.startsWith(prefixes.get(resource)); } class CustomersMandatesResource extends ParentedResource { constructor(...args) { super(...args); _defineProperty(this, "injectPrototypes", injectPrototypes$4); _defineProperty(this, "all", this.list); _defineProperty(this, "page", this.list); _defineProperty(this, "cancel", this.revoke); _defineProperty(this, "delete", this.revoke); } getResourceUrl(customerId) { return `customers/${customerId}/mandates`; } create(parameters) { if (renege(this, this.create, ...arguments)) return; const customerId = this.getParentId(parameters.customerId); if (!checkId(customerId, 'customer')) { throw new ApiError('The customer id is invalid'); } const data = _objectWithoutProperties(parameters, ["customerId"]); return this.network.post(this.getResourceUrl(customerId), data); } /** * Get a customer mandate by ID * * @since 1.2.0 * * @see https://docs.mollie.com/reference/v2/mandates-api/get-mandate */ get(id, parameters) { if (renege(this, this.get, ...arguments)) return; if (!checkId(id, 'mandate')) { throw new ApiError('The customers_mandate id is invalid'); } // parameters || {} is used here, because in case withParent is used, parameters could be omitted. const customerId = this.getParentId((parameters || {}).customerId); if (!checkId(customerId, 'customer')) { throw new ApiError('The customer id is invalid'); } const _ref = parameters || {}, query = _objectWithoutProperties(_ref, ["customerId"]); return this.network.get(`${this.getResourceUrl(customerId)}/${id}`, query); } /** * Get all of a customer's mandates * * @since 3.0.0 * * @see https://docs.mollie.com/reference/v2/mandates-api/list-mandates */ list(parameters) { if (renege(this, this.list, ...arguments)) return; // parameters || {} is used here, because in case withParent is used, parameters could be omitted. const customerId = this.getParentId((parameters || {}).customerId); if (!checkId(customerId, 'customer')) { throw new ApiError('The customer id is invalid'); } const _ref2 = parameters || {}, query = _objectWithoutProperties(_ref2, ["customerId"]); return this.network.list(this.getResourceUrl(customerId), 'mandates', query).then(result => this.injectPaginationHelpers(result, this.list, parameters || {})); } /** * Delete a customer subscription * * @since 2.0.0 * * @see https://docs.mollie.com/reference/v2/mandates-api/revoke-mandate */ revoke(id, parameters) { if (renege(this, this.revoke, ...arguments)) return; if (!checkId(id, 'mandate')) { throw new ApiError('The customers_mandate id is invalid'); } // parameters || {} is used here, because in case withParent is used, parameters could be omitted. const customerId = this.getParentId((parameters || {}).customerId); if (!checkId(customerId, 'customer')) { throw new ApiError('The customer is invalid'); } const _ref3 = parameters || {}, context = _objectWithoutProperties(_ref3, ["custo