Esempio n. 1
0
 public void VerifyUserAgentHeader()
 {
     var userAgent = new UserAgentHeader("test-product", "1.5.0");
     var header = userAgent.GetHeader();
     Assert.IsTrue(header.ContainsKey(BaseConstants.UserAgentHeader));
     var userAgentString = userAgent.GetHeader()[BaseConstants.UserAgentHeader];
     Assert.IsTrue(userAgentString.StartsWith("PayPalSDK/test-product 1.5.0"));
 }
Esempio n. 2
0
        /// <summary>
        /// Gets a collection of headers to be used in an HTTP request.
        /// </summary>
        /// <param name="apiContext">APIContext object containing information needed to construct the headers map.</param>
        /// <returns>A collection of headers.</returns>
        public static Dictionary <string, string> GetHeaderMap(APIContext apiContext)
        {
            var headers = new Dictionary <string, string>();

            /*
             * The implementation is PayPal specific. The Authorization header is
             * formed for OAuth or Basic, for OAuth system the authorization token
             * passed as a parameter is used in creation of HTTP header, for Basic
             * Authorization the ClientID and ClientSecret passed as parameters are
             * used after a Base64 encoding.
             */
            if (!string.IsNullOrEmpty(apiContext.AccessToken))
            {
                headers.Add(BaseConstants.AuthorizationHeader, apiContext.AccessToken);
            }
            else
            {
                var config       = apiContext.GetConfigWithDefaults();
                var clientId     = config.ContainsKey(BaseConstants.ClientId) ? config[BaseConstants.ClientId] : null;
                var clientSecret = config.ContainsKey(BaseConstants.ClientSecret) ? config[BaseConstants.ClientSecret] : null;
                if (!string.IsNullOrEmpty(clientId) && !string.IsNullOrEmpty(clientSecret))
                {
                    headers.Add(BaseConstants.AuthorizationHeader, "Basic " + EncodeToBase64(clientId, clientSecret));
                }
            }

            /*
             * Appends request Id which is used by PayPal API service for
             * Idempotency
             */
            var requestId = apiContext.MaskRequestId ? null : apiContext.RequestId;

            if (!string.IsNullOrEmpty(requestId))
            {
                headers.Add(BaseConstants.PayPalRequestIdHeader, requestId);
            }

            // Add User-Agent header for tracking in PayPal system
            var userAgentMap = UserAgentHeader.GetHeader();

            if (userAgentMap != null && userAgentMap.Count > 0)
            {
                foreach (KeyValuePair <string, string> entry in userAgentMap)
                {
                    headers.Add(entry.Key, entry.Value);
                }
            }

            // Add any custom headers
            if (apiContext.HTTPHeaders != null && apiContext.HTTPHeaders.Count > 0)
            {
                foreach (var header in apiContext.HTTPHeaders)
                {
                    headers.Add(header.Key, header.Value);
                }
            }
            return(headers);
        }
        /// <summary>
        /// Returns a PayPal specific User-Agent HTTP Header
        /// </summary>
        /// <returns>Dictionary containing User-Agent HTTP Header</returns>
        public static Dictionary <string, string> GetHeader()
        {
            var userAgentDictionary = new Dictionary <string, string>
            {
                { BaseConstants.UserAgentHeader, UserAgentHeader.GetUserAgentHeader() }
            };

            return(userAgentDictionary);
        }
Esempio n. 4
0
        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
                {
                    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
                var iso8851 = Encoding.GetEncoding("iso-8859-1", new EncoderReplacementFallback(string.Empty), new DecoderExceptionFallback());
                var 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);

            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);
        }
        /// <summary>
        /// Override this method to customize User-Agent header value
        /// </summary>
        /// <returns>User-Agent header value string</returns>
        protected Dictionary <string, string> FormUserAgentHeader()
        {
            UserAgentHeader userAgentHeader = new UserAgentHeader((SdkVersion == null)? null : SdkVersion.GetSDKId(), (SdkVersion == null)? null : SdkVersion.GetSDKVersion());

            return(userAgentHeader.GetHeader());
        }
        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
                {
                    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
                var iso8851 = Encoding.GetEncoding("iso-8859-1", new EncoderReplacementFallback(string.Empty), new DecoderExceptionFallback());
                var 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);
            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;
        }
 /// <summary>
 /// Override this method to customize User-Agent header value
 /// </summary>
 /// <returns>User-Agent header value string</returns>
 protected Dictionary<string, string> FormUserAgentHeader()
 {
     UserAgentHeader userAgentHeader = new UserAgentHeader((SdkVersion == null)? null : SdkVersion.GetSDKId(), (SdkVersion == null)? null : SdkVersion.GetSDKVersion());
     return userAgentHeader.GetHeader();
 }