// CONFIGURAÇÕES DA PAGHIPER const API_KEY = "SEU_APIKEY"; // Começa com apk_... /** * Criamos no menu da planilha atalho para acionar o script */ function onOpen() { try { const ui = SpreadsheetApp.getUi(); ui.createMenu('PagHiper API') .addItem('Gerar Pix/Boleto da Lista', 'processarPagamentos') .addToUi(); } catch (e) { console.log("Não foi possível carregar a UI: " + e.message); } } /** * Função principal que lê a planilha e chama a API */ function processarPagamentos() { const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); const data = sheet.getDataRange().getValues(); // Pula a primeira linha (cabeçalho) for (let i = 1; i < data.length; i++) { // capturamos os dados que usaremos para emissao let [nome, email, cpfCnpj, item, valor, diasVencimento,tipoEmissao, idTransacao, link] = data[i]; // Se já tiver id da transacao ou link pulamos para nao duplicar a emissnao if (link || idTransacao) continue; // Valores obrigatorios que precisamos para emitir if (!nome || !valor || !cpfCnpj || !item) continue; // Tratamento para conveter o valor de reais para centavos // Garante que o valor seja tratado como texto para a substituição, // depois troca a vírgula por ponto e converte para número decimal. let valorLimpo = valor.toString().replace(",", "."); let valorNumerico = parseFloat(valorLimpo); let valorCentavos = Math.round(valorNumerico * 100); let url = ''; let payload = { "apiKey": API_KEY, "order_id": "PEDIDO_" + new Date().getTime() + i, // ID gerado automaticamente "payer_email": email, "payer_name": nome, "payer_cpf_cnpj": cpfCnpj.toString().replace(/\D/g, ''), // remove pontos/traços "days_due_date": diasVencimento || 1, "type_bank_slip": "boletoA4", "items": [ { "description": item, "quantity": 1, "item_id": "1", "price_cents": valorCentavos } ] }; try { // definimos qual meio de pagamento vamos usar if (tipoEmissao === "pix") { url = "https://pix.paghiper.com/invoice/create/"; } else if (tipoEmissao === "boleto") { url = "https://api.paghiper.com/transaction/create/"; } else { sheet.getRange(i + 1, 8).setValue("Erro: Tipo inválido (use boleto ou pix)"); continue; } let options = { "method": "post", "contentType": "application/json", "payload": JSON.stringify(payload), "muteHttpExceptions": true }; let response = UrlFetchApp.fetch(url, options); let json = JSON.parse(response.getContentText()); trataRetorno(sheet,json,tipoEmissao,i); } catch (e) { // se algo ocorrer de errado pegamos todo o retorno que api da paghiper retornou sheet.getRange(i + 1, 9).setValue(response); } } SpreadsheetApp.getUi().alert("Sucesso nas emissoes"); } // tratamos o retorno que api nos deu function trataRetorno(sheet,json, tipoEmissao,i){ if(tipoEmissao === 'pix'){ if (json.pix_create_request && json.pix_create_request.result === "success") { // Preenche a planilha com o retorno let resData = json.pix_create_request; sheet.getRange(i + 1, 8).setValue(resData.transaction_id); // Link do boleto (para Pix, o campo pode mudar na resposta conforme docs) let linkPagamento = resData.pix_code.pix_url ? resData.pix_code.pix_url : "Gerado"; sheet.getRange(i + 1, 9).setValue(linkPagamento); } else { sheet.getRange(i + 1, 9).setValue("Erro: " + json.pix_create_request.response_message); } }else{ if (json.create_request && json.create_request.result === "success") { // Preenche a planilha com o retorno let resData = json.create_request; sheet.getRange(i + 1, 8).setValue(resData.transaction_id); // Link do boleto (para Pix, o campo pode mudar na resposta conforme docs) let linkPagamento = resData.bank_slip.url_slip ? resData.bank_slip.url_slip : "Gerado"; sheet.getRange(i + 1, 9).setValue(linkPagamento); } else { sheet.getRange(i + 1, 9).setValue("Erro: " + json.create_request.response_message); } } }