Histórico de mensagens sobre credentials em pix

EXIBINDO CONVERSAS RECENTES:

Texto: credentials
Canal: pix
Avatar discord do usuario sinapse8788

sinapse8788

gn = Gerencianet(credentials)

# pega a data atual
data_atual = datetime.datetime.now().strftime("%Y-%m-%d")

# formata a data para o formato ano-mês-diaT00:00:00Z
# pega a data de início como um dia antes da data atual
data_inicio = (datetime.datetime.strptime(data_atual, '%Y-%m-%d') - datetime.timedelta(days=1)).strftime(
"%Y-%m-%d") + 'T00:00:00Z'

# pega a data de fim como o dia de hoje até a meia noite
data_fim = (datetime.datetime.strptime(data_atual, '%Y-%m-%d') + datetime.timedelta(days=0)).strftime(
"%Y-%m-%d") + 'T23:59:59Z'

params = {
"inicio": data_inicio,
"fim": data_fim
}

response = gn.pix_received_list(params=params)

print("Response antes da criação da lista", response)
# cria uma lista com os txid
txid_list = []
for pix in response['pix']:
txid_list.append(pix['txid'])
print("Lista tx", txid_list)

Avatar discord do usuario aureomoraes

aureomoraes

Ver Respostas

async function getToken(credentials) {
const authResponse = await authenticated(credentials);
const authData = Object.create(null);
const createdAt = Date.now();
authData.accessToken = authResponse.data?.access_token;
authData.createdAt = createdAt;
console.log(authData)
return authData
}


const GNRequest = async (credentials) => {

const { accessToken, createdAt } = await getToken(credentials);

const compareDate = addHours(createdAt, 1)

if (isAfter(Date.now(), compareDate)) {
console.log('chamou a função')
return getToken(credentials)
}


return axios.create({
baseURL: process.env.GN_ENDPOINT,
httpsAgent: agent,
headers: {
Authorization:
Bearer ${accessToken},
'Content-Type': 'application/json'
}
});
};

Avatar discord do usuario henryq_

henryq_

const GNRequest = async (credentials) => {
const authResponse = await authenticate(credentials);
const accessToken = authResponse.data?.access_token;

setTimeout(async () => {
GNRequest(credentials);
console.log(accessToken);
}, 3600000);

return axios.create({
baseURL: process.env.GN_ENDPOINT,
httpsAgent: agent,
headers: {
Authorization: Bearer ${accessToken},
"Content-Type": "application/json",
},
});
};

Avatar discord do usuario guilherme_efi

guilherme_efi

Ver Respostas

Primeiro você deve autenticar na API e obter o access_token.

php
$curl = curl_init();

$authorization = base64_encode("$client_id:$client_secret");

curl_setopt_array($curl, array(
CURLOPT_URL => "https://api-pix-h.gerencianet.com.br/oauth/token", // Rota base, desenvolvimento ou produção
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => '{"grant_type": "client_credentials"}',
CURLOPT_SSLCERT => $arq_certificado, // Caminho do certificado
CURLOPT_SSLCERTPASSWD => "",
CURLOPT_HTTPHEADER => array(
"Authorization: Basic $authorization",
"Content-Type: application/json"
),
));

$auth = json_decode(curl_exec($curl), true);

curl_close($curl);

$tokenType = $auth['token_type'];
$accessToken = $auth['access_token'];

Depois emitir o pix
php
$curl = curl_init();

curl_setopt_array($curl, array(
CURLOPT_URL => "https://api-pix-h.gerencianet.com.br/v2/cob/$txID",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "PUT",
CURLOPT_SSLCERT => $arq_certificado, // Caminho do certificado
CURLOPT_SSLCERTPASSWD => "",
CURLOPT_POSTFIELDS => '{
"calendario": {
"expiracao": 3600
},
"devedor": {
"cpf": "02279112312",
"nome": "Maria apareciada monteiro"
},
"valor": {
"original": "10.21"
},
"chave": "",
"solicitacaoPagador": "Mensaldiade Monteiro Sistemas"
}',
CURLOPT_HTTPHEADER => array(
"authorization: $tokenType $accessToken",
"Content-Type: application/json"
),
));

$dadosPix = json_decode(curl_exec($curl), true);
curl_close($curl);

return $dadosPix;

Avatar discord do usuario relixes

relixes

{
"error": "invalid_client",
"error_description": "Invalid or inactive credentials"
}

Avatar discord do usuario relixes

relixes

curl --location --request POST 'https://api-pix.gerencianet.com.br/oauth/token' \
--header 'x-client-cert-pem: {{X-Certificate-Pem}}' \
--data-raw '{
"grant_type": "client_credentials"
}'

Avatar discord do usuario rubenskuhl

rubenskuhl

Ver Respostas

A chave Pix é mencionada na chamada de um create immediate charge, por exemplo.

from gerencianet import Gerencianet
from ...credentials import credentials

gn = Gerencianet(credentials.CREDENTIALS)

body = {
'calendario': {
'expiracao': 3600
},
'devedor': {
'cpf': '',
'nome': ''
},
'valor': {
'original': ''
},
'chave': '',
'solicitacaoPagador': 'Cobrança dos serviços prestados.'
}

response = gn.pix_create_immediate_charge(body=body)
print(response)

Avatar discord do usuario bruno_laureano

bruno_laureano

Mas eu já passei o certificado dentro de credentials, alguém sabe o que pode ser o erro?

Avatar discord do usuario david_balbino

david_balbino


public class GerarPix {

static public void gerarPix(int valor){

Credentials credentials = new Credentials();

JSONObject options = new JSONObject();
options.put("client_id", credentials.getClientId());
options.put("client_secret", credentials.getClientSecret());
options.put("pix_cert", credentials.getCertificadoPix());
options.put("sandbox", credentials.isSandbox());

JSONObject body = new JSONObject();
body.put("calendario", new JSONObject().put("expiracao", 3600));
//body.put("devedor", new JSONObject().put("cpf", "94271564656").put("nome", "Gorbadoc Oldbuck"));
body.put("valor", new JSONObject().put("original", valor));
body.put("chave", "sua_chave");

try {
Gerencianet gn = new Gerencianet(options);
JSONObject response = gn.call("pixCreateImmediateCharge", new HashMap(), body);
System.out.println(response);
}catch (GerencianetException e){
System.out.println(e.getError());
System.out.println(e.getErrorDescription());
}
catch (Exception e) {
System.out.println(e.getMessage());
}

}


static public void gerarQrCode(String locId){

Credentials credentials = new Credentials();

HashMap options = new HashMap();
options.put("client_id", credentials.getClientId());
options.put("client_secret", credentials.getClientSecret());
options.put("pix_cert", credentials.getCertificadoPix());
options.put("sandbox", credentials.isSandbox());

HashMap params = new HashMap();
params.put("id", locId );

try {
Gerencianet gn = new Gerencianet(options);
Map response = gn.call("pixGenerateQRCode", params, new HashMap());

File outputfile = new File("qrCodeImage.png");
ImageIO.write(ImageIO.read(new ByteArrayInputStream(javax.xml.bind.DatatypeConverter.parseBase64Binary(((String) response.get("imagemQrcode")).split(",")[1]))), "png", outputfile);
Desktop desktop = Desktop.getDesktop();
desktop.open(outputfile);

}catch (GerencianetException e){
System.out.println(e.getError());
System.out.println(e.getErrorDescription());
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
}

Avatar discord do usuario carvalhocarneiro

carvalhocarneiro

Ver Respostas

Como falei antes, configurei tudo como modo de produção, mas no método de autenticação ele retorna Status:403 Could not authenticate. \nPlease make sure you are using correct credentials and if you are using then in the correct environment.

Avatar discord do usuario carvalhocarneiro

carvalhocarneiro

Ver Respostas

Bom dia, fiz a configuração do meu ambiente de desenvolvimento inicialmente utilizando as dados de homologação, mas o qrCode gerado sempre vem com erro, tentei fazer utilizando os dados de produção, baixando o certificado, gerando o pem, utilizando as chaves de cliente do ambiente de homologação, mas sempre retorna o erro:

Status:403 Could not authenticate. \nPlease make sure you are using correct credentials and if you are using then in the correct environment.
Estou utilizando essa lib -> https://github.com/gerencianet/gn-api-sdk-python

Avatar discord do usuario palloma_efi

palloma_efi

Ver Respostas

Você alterou o campo sandbox do aquivo de credentials.js para false?

Avatar discord do usuario jessica_efi

jessica_efi

Ver Respostas

Lembrando que você deve se atentar para o ambiente que esta utilizando, caso seja produção, inserir as credenciais de produção e o ambiente sandbox, como false e na pasta do certificado, inserir o seu certificado de produção, sendo que o nome do certificado deve ser o mesmo que esta no arquivo credentials.rb

Avatar discord do usuario jessica_efi

jessica_efi

Ver Respostas

Bom dia @keithyoder ! Você inseriu o client_id e client_secret nesse arquivo https://github.com/gerencianet/gn-api-sdk-ruby/blob/master/examples/credentials.rb e o certificado nessa pasta https://github.com/gerencianet/gn-api-sdk-ruby/tree/master/examples/certs ?

Avatar discord do usuario rubenskuhl

rubenskuhl

Ver Respostas

O exemplo que tem na doc é assim:

//Desenvolvido pela Consultoria Técnica da Gerencianet

"use strict";
const https = require("https");
var axios = require("axios");
var fs = require("fs");

//Insira o caminho de seu certificado .p12 dentro de seu projeto
var certificado = fs.readFileSync("./certificado.p12");

//Insira os valores de suas credenciais em desenvolvimento do pix
var credenciais = {
client_id: "YOUR-CLIENT-ID",
client_secret: "YOUR-CLIENT-SECRET",
};

var data = JSON.stringify({ grant_type: "client_credentials" });
var data_credentials = credenciais.client_id + ":" + credenciais.client_secret;

// Codificando as credenciais em base64
var auth = Buffer.from(data_credentials).toString("base64");

const agent = new https.Agent({
pfx: certificado,
passphrase: "",
});
//Consumo em desenvolvimento da rota post oauth/token
var config = {
method: "POST",
url: "https://api-pix-h.gerencianet.com.br/oauth/token",
headers: {
Authorization: "Basic " + auth,
"Content-Type": "application/json",
},
httpsAgent: agent,
data: data,
};

axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});

Avatar discord do usuario guilherme_efi

guilherme_efi

Ver Respostas

No body da requisição está enviando algo?
Deve se enviado o json:

json
{
"grant_type": "client_credentials"
}

imagem enviada na mensagem pelo usuario guilherme_efi

Avatar discord do usuario rubenskuhl

rubenskuhl

Ver Respostas

Ele precisa gerar client_id, client_secret e certificado, e te passar, por causa do modelo Credentials Flow. O que você sugere se chama Auth Code Flow, e este issue no GitHub do BACEN discute como isso seria:
https://github.com/bacen/pix-api/issues/83

Avatar discord do usuario igor_efi

igor_efi

Ver Respostas

Segue o exemplo:


$curl = curl_init();

curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api-pix-h.gerencianet.com.br/oauth/token',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS =>'{
"grant_type": "client_credentials"
}',
CURLOPT_HTTPHEADER => array(
'x-client-cert-pem: {{X-Certificate-Pem}}',
'Authorization: Basic (client id e secret em base64)',
'Content-Type: application/json'
),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;

Avatar discord do usuario rozer9580

rozer9580

x-amzn-requestid: 9367a7d9-a47b-4002-a7d2-9f5344a21e93
content-length: 70
x-amzn-remapped-content-length: 70
x-amzn-remapped-connection: keep-alive
x-request-id: ab5e47a4-28f2-4e94-84d0-9e7a8a1c456b
x-amz-apigw-id: P59iyGQhoAMFxFw=
vary: Origin
etag: W/"46-XAD/Fng+Qq6nuJUwSmDmoLFq8bc"
x-amzn-remapped-date: Fri, 01 Apr 2022 14:43:55 GMT
access-control-allow-credentials: true
content-type: application/json; charset=utf-8
date: Fri, 01 Apr 2022 14:43:55 GMT

{"nome":"erro_interno_servidor","mensagem":"Erro interno do servidor"}ArrayCurl info: