Histórico de mensagens sobre credentials

EXIBINDO CONVERSAS RECENTES:

Texto: credentials
# pix
Avatar discord do usuario frankkafka

frankkafka

js
const EfiPay = require('sdk-node-apis-efi')
const options = require('../../credentials')

let params = {
id: '95',
}

const efipay = new EfiPay(options)
console.log(efipay);

efipay.pixGenerateQRCode(params)
.then((resposta) => {
console.log(resposta)
})
.catch((error) => {
console.log(error)
})

# pix
Avatar discord do usuario _acb09

_acb09

Ver Respostas

O meu código está assim:

$config = [];
$config["certificado"] = config("services.efipay.certificate_path");
$config["client_id"] = config("services.efipay.client_id");
$config["client_secret"] = config("services.efipay.client_secret");

$headers = [];
$headers['Authorization'] = "Basic " . base64_encode($config["client_id"] . ":" . $config["client_secret"]);
$headers['Content-Type'] = 'application/json';

$curl = curl_init();

curl_setopt_array($curl, array(
CURLOPT_URL => "https://pix-h.api.efipay.com.br/oauth/token", // Rota base, homologação ou produção
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 60,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => '{"grant_type": "client_credentials"}',
CURLOPT_SSLCERT => $config["certificado"], // Caminho do certificado
CURLOPT_SSLCERTPASSWD => "",
CURLOPT_HTTPHEADER => $headers
));

$response = curl_exec($curl);

if (curl_errno($curl)) {
dd('Error:' . curl_error($curl));
}

curl_close($curl);

dd($response);

# pix
Avatar discord do usuario guilherme_efi

guilherme_efi

Ver Respostas

Provavelmente será isto.
Em nossa documentação técnica tem uma sessão sobre isto: https://dev.efipay.com.br/docs/api-pix/credenciais/#convers%C3%A3o-de-certificado-p12-para-o-formato-pem
Você pode usar este link para fazer a conversão do certificado: https://efipay.github.io/encode-credentials/certificado.html
Despois é só baixar o certificado, e este convertido você inseir no diretório.

# devs
Avatar discord do usuario cleyton5212

cleyton5212

Ver Respostas

class Gerencianet:
"""Classe para pagamento do Gerencianet."""

def __init__(self, credentials: GerencianetCredentials):
self.header = {}
self.credentials = credentials
self.cert = credentials.cert
self.payment_id = None
self.status_payment = None
self.key_pix = credentials.key_pix
self.user_id = None
self.hc = credentials.hc
self.c = "GerenciaNet"

async def create_payment(
self,
value: Union[int, float] = 0.0,
time: int = 30,
cpf: str = "",
name: str = "",
user_id: int = 0,
):
token = await self.credentials.token()
header = {
"Authorization": f"Bearer {token}",
}

# devs
Avatar discord do usuario russofullstack

russofullstack

posso subir em outro servidor e mandar o caminho no obj credentials?

# pix
Avatar discord do usuario d_coder_

d_coder_

Ver Respostas

pessoal quando estou fazendo a requisição para conseguir o access_token tenho como reposta
{"error":"invalid_client","error_description":"Invalid or inactive credentials"}
Isso é o certificado que esta errado ou as credenciais, client id e secrect que estão ? Tipo estou usando a url e homologação.

# pix
Avatar discord do usuario rubenskuhl

rubenskuhl

Ver Respostas

cob.write é escopo. Tem que ser client_credentials.

# pix
Avatar discord do usuario rubenskuhl

rubenskuhl

Ver Respostas

Parece que está faltando o

'{"grant_type": "client_credentials"}',

# devs
Avatar discord do usuario joaolucas_efi

joaolucas_efi

Ver Respostas

@jonadabir há uma falha na forma com que você está montando a requisição.

Ela deve ser da seguinte forma:

js
const certificatePath = path.join(
__dirname,
'../../../certificates/pix_certificate.p12',
);

const certificate = fs.readFileSync(certificatePath);

const getPixAuthorization = async () => {
const agent = new https.Agent({
pfx: certificate,
passphrase: '',
});

let authParams = {
method: 'POST',
url: 'https://pix-h.api.efipay.com.br/oauth/token',
data: {
grant_type: 'client_credentials',
},
httpsAgent: agent,
};
let token = Buffer.from(credentials.client_id + ':' + credentials.client_secret).toString('base64')
authParams.headers['Authorization'] = 'Basic ' + token
authParams.headers['Content-Type'] = 'application/json'
const authRes = await axios(authParams);

return authRes.data;
};

# devs
Avatar discord do usuario jonadabir

jonadabir

Ver Respostas

estou tentando fazer a req de obter autorização PIX porem estou recebendo o seguinte erro:

ts
cause: Error: socket hang up
at TLSSocket.socketOnEnd (node:_http_client:524:23)
at TLSSocket.emit (node:events:531:35)
at endReadableNT (node:internal/streams/readable:1696:12)
at processTicksAndRejections (node:internal/process/task_queues:82:21) {
code: 'ECONNRESET'
}
Meu código:
ts
const certificatePath = path.join(
__dirname,
'../../../certificates/pix_certificate.p12',
);

const certificate = fs.readFileSync(certificatePath);

const getPixAuthorization = async () => {
const agent = new https.Agent({
pfx: certificate,
passphrase: '',
});

const authParams = {
method: 'POST',
url: 'https://pix-h.api.efipay.com.br/oauth/token',
auth: {
username: credentials.client_id,
password: credentials.client_secret,
},
data: {
grant_type: 'client_credentials',
},
httpsAgent: agent,
};

const authRes = await axios(authParams);

return authRes.data;
};

# pix
Avatar discord do usuario joaolucas_efi

joaolucas_efi

Ver Respostas

A requisição não esta enviado os campos corretos, um exemplo de envio seria esse aqui:

py

# encoding: utf-8

from efipay import EfiPay
from ...credentials import credentials

efi = EfiPay(credentials.CREDENTIALS)


params = {
'idEnvio': 1
}

body = {
'valor': '0.01',
'pagador': {
'chave': '' # Sua chave aqui
},
'favorecido': {
'chave': '' # Chave de quem vai receber aqui
}
}

response = efi.pix_send(params=params, body=body)
print(response)

Também informamos que é para habilitar o endpoint de Envio de Pix em produção, é necessário preencher este formulário. Após o preenchimento, basta aguardar que entraremos em contato.

# pix
Avatar discord do usuario diogojunior.

diogojunior.

def enviar_pagamento_pix(chave_pix, valor):
try:
efi = EfiPay(credentials)

# Corpo da requisição para enviar um pagamento PIX
body = {
'valor': {
'original': valor # Valor da transferência
},
'chave': chave_pix, # Chave PIX do destinatário
'infoPagador': 'Pagamento pelos serviços prestados.' # Informação adicional
}

# Tentando diferentes métodos para enviar o pagamento PIX
response = None
if hasattr(efi, 'pix_send_payment'):
response = efi.pix_send_payment(body=body)
elif hasattr(efi, 'pix_transfer'):
response = efi.pix_transfer(body=body)
else:
raise AttributeError("Nenhum método encontrado para enviar pagamento PIX.")

print("Resposta da API:", response)

except Exception as e:
print(f"Erro ao enviar pagamento PIX: {e}")
sys.exit(1)

if __name__ == "__main__":
chave_pix, valor = obter_dados_usuario()
enviar_pagamento_pix(chave_pix, valor)

# pix
Avatar discord do usuario diogojunior.

diogojunior.

# encoding: utf-8

from efipay import EfiPay
import sys

# Configurações de credenciais
credentials = {
'client_id': '',
'client_secret': '',
'sandbox': False, # Altere para True se estiver usando o ambiente de sandbox
'certificate': r''
}

def obter_dados_usuario():
try:
chave_pix = input("Informe a chave PIX do destinatário: ")
valor = input("Informe o valor da transferência: ")

# Verificando se os valores informados são válidos
if not chave_pix:
raise ValueError("A chave PIX não pode ser vazia.")

# Substituir vírgula por ponto e converter para float
valor_float = float(valor.replace(',', '.'))

if valor_float <= 0:
raise ValueError("O valor deve ser um número positivo.")

return chave_pix, "{:.2f}".format(valor_float)
except ValueError as ve:
print(f"Erro de validação: {ve}")
sys.exit(1)

# pix
Avatar discord do usuario joaolucas_efi

joaolucas_efi

Ver Respostas

This is correct, but in this case the credentials that you use are not from the account that own the self.EFI_FT_PIX_KEY.

# pix
Avatar discord do usuario _franciscovieira

_franciscovieira

json {"grant_type":"client_credentials"}

# pix
Avatar discord do usuario _franciscovieira

_franciscovieira

Boa tarde pessoal
Estou com uma dúvida aqui
params.put("grant_type", "client_credentials");

String json = g.toJson(new GrantType("client_credentials"));

Esse cara está me retornando que está fatando grantType

# devs
Avatar discord do usuario joaolucas_efi

joaolucas_efi

Ver Respostas

Bom dia, @jonadabir, tudo bem?
A autenticação para a API de cobranças deve ser algo da seguinte forma

js
async authenticate() {
let authParams = {
method: 'POST',
url: 'https://cobrancas-h.api.efipay.com.br/v1/authorize',
auth: {
username: credentials.client_id,
password: credentials.client_secret,
},
data: {
grant_type: 'client_credentials',
},
}
return axios(authParams)
.then((res) => {
this.auth = res.data
this.auth.authDate = new Date().getTime() / 1000
})
.catch((error) => {
throw error.data
})
}

# devs
Avatar discord do usuario jonadabir

jonadabir

Ver Respostas

Bom dia! Estou tentando fazer a requisiçao de obter a autorizaçao no node igual na documentaçao, porem estou tomando um 401

ts
const credentials = {
client_id: process.env.EFI_CLIENT_ID,
client_secret: process.env.EFI_CLIENT_SECRET,
};

export const getCobrancasAuthorization = async () => {
const data = JSON.stringify({ grant_type: 'client_credentials' });
const data_credentials =
credentials.client_id + ':' + credentials.client_secret;

const auth = Buffer.from(data_credentials).toString('base64');

const config = {
method: 'POST',
url: 'https://cobrancas-h.api.efipay.com.br/v1/authorize',
headers: {
Authorization: 'Basic ' + auth,
'Content-Type': 'application/json',
},
data: data,
};

try {
const response = await axios(config);
return response.data;
} catch (error) {
console.log(error);
}
};