· 4 years ago · May 04, 2021, 10:42 PM
1 [Serializable]
2 private class GrantType{
3 public string grant_type { get; set; }
4 }
5
6 public static string GetGerencianetToken(){
7 //default true = teste
8 Boolean ambienteDeTeste = true; //true = teste, false = producao
9
10 //sandbox
11 string URL_TOKEN = GerencianetPIXUrls.GetUrlSandbox() + "/oauth/token";
12 string ClientID = GerencianetPIXKeys.ClientIDSandbox();
13 string ClientSecret = GerencianetPIXKeys.ClientSecretSandbox();
14
15 if (!ambienteDeTeste){
16 //producao
17 URL_TOKEN = GerencianetPIXUrls.GetUrlProducao() + "/oauth/token";
18 ClientID = GerencianetPIXKeys.ClientIDProducao();
19 ClientSecret = GerencianetPIXKeys.ClientSecretProducao();
20 }
21 Debug.WriteLine("Token: " + URL_TOKEN);
22
23 var credencials = new Dictionary<string, string>{
24 {"client_id", ClientID},
25 {"client_secret", ClientSecret}
26 };
27 var authorization = Base64.Encode(credencials["client_id"] + ":" + credencials["client_secret"]);
28 var client = new RestSharp.RestClient(URL_TOKEN);
29 var request = new RestRequest(Method.POST);
30
31 //certificado
32 String pathFile = HttpContext.Current.Server.MapPath("~/GerenciaNetAPI");
33 X509Certificate2 uidCert = null;
34 if (ambienteDeTeste){
35 //sandbox
36 String cert = Path.Combine(pathFile, "homologacao-299325-premiosonpix_ce.p12");
37 uidCert = new X509Certificate2(cert, "");
38 }else{
39 //producao
40 String cert = Path.Combine(pathFile, "producao-299325-premiosonpix_ce.p12");
41 uidCert = new X509Certificate2(cert, "");
42 }
43 client.ClientCertificates = new X509CertificateCollection() { uidCert };
44
45 //json
46 GrantType grantType = new GrantType() { grant_type = "client_credentials" };
47 var jsonContent = JsonConvert.SerializeObject(grantType, Formatting.Indented);
48 //Debug.WriteLine("Content String: " + jsonContent);
49
50 //header
51 request.AddHeader("Authorization", "Basic " + authorization);
52 request.AddHeader("Content-Type", "application/json");
53 request.AddParameter("application/json", jsonContent, ParameterType.RequestBody);
54
55 IRestResponse restResponse = client.Execute(request);
56 Debug.WriteLine("Rest Response: " + restResponse);
57 string response = restResponse.Content;
58 Debug.WriteLine("Response: " + response);
59 JObject json = JObject.Parse(response);
60 string access_token = json["access_token"].ToString();
61
62 return access_token;
63 }