UNPKG

@malga-checkout/core

Version:
89 lines (88 loc) 2.92 kB
import { v4 as uuid } from 'uuid'; import settings from '../../stores/settings'; import payment from '../../stores/payment'; import { handleSubmitValidation } from '../../stores/credit'; import { Card } from '../../providers/card'; import { Charges } from '../../services/charges'; import { Customers } from '../../services/customers'; import { CustomerCards } from '../../services/customer-cards'; import { t } from '@malga-checkout/i18n'; export class MalgaPaymentsCreditService { constructor({ onPaymentSuccess, onPaymentFailed, onShowDialog, data, }) { this.charge = new Charges({ provider: new Card({ card: data }) }); this.customer = new Customers(); this.customerCards = new CustomerCards(); this.data = data; this.onPaymentSuccess = onPaymentSuccess; this.onPaymentFailed = onPaymentFailed; this.onShowDialog = onShowDialog; } handlePaymentSuccess(data) { if (settings.dialogConfig.show) { this.onShowDialog({ mode: 'success', amount: data.amount, open: true, }); } this.onPaymentSuccess(data); } handlePaymentFailed(error) { if (settings.automaticallyGeneratedIdempotencyKey) { settings.idempotencyKey = uuid(); } if (settings.dialogConfig.show) { this.onShowDialog({ open: true, mode: 'error', errorMessage: t('dialogs.card.errorMessage', settings.locale), }); } this.onPaymentFailed(error); } async handleCustomerId() { if (!settings.transactionConfig.customer && !settings.transactionConfig.customerId) { return null; } if (settings.transactionConfig.customerId) { return settings.transactionConfig.customerId; } return this.customer.create(); } async pay() { try { if (payment.selectedPaymentMethod === 'credit') { const formIsValid = await handleSubmitValidation(); if (!formIsValid) return; } if (payment.isSelectedSavedCard && payment.cvv.trim().length < 3 && (!payment.installments || payment.installments === 'none')) { return; } const customerId = await this.handleCustomerId(); const checkoutResponse = await this.charge.create(customerId); if (checkoutResponse.hasError) { this.handlePaymentFailed({ type: checkoutResponse.data.status, message: 'Your transaction cannot be completed', errorStack: checkoutResponse.data, }); return; } if (this.data['saveCard']) { await this.customerCards.create(checkoutResponse.data.paymentSource.cardId, customerId); } this.handlePaymentSuccess(checkoutResponse.data); } catch (error) { this.handlePaymentFailed({ type: error.response.status, message: 'Your transaction cannot be completed', errorStack: error.response.data, }); } } }