コード例 #1
0
        private string GenerateOAuthToken(string base64ClientID)
        {
            string response = null;

            Uri uniformResourceIdentifier = null;
            Uri baseUri = null;

            if (config.ContainsKey(BaseConstants.OAUTH_ENDPOINT))
            {
                baseUri = new Uri(config[BaseConstants.OAUTH_ENDPOINT]);
            }
            else if (config.ContainsKey(BaseConstants.END_POINT_CONFIG))
            {
                baseUri = new Uri(config[BaseConstants.END_POINT_CONFIG]);
            }
            else if (config.ContainsKey(BaseConstants.APPLICATION_MODE_CONFIG))
            {
                string mode = config[BaseConstants.APPLICATION_MODE_CONFIG];
                if (mode.Equals(BaseConstants.LIVE_MODE))
                {
                    baseUri = new Uri(BaseConstants.REST_LIVE_ENDPOINT);
                }
                else if (mode.Equals(BaseConstants.SANDBOX_MODE))
                {
                    baseUri = new Uri(BaseConstants.REST_SANDBOX_ENDPOINT);
                }
                else
                {
                    throw new ConfigException("You must specify one of mode(live/sandbox) OR endpoint in the configuration");
                }
            }
            bool success = Uri.TryCreate(baseUri, OAUTHTOKENPATH, out uniformResourceIdentifier);
            ConnectionManager connManager = ConnectionManager.Instance;
            HttpWebRequest    httpRequest = connManager.GetConnection(this.config, uniformResourceIdentifier.AbsoluteUri);


            Dictionary <string, string> headers = new Dictionary <string, string>();

            headers.Add("Authorization", "Basic " + base64ClientID);
            string postRequest = "grant_type=client_credentials";

            httpRequest.Method      = "POST";
            httpRequest.Accept      = "*/*";
            httpRequest.ContentType = "application/x-www-form-urlencoded";
            httpRequest.UserAgent   = RESTConfiguration.FormUserAgentHeader();
            foreach (KeyValuePair <string, string> header in headers)
            {
                httpRequest.Headers.Add(header.Key, header.Value);
            }

            HttpConnection httpConnection = new HttpConnection(config);

            response = httpConnection.Execute(postRequest, httpRequest);
            JObject deserializedObject = (JObject)JsonConvert.DeserializeObject(response);
            string  generatedToken     = (string)deserializedObject["token_type"] + " " + (string)deserializedObject["access_token"];

            appID              = (string)deserializedObject["app_id"];
            secondsToExpire    = (int)deserializedObject["expires_in"];
            timeInMilliseconds = DateTime.Now.Millisecond;
            return(generatedToken);
        }
コード例 #2
0
        public static T ConfigureAndExecute <T>(APIContext apiContext, HttpMethod httpMethod, string resource, Dictionary <string, string> headersMap, string payLoad)
        {
            try
            {
                string response = null;
                Dictionary <string, String> headers;
                Uri uniformResourceIdentifier = null;
                Uri baseUri = null;
                Dictionary <string, string> config = null;
                if (apiContext.Config == null)
                {
                    config = ConfigManager.getConfigWithDefaults(ConfigManager.Instance.GetProperties());
                }
                else
                {
                    config = ConfigManager.getConfigWithDefaults(apiContext.Config);
                }
                baseUri = GetBaseURI(config);
                bool success = Uri.TryCreate(baseUri, resource, out uniformResourceIdentifier);

                RESTConfiguration restConfiguration = new RESTConfiguration(config, headersMap);
                restConfiguration.authorizationToken = apiContext.AccessToken;
                restConfiguration.requestId          = apiContext.RequestID;
                headers = restConfiguration.GetHeaders();

                ConnectionManager connMngr = ConnectionManager.Instance;
                connMngr.GetConnection(config, uniformResourceIdentifier.ToString());
                HttpWebRequest httpRequest = connMngr.GetConnection(config, uniformResourceIdentifier.ToString());
                httpRequest.Method = httpMethod.ToString();
                if (headers != null && headers.ContainsKey("Content-Type"))
                {
                    httpRequest.ContentType = headers["Content-Type"];
                    headers.Remove("Content-Type");
                }
                else
                {
                    httpRequest.ContentType = "application/json";
                }
                httpRequest.ContentLength = payLoad.Length;
                foreach (KeyValuePair <string, string> header in headers)
                {
                    if (header.Key.Trim().Equals("User-Agent"))
                    {
                        httpRequest.UserAgent = header.Value;
                    }
                    else
                    {
                        httpRequest.Headers.Add(header.Key, header.Value);
                    }
                }
                if (logger.IsDebugEnabled)
                {
                    foreach (string headerName in httpRequest.Headers)
                    {
                        logger.Debug(headerName + ":" + httpRequest.Headers[headerName]);
                    }
                }
                HttpConnection connectionHttp = new HttpConnection(config);
                response = connectionHttp.Execute(payLoad, httpRequest);
                if (typeof(T).Name.Equals("Object"))
                {
                    return(default(T));
                }
                else
                {
                    return(JsonConvert.DeserializeObject <T>(response));
                }
            }
            catch (PayPalException ex)
            {
                throw ex;
            }
            catch (System.Exception ex)
            {
                throw new PayPalException(ex.Message, ex);
            }
        }
コード例 #3
0
        /// <summary>
        /// Generates a new OAuth token useing the specified client credentials in the authorization request.
        /// </summary>
        /// <param name="base64ClientId">The base-64 encoded credentials to be used in the authorization request.</param>
        /// <returns>The OAuth access token to use for making PayPal requests.</returns>
        private string GenerateOAuthToken(string base64ClientId)
        {
            string response = null;

            Uri uniformResourceIdentifier = null;
            Uri baseUri = null;

            if (config.ContainsKey(BaseConstants.OAuthEndpoint))
            {
                baseUri = new Uri(config[BaseConstants.OAuthEndpoint]);
            }
            else if (config.ContainsKey(BaseConstants.EndpointConfig))
            {
                baseUri = new Uri(config[BaseConstants.EndpointConfig]);
            }
            else if (config.ContainsKey(BaseConstants.ApplicationModeConfig))
            {
                string mode = config[BaseConstants.ApplicationModeConfig];
                if (mode.Equals(BaseConstants.LiveMode))
                {
                    baseUri = new Uri(BaseConstants.RESTLiveEndpoint);
                }
                else if (mode.Equals(BaseConstants.SandboxMode))
                {
                    baseUri = new Uri(BaseConstants.RESTSandboxEndpoint);
                }
                else if (mode.Equals(BaseConstants.TestSandboxMode))
                {
                    baseUri = new Uri(BaseConstants.RESTTestSandboxEndpoint);
                }
                else
                {
                    throw new ConfigException("You must specify one of mode(live/sandbox) OR endpoint in the configuration");
                }
            }
            bool success = Uri.TryCreate(baseUri, OAuthTokenPath, out uniformResourceIdentifier);
            ConnectionManager connManager = ConnectionManager.Instance;
            HttpWebRequest    httpRequest = connManager.GetConnection(this.config, uniformResourceIdentifier.AbsoluteUri);

            Dictionary <string, string> headers = new Dictionary <string, string>();

            headers.Add("Authorization", "Basic " + base64ClientId);
            string postRequest = "grant_type=client_credentials";

            httpRequest.Method      = "POST";
            httpRequest.Accept      = "*/*";
            httpRequest.ContentType = "application/x-www-form-urlencoded";
            UserAgentHeader             userAgentHeader = new UserAgentHeader(SdkVersion == null ? "" : SdkVersion.GetSDKId(), SdkVersion == null ? "" : SdkVersion.GetSDKVersion());
            Dictionary <string, string> userAgentMap    = userAgentHeader.GetHeader();

            foreach (KeyValuePair <string, string> entry in userAgentMap)
            {
                // aganzha
                //iso-8859-1
                Encoding iso8851 = Encoding.GetEncoding("iso-8859-1", new EncoderReplacementFallback(string.Empty), new DecoderExceptionFallback());
                byte[]   bytes   = Encoding.Convert(Encoding.UTF8, iso8851, Encoding.UTF8.GetBytes(entry.Value));
                httpRequest.UserAgent = iso8851.GetString(bytes);
            }
            foreach (KeyValuePair <string, string> header in headers)
            {
                httpRequest.Headers.Add(header.Key, header.Value);
            }

            HttpConnection httpConnection = new HttpConnection(config);

            try
            {
                response = httpConnection.Execute(postRequest, httpRequest);
            }
            catch (PayPal.Exception.HttpException ex)
            {
                // If we get an HTTP exception back and the status code is 401,
                // then try and generate an IdentityException object to throw.
                if (ex.StatusCode == HttpStatusCode.Unauthorized)
                {
                    IdentityException identityEx;
                    if (ex.TryConvertTo <IdentityException>(out identityEx))
                    {
                        throw identityEx;
                    }
                }

                throw;
            }

            JObject deserializedObject = (JObject)JsonConvert.DeserializeObject(response);
            string  generatedToken     = (string)deserializedObject["token_type"] + " " + (string)deserializedObject["access_token"];

            this.ApplicationId = (string)deserializedObject["app_id"];
            this.AccessTokenExpirationInSeconds = (int)deserializedObject["expires_in"];
            this.AccessTokenLastCreationDate    = DateTime.Now;
            return(generatedToken);
        }