public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { JObject endpoint = null; endpoint = (JObject)this.endpoints[binder.Name]; if (endpoint == null) throw new GnException(0, "invalid_endpoint", string.Format("Método '{0}' inexistente", binder.Name)); var route = (string)endpoint["route"]; var method = (string)endpoint["method"]; object body = new { }; object query = new { }; if (args.Length > 0 && args[0] != null) query = args[0]; if (args.Length > 1 && args[1] != null) body = args[1]; if (token == null) Authenticate(); try { result = RequestEndpoint(route, method, query, body); return true; } catch (GnException e) { if (e.Code == 401) { this.Authenticate(); result = this.RequestEndpoint(route, method, query, body); return true; } else { throw e; } } }
private void Authenticate() { object body = new { grant_type = "client_credentials" }; WebRequest request = this.httpHelper.GetWebRequest("/authorize", "post", null); string credentials = string.Format("{0}:{1}", this.clientId, this.clientSecret); string encodedAuth = Convert.ToBase64String(Encoding.GetEncoding("UTF-8").GetBytes(credentials)); request.Headers.Add("Authorization", string.Format("Basic {0}", encodedAuth)); request.Headers.Add("api-sdk", string.Format("dotnet-{0}", Endpoints.Version)); try { dynamic response = this.httpHelper.SendRequest(request, body); this.token = response.access_token; } catch (WebException) { throw GnException.Build("", 401); } }