Exemplo n.º 1
0
        /// <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>();

            userAgentDictionary.Add(BaseConstants.UserAgentHeader, UserAgentHeader.GetUserAgentHeader());
            return(userAgentDictionary);
        }
Exemplo 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
            if (!apiContext.MaskRequestId && !string.IsNullOrEmpty(apiContext.RequestId))
            {
                headers.Add(BaseConstants.PayPalRequestIdHeader, apiContext.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);
        }
Exemplo n.º 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
                {
                    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";

            // Set User-Agent HTTP header
            var 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);
            }

            // Set Custom HTTP headers
            foreach (KeyValuePair <string, string> header in headers)
            {
                httpRequest.Headers.Add(header.Key, header.Value);
            }

            foreach (string headerName in httpRequest.Headers)
            {
                logger.DebugFormat(headerName + ":" + httpRequest.Headers[headerName]);
            }

            HttpConnection httpConnection = new HttpConnection(config);

            try
            {
                response = httpConnection.Execute(postRequest, httpRequest);
            }
            catch (PayPal.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);
        }
 /// <summary>
 /// Override this method to customize User-Agent header value
 /// </summary>
 /// <returns>User-Agent header value string</returns>
 protected Dictionary <string, string> FormUserAgentHeader()
 {
     return(UserAgentHeader.GetHeader());
 }