Histórico de mensagens sobre credentials

EXIBINDO CONVERSAS RECENTES:

Texto: credentials
# pix
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",
},
});
};

# dúvidas
Avatar discord do usuario joehenrique7

joehenrique7

No exemplo tem:
Map credentials = {
'client_id': '',
'client_secret': '',
'account_id': '',
'sandbox': true,
'certificate': '',
'private_key': ''
};

onde pego este dado

# pix
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;

# pix
Avatar discord do usuario relixes

relixes

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

# pix
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)

# pix
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?

# pix
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());
}
}
}

# pix
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.

# pix
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

# pix
Avatar discord do usuario palloma_efi

palloma_efi

Ver Respostas

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

# pix
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

# pix
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 ?

# cartões
Avatar discord do usuario igor_efi

igor_efi

Ver Respostas

Certo, é possivel sim. No PHP você pode utilizar o Curl para realizar as requisições. Segue o exemplo para autenticar na API:


$curl = curl_init();

curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.gerencianet.com.br/v1/authorize',
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(
'Authorization: Basic (cliend_id:client_secret) em base64',
'Content-Type: application/json'
),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;

# pix
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);
});

# pix
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

# pix
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

# assinaturas
Avatar discord do usuario higorvergara

higorvergara

Ver Respostas

Bem conseguimos, o erro foi visto no LOG, foi informado que a pasta não existia, alteramos e foi confirmado, ou seja, quem tiver esse erro é só ver a questão do diretorio nos arquivos credentials.json, emitir_assinatura.php

# pix
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;