|
| 1 | +import type { |
| 2 | + AppModuleBody, |
| 3 | + CreateTransactionResponse, |
| 4 | +} from '@cloudcommerce/types'; |
| 5 | +import type { AxiosError } from 'axios'; |
| 6 | +import config, { logger } from '@cloudcommerce/firebase/lib/config'; |
| 7 | +import { |
| 8 | + fullName as getFullname, |
| 9 | + phone as getPhone, |
| 10 | + price as getPrice, |
| 11 | +} from '@ecomplus/utils'; |
| 12 | +import { getYapayAxios } from './util/yapay-api'; |
| 13 | + |
| 14 | +export default async (modBody: AppModuleBody<'create_transaction'>) => { |
| 15 | + const { |
| 16 | + application, |
| 17 | + params, |
| 18 | + } = modBody; |
| 19 | + const appData = { |
| 20 | + ...application.data, |
| 21 | + ...application.hidden_data, |
| 22 | + }; |
| 23 | + if (appData.yapay_api_token) { |
| 24 | + process.env.YAPAY_API_TOKEN = appData.yapay_api_token; |
| 25 | + } |
| 26 | + const { YAPAY_API_TOKEN } = process.env; |
| 27 | + if (!YAPAY_API_TOKEN) { |
| 28 | + logger.warn('Checkout missing Yapay API Token'); |
| 29 | + return { |
| 30 | + error: 'NO_YAPAY_TOKEN', |
| 31 | + message: 'Token da conta não configurado (lojista deve configurar o aplicativo)', |
| 32 | + }; |
| 33 | + } |
| 34 | + |
| 35 | + const locationId = config.get().httpsFunctionOptions.region; |
| 36 | + const webhookUri = `https://${locationId}-${process.env.GCLOUD_PROJECT}.cloudfunctions.net` |
| 37 | + + '/yapay-webhook'; |
| 38 | + |
| 39 | + const { |
| 40 | + order_id: orderId, |
| 41 | + order_number: orderNumber, |
| 42 | + payment_method: paymentMethod, |
| 43 | + amount, |
| 44 | + buyer, |
| 45 | + items, |
| 46 | + billing_address: billingAddr, |
| 47 | + to: shippingAddr, |
| 48 | + } = params; |
| 49 | + const customerAddr = billingAddr || shippingAddr; |
| 50 | + const yapayAxios = await getYapayAxios(); |
| 51 | + const transaction: CreateTransactionResponse['transaction'] = { |
| 52 | + amount: amount.total, |
| 53 | + status: { |
| 54 | + current: 'pending', |
| 55 | + }, |
| 56 | + }; |
| 57 | + |
| 58 | + if (paymentMethod.code !== 'account_deposit') { |
| 59 | + return { |
| 60 | + error: 'PAYMENT_METHOD_NOT_SUPPORTED', |
| 61 | + message: 'Apenas Pix é suportado no momento', |
| 62 | + }; |
| 63 | + } |
| 64 | + |
| 65 | + try { |
| 66 | + const phone = getPhone(buyer); |
| 67 | + const phoneContacts: Array<Record<string, any>> = []; |
| 68 | + if (phone) { |
| 69 | + const phoneNumber = phone.replace(/\D/g, ''); |
| 70 | + if (phoneNumber.length === 11) { |
| 71 | + phoneContacts.push({ |
| 72 | + type_contact: 'M', |
| 73 | + number_contact: phoneNumber, |
| 74 | + }); |
| 75 | + } else if (phoneNumber.length === 10) { |
| 76 | + phoneContacts.push({ |
| 77 | + type_contact: 'H', |
| 78 | + number_contact: phoneNumber, |
| 79 | + }); |
| 80 | + } |
| 81 | + } |
| 82 | + |
| 83 | + const yapayTransaction = { |
| 84 | + customer: { |
| 85 | + contacts: phoneContacts.length > 0 ? phoneContacts : undefined, |
| 86 | + addresses: customerAddr ? [{ |
| 87 | + type_address: 'B', |
| 88 | + postal_code: customerAddr.zip, |
| 89 | + street: customerAddr.street, |
| 90 | + number: customerAddr.number?.toString() || 'S/N', |
| 91 | + completion: customerAddr.complement, |
| 92 | + neighborhood: customerAddr.borough, |
| 93 | + city: customerAddr.city, |
| 94 | + state: customerAddr.province_code, |
| 95 | + }] : undefined, |
| 96 | + name: buyer.fullname || getFullname(buyer) || buyer.email, |
| 97 | + birth_date: buyer.birth_date?.day && buyer.birth_date?.month && buyer.birth_date?.year |
| 98 | + ? `${buyer.birth_date.day.toString().padStart(2, '0')}/` |
| 99 | + + `${buyer.birth_date.month.toString().padStart(2, '0')}/` |
| 100 | + + `${buyer.birth_date.year}` |
| 101 | + : undefined, |
| 102 | + [buyer.registry_type === 'p' ? 'cpf' : 'cnpj']: buyer.doc_number, |
| 103 | + email: buyer.email, |
| 104 | + }, |
| 105 | + transaction_product: items.map((item, index) => ({ |
| 106 | + description: item.name || item.product_id, |
| 107 | + quantity: item.quantity.toString(), |
| 108 | + price_unit: getPrice(item)?.toFixed(2) || '0.00', |
| 109 | + code: (index + 1).toString(), |
| 110 | + sku_code: item.sku || item.product_id, |
| 111 | + extra: item.variation_id ? `Variação: ${item.variation_id}` : undefined, |
| 112 | + })), |
| 113 | + transaction: { |
| 114 | + available_payment_methods: '27', |
| 115 | + customer_ip: params.client_ip, |
| 116 | + shipping_type: 'Outro', |
| 117 | + shipping_price: amount.freight?.toFixed(2) || '0', |
| 118 | + price_discount: amount.discount?.toFixed(2) || '', |
| 119 | + url_notification: webhookUri, |
| 120 | + free: `Pedido ${orderNumber}`, |
| 121 | + }, |
| 122 | + payment: { |
| 123 | + payment_method_id: '27', |
| 124 | + }, |
| 125 | + }; |
| 126 | + |
| 127 | + const { data: yapayResponse } = await yapayAxios.post( |
| 128 | + '/transactions/payment', |
| 129 | + yapayTransaction, |
| 130 | + ); |
| 131 | + if (yapayResponse.message_response?.message !== 'success') { |
| 132 | + throw new Error( |
| 133 | + yapayResponse.error_response?.message |
| 134 | + || yapayResponse.message_response?.message |
| 135 | + || 'Erro ao criar transação', |
| 136 | + ); |
| 137 | + } |
| 138 | + const yapayData = yapayResponse.data_response.transaction; |
| 139 | + transaction.intermediator = { |
| 140 | + transaction_id: yapayData.transaction_id?.toString(), |
| 141 | + transaction_reference: yapayData.order_number?.toString(), |
| 142 | + transaction_code: yapayData.payment?.qrcode_original_path?.toString(), |
| 143 | + payment_method: { |
| 144 | + code: 'account_deposit', |
| 145 | + name: yapayData.payment?.payment_method_name, |
| 146 | + }, |
| 147 | + }; |
| 148 | + if (yapayData.payment.url_payment) { |
| 149 | + transaction.payment_link = yapayData.payment.url_payment; |
| 150 | + } |
| 151 | + if (yapayData.payment.qrcode_path) { |
| 152 | + transaction.notes = `<img src="${yapayData.payment.qrcode_path}" style="display:block;margin:0 auto">`; |
| 153 | + } |
| 154 | + if (yapayData.max_days_to_keep_waiting_payment) { |
| 155 | + transaction.account_deposit = { |
| 156 | + valid_thru: new Date(yapayData.max_days_to_keep_waiting_payment).toISOString(), |
| 157 | + }; |
| 158 | + } |
| 159 | + |
| 160 | + return { transaction }; |
| 161 | + } catch (_err) { |
| 162 | + const err = _err as AxiosError; |
| 163 | + logger.warn(`Failed payment for ${orderId}`, { |
| 164 | + orderNumber, |
| 165 | + url: err.config?.url, |
| 166 | + request: err.config?.data, |
| 167 | + response: err.response?.data, |
| 168 | + status: err.response?.status, |
| 169 | + }); |
| 170 | + logger.error(err); |
| 171 | + return { |
| 172 | + error: 'YAPAY_TRANSACTION_ERROR', |
| 173 | + message: err.message, |
| 174 | + }; |
| 175 | + } |
| 176 | +}; |
0 commit comments