Skip to content

Commit

Permalink
feat(banrisul): create app
Browse files Browse the repository at this point in the history
  • Loading branch information
wisley7l committed Aug 23, 2023
1 parent dd22452 commit 5cc2f0d
Show file tree
Hide file tree
Showing 26 changed files with 2,473 additions and 203 deletions.
Binary file added functions/assets/fonts/Code25I.ttf
Binary file not shown.
Binary file not shown.
Binary file added functions/assets/fonts/Times New Roman Bold.ttf
Binary file not shown.
Binary file not shown.
Binary file added functions/assets/fonts/Times New Roman.ttf
Binary file not shown.
Binary file added functions/assets/images/banrisul.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
207 changes: 172 additions & 35 deletions functions/ecom.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,13 +34,13 @@ const app = {
* Triggered when listing payments, must return available payment methods.
* Start editing `routes/ecom/modules/list-payments.js`
*/
// list_payments: { enabled: true },
list_payments: { enabled: true },

/**
* Triggered when order is being closed, must create payment transaction and return info.
* Start editing `routes/ecom/modules/create-transaction.js`
*/
// create_transaction: { enabled: true },
create_transaction: { enabled: true },
},

/**
Expand Down Expand Up @@ -82,7 +82,7 @@ const app = {
// 'DELETE', // Delete customers
],
orders: [
// 'GET', // List/read orders with public and private fields
'GET', // List/read orders with public and private fields
// 'POST', // Create orders
// 'PATCH', // Edit orders
// 'PUT', // Overwrite orders
Expand All @@ -106,7 +106,7 @@ const app = {
],
'orders/payments_history': [
// 'GET', // List/read order payments history events
// 'POST', // Create payments history entry with new status
'POST', // Create payments history entry with new status
// 'DELETE', // Delete payments history entry
],

Expand Down Expand Up @@ -138,37 +138,174 @@ const app = {
},

admin_settings: {
/**
* JSON schema based fields to be configured by merchant and saved to app `data` / `hidden_data`, such as:
webhook_uri: {
schema: {
type: 'string',
maxLength: 255,
format: 'uri',
title: 'Notifications URI',
description: 'Unique notifications URI available on your Custom App dashboard'
},
hide: true
},
token: {
schema: {
type: 'string',
maxLength: 50,
title: 'App token'
},
hide: true
},
opt_in: {
schema: {
type: 'boolean',
default: false,
title: 'Some config option'
},
hide: false
},
*/
client_id: {
schema: {
type: 'string',
maxLength: 255,
title: 'Client Id',
// description: ''
},
hide: true
},
client_secret: {
schema: {
type: 'string',
maxLength: 255,
title: 'Client Secret',
// description: ''
},
hide: true
},
beneficiary_code: {
schema: {
type: 'string',
maxLength: 13,
title: 'Código beneficiário',
description: 'Seu código de beneficiário no Banrisul (13 dígitos)'
},
hide: true
},
is_homologation: {
schema: {
type: 'boolean',
title: 'Ambiente de Homologação',
description: 'Habilitar ambiente para Homologação',
default: false
},
hide: false
},
days_to_expiry: {
schema:{
type: 'integer',
minimum: 1,
maximum: 999,
default: 7,
title: 'Dias corridos até o vencimento',
description: 'Representa diferença de dias entre a data da requisição e a data de vencimento'
},
hide: false
},
fees: {
schema: {
type: 'object',
required: [
'value'
],
title: 'Juros',
description: 'Juros a ser aplicado nos boletos após vencimento',
additionalProperties: false,
properties: {
type: {
type: 'string',
enum: [
'percentual',
'fixo',
'isento'
],
default: 'isento',
title: 'Tipo de juros',
description: 'Se fixo valor diário, se percentual taxa mensal'
},
value: {
type: 'number',
minimum: 0,
maximum: 99999999,
title: 'Valor do juros',
description: 'Valor percentual ou fixo a ser acrescentado, dependendo to tipo configurado'
}
}
},
hide: false
},
tax: {
schema: {
type: 'object',
required: [
'value'
],
title: 'Multa',
description: 'Multa a ser aplicada nos boletos após vencimento',
additionalProperties: false,
properties: {
disable: {
type: 'boolean',
default: true,
title: 'Desabilitar multa'
},
type: {
type: 'string',
enum: [
'percentual',
'fixa'
],
default: 'percentual',
title: 'Tipo de multa',
description: 'Multa com valor percentual ou fixo'
},
value: {
type: 'number',
minimum: 0,
maximum: 99999999,
title: 'Valor da multa',
description: 'Valor percentual ou fixo a ser acrescentado, dependendo to tipo configurado'
}
}
},
hide: false
},
discount: {
schema: {
type: 'object',
required: [
'value'
],
title: 'Desconto',
additionalProperties: false,
properties: {
disable: {
type: 'boolean',
default: false,
title: 'Desabilitar desconto'
},
apply_at: {
type: 'string',
enum: [
'total',
'subtotal',
'freight'
],
default: 'subtotal',
title: 'Aplicar desconto em',
description: 'Em qual valor o desconto deverá ser aplicado no checkout'
},
min_amount: {
type: 'integer',
minimum: 1,
maximum: 999999999,
title: 'Pedido mínimo',
description: 'Montante mínimo para aplicar o desconto'
},
type: {
type: 'string',
enum: [
'percentage',
'fixed'
],
default: 'percentage',
title: 'Tipo de desconto',
description: 'Desconto com valor percentual ou fixo'
},
value: {
type: 'number',
minimum: 0,
maximum: 99999999,
title: 'Valor do desconto',
description: 'Valor percentual ou fixo a ser descontado, dependendo to tipo configurado'
}
}
},
hide: false
}
}
}

Expand Down
54 changes: 54 additions & 0 deletions functions/lib/banrisul/auth/create-access.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
const createAxios = require('./create-axios')
const getOAuth = require('./get-token')

module.exports = function (clientId, clientSecret, storeId, firestoreColl = 'banrisul_auth') {
const self = this

let documentRef
// const hashLogin = Buffer.from(`${galaxpayId}:${galaxpayHash}`).toString('base64')

if (firestoreColl) {
documentRef = require('firebase-admin')
.firestore()
.doc(`${firestoreColl}/${storeId}`)
}

this.preparing = new Promise((resolve, reject) => {
const authenticate = (accessToken, documentRef) => {
self.axios = createAxios(accessToken)
self.documentRef = documentRef
if (documentRef) {
documentRef
.set({ accessToken }, { merge: true })
.catch(console.error)
}
resolve(self)
}

const handleAuth = () => {
console.log('> Banrisul Auth02 ', storeId)
getOAuth(clientId, clientSecret)
.then((accessToken) => {
console.log(`>> s:${storeId} token => ${accessToken}`)
authenticate(accessToken, documentRef)
})
.catch(reject)
}

if (documentRef) {
documentRef.get()
.then((documentSnapshot) => {
if (documentSnapshot.exists &&
Date.now() - documentSnapshot.updateTime.toDate().getTime() <= 59 * 60 * 1000 // access token expires in 60 minutes
) {
authenticate(documentSnapshot.get('accessToken'), documentRef)
} else {
handleAuth()
}
})
.catch(console.error)
} else {
handleAuth()
}
})
}
18 changes: 18 additions & 0 deletions functions/lib/banrisul/auth/create-axios.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
const axios = require('axios')
module.exports = (accessToken, isGetToken) => {
const isSandbox = true

const headers = {
'Content-Type': 'application/json'
}

if (accessToken) {
console.log('> token ', accessToken)
headers.Authorization = `Bearer ${accessToken}`
}

return axios.create({
baseURL: `https://api${isSandbox ? 'dev' : ''}.banrisul.com.br${isGetToken ? '' : '/cobranca/v1'}`,
headers
})
}
35 changes: 35 additions & 0 deletions functions/lib/banrisul/auth/get-token.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
const axios = require('./create-axios')
const qs = require('qs')

module.exports = (clientId, clientSecret) => new Promise((resolve, reject) => {
const banrisulAxios = axios(null, true)

const request = async (isRetry) => {
try {
const headers = {
'content-type': 'application/x-www-form-urlencoded',
Authorization: `Basic ${Buffer.from(`${clientId}:${clientSecret}`).toString('base64')}`
}

const body = {
grant_type: 'client_credentials',
scope: 'boletos'
}

const { data: { access_token: token } } = await banrisulAxios.post(
'/auth/oauth/v2/token',
qs.stringify(body),
{ headers }
)

resolve(token)
} catch (err) {
if (!isRetry && err.response && err.response.status >= 429) {
setTimeout(() => request(true), 7000)
}
reject(err)
}
}

request()
})
Loading

0 comments on commit 5cc2f0d

Please sign in to comment.