Esempio n. 1
0
        private async Task <WooProductAttributeResponse> InsertWoocommerceBrandAttribute(string woocommerceUrl, string consumerKey, string consumerSecret)
        {
            WooProductAttributeResponse productAttribute = null;

            var requestUrl  = $"{woocommerceUrl}/wp-json/wc/v3/products/attributes";
            var oAuthClient = OAuthRequest.ForRequestToken(consumerKey, consumerSecret);

            oAuthClient.RequestUrl = requestUrl;
            oAuthClient.Method     = "POST";
            var auth = oAuthClient.GetAuthorizationHeader();

            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("Authorization", auth);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*"));
                client.DefaultRequestHeaders.UserAgent.ParseAdd("PostmanRuntime/7.26.8");
                client.DefaultRequestHeaders.Connection.Add("keep-alive");
                client.Timeout = new TimeSpan(1, 0, 0);

                var requestBody = JsonConvert.SerializeObject(new WooProductAttributeRequest
                {
                    Name = "brand"
                });

                var response = await client.PostAsync(requestUrl, new StringContent(requestBody, Encoding.UTF8, "application/json"));

                var responseStr = await response.Content.ReadAsStringAsync();

                productAttribute = JsonConvert.DeserializeObject <WooProductAttributeResponse>(responseStr);
            }

            return(productAttribute);
        }
Esempio n. 2
0
        public async Task <RequestTokenInfo> GetRequestToken()
        {
            OAuthRequest client = OAuthRequest.ForRequestToken(
                Resources.ConsumerKey,
                Resources.ConsumerSecret,
                Resources.CallbackURL);

            client.RequestUrl = Resources.RequestTokenURL;

            // Using URL query authorization
            var responseString = await Tools.GetStringResponse(string.Format("{0}?{1}", client.RequestUrl, client.GetAuthorizationQuery()));

            var tokenValues = GetTokenValues(responseString);

            var requestTokenInfo = new RequestTokenInfo();

            requestTokenInfo.RequestToken      = tokenValues[0];
            requestTokenInfo.RequestSecret     = tokenValues[1];
            requestTokenInfo.CallbackConfirmed = tokenValues[2];
            requestTokenInfo.CallbackUrl       = Resources.CallbackURL;

            requestTokenInfo.AccessUrl = string.Format("{0}?oauth_token={1}", Resources.AuthorizeURL, requestTokenInfo.RequestToken);

            return(requestTokenInfo);
        }
Esempio n. 3
0
        public string CreateBrowseableUrl()
        {
            // this is the endpoint we will be calling
            string REQUEST_URL = "https://api.twitter.com/oauth/request_token?oauth_callback=oob";

            // Create a new connection to the OAuth server, with a helper method
            OAuthRequest client = OAuthRequest.ForRequestToken(YoutubeClientData.TwitterOauthToken, YoutubeClientData.TwitterOauthTokenSecret, "oob");

            client.RequestUrl = REQUEST_URL;

            // add HTTP header authorization
            string         auth    = client.GetAuthorizationHeader();
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(client.RequestUrl);

            request.Headers.Add("Authorization", auth);

            Console.WriteLine("Calling " + REQUEST_URL);

            // make the call and print the string value of the response JSON
            HttpWebResponse response    = (HttpWebResponse)request.GetResponse();
            Stream          dataStream  = response.GetResponseStream();
            StreamReader    reader      = new StreamReader(dataStream);
            string          strResponse = reader.ReadToEnd();

            var queryParams = HttpUtility.ParseQueryString(strResponse);

            RequestToken = queryParams["oauth_token"];

            // answer: oauth_token=6E9q-gAAAAABFGpUAAABc0TQsN4&oauth_token_secret=FwJdADlFg2H4niPoE0M3WOUROmElhcal&oauth_callback_confirmed=true
            return($"https://api.twitter.com/oauth/authorize?oauth_token={RequestToken}");
        }
        /// <summary>
        /// Gets an OAuth request token
        /// </summary>
        private OAuthToken GetRequestToken()
        {
            var request = OAuthRequest.ForRequestToken(_clientKey, _clientSecret);

            request.CallbackUrl = "oob";
            request.Method      = "POST";
            request.RequestUrl  = _apiUri.AbsoluteUri + ApiEndpoints.RequestToken;

            using (var http = new HttpClient())
            {
                http.DefaultRequestHeaders.Add("Authorization", request.GetAuthorizationHeader());

                var response     = http.PostAsync(request.RequestUrl, null).Result;
                var responseBody = response.Content.ReadAsStringAsync().Result;

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    throw new BreezyApiException(
                              String.Format("Could not get request token.\r\nResponse status code: {0}.\r\nResponse: {1}",
                                            response.StatusCode, responseBody));
                }

                var content = Util.ParseFormContent(responseBody);
                return(new OAuthToken
                {
                    Token = content["oauth_token"],
                    TokenSecret = content["oauth_token_secret"]
                });
            }
        }
        public static OauthToken GetRequestToken(string baseUrl, AvansOauthHelperOptions options)
        {
            // Creating a new instance with a helper method
            OAuthRequest client = OAuthRequest.ForRequestToken(options.AvansClientId, options.AvansSecret);

            client.RequestUrl  = "https://publicapi.avans.nl/oauth/request_token";
            client.CallbackUrl = baseUrl + "/api/account/AvansCallback";

            // Using URL query authorization to get the request token
            string auth     = client.GetAuthorizationQuery();
            var    url      = client.RequestUrl + "?" + auth;
            var    request  = (HttpWebRequest)WebRequest.Create(url);
            var    response = (HttpWebResponse)request.GetResponse();

            Stream       receiveStream = response.GetResponseStream();
            StreamReader reader        = new StreamReader(receiveStream, Encoding.UTF8);
            string       body          = reader.ReadToEnd();

            //TY for the concistent response avans
            var uri = body.Replace("php&", "php?");

            uri = uri.Split("authentification_url=")[1];

            return(AvansOauthHelper.getTokenFormUri(uri));
        }
Esempio n. 6
0
        public string GetOAuthRedirect(string consumerKey, string consumerSecret, string callbackUrl)
        {
            // Creating a new instance with a helper method
            var oAuthRequest = OAuthRequest.ForRequestToken(consumerKey, consumerSecret, callbackUrl);

            oAuthRequest.RequestUrl = "https://api.twitter.com/oauth/request_token";
            var qscoll = HttpUtility.ParseQueryString(ExecuteRequest(GetRequest(oAuthRequest, new Dictionary <string, string>())).Content);

            return(string.Format("https://api.twitter.com/oauth/authorize?oauth_token={0}", qscoll["oauth_token"]));
        }
Esempio n. 7
0
        public string GetOAuthRedirect(string consumerKey, string consumerSecret, string callbackUrl)
        {
            // Creating a new instance with a helper method
            var oAuthRequest = OAuthRequest.ForRequestToken(consumerKey, consumerSecret, callbackUrl);

            oAuthRequest.RequestUrl = "https://api.twitter.com/oauth/request_token";
            var qscoll = OAuthQuery(oAuthRequest);

            return(string.Format("https://api.twitter.com/oauth/authorize?oauth_token={0}", qscoll["oauth_token"]));
        }
Esempio n. 8
0
        private static string GetRequestToken(string url)
        {
            OAuthRequest client = OAuthRequest.ForRequestToken(ConsumerKey, ConsumerSecret);

            client.RequestUrl      = url;
            client.Method          = "POST";
            client.SignatureMethod = OAuthSignatureMethod.HmacSha1;
            string urlRet = client.GetAuthorizationQuery();

            return(url + '?' + urlRet);
        }
Esempio n. 9
0
        public override object RequestAction(string action, IDictionary <string, string> query)
        {
            if (action == "startOAuth")
            {
                if (query["callbackUrl"].IsNullOrWhiteSpace())
                {
                    throw new BadRequestException("QueryParam callbackUrl invalid.");
                }

                var oAuthRequest = OAuthRequest.ForRequestToken(null, null, query["callbackUrl"]);
                oAuthRequest.RequestUrl = Settings.OAuthRequestTokenUrl;
                var qscoll = OAuthQuery(oAuthRequest);

                var url = string.Format("{0}?oauth_token={1}&oauth_callback={2}", Settings.OAuthUrl, qscoll["oauth_token"], query["callbackUrl"]);

                return(new
                {
                    OauthUrl = url,
                    RequestTokenSecret = qscoll["oauth_token_secret"]
                });
            }
            else if (action == "getOAuthToken")
            {
                if (query["oauth_token"].IsNullOrWhiteSpace())
                {
                    throw new BadRequestException("QueryParam oauth_token invalid.");
                }

                if (query["requestTokenSecret"].IsNullOrWhiteSpace())
                {
                    throw new BadRequestException("Missing requestTokenSecret.");
                }

                var oAuthRequest = OAuthRequest.ForAccessToken(null, null, query["oauth_token"], query["requestTokenSecret"], "");
                oAuthRequest.RequestUrl = Settings.OAuthAccessTokenUrl;
                var qscoll = OAuthQuery(oAuthRequest);

                Settings.AccessToken       = qscoll["oauth_token"];
                Settings.AccessTokenSecret = qscoll["oauth_token_secret"];

                var user = GetUser(Settings.UserId);

                return(new
                {
                    Settings.AccessToken,
                    Settings.AccessTokenSecret,
                    RequestTokenSecret = "",
                    UserId = user.Item1,
                    UserName = user.Item2
                });
            }

            return(new { });
        }
Esempio n. 10
0
        //Stream currentResponse;

        //Constructor
        public OAuth(string consumer_key, string consumer_secret)
        {
            this.baseUrl = "https://app.smartfile.com/";

            this.requestUrl       = "https://app.smartfile.com/oauth/request_token/";
            this.userAuthorizeUrl = "https://app.smartfile.com/oauth/authorize/";
            this.accessUrl        = "https://app.smartfile.com/oauth/access_token/";
            this.consumer_key     = consumer_key;
            this.consumer_secret  = consumer_secret;

            this.client = OAuthRequest.ForRequestToken(this.consumer_key, this.consumer_secret);
        }
Esempio n. 11
0
        public void Can_get_request_token_with_query()
        {
            var client = OAuthRequest.ForRequestToken(_consumerKey, _consumerSecret);

            client.RequestUrl = string.Format(BaseUrl, "request_token");

            var auth = client.GetAuthorizationQuery();

            var url = client.RequestUrl + "?" + auth;

            var request = (HttpWebRequest)WebRequest.Create(url);

            var response = (HttpWebResponse)request.GetResponse();

            Assert.IsNotNull(response);

            Assert.AreEqual(200, (int)response.StatusCode);
        }
Esempio n. 12
0
        private async Task <WooInsertCategoriesRootResponse> InsertBatchCategories(IEnumerable <CategoryNamesMapping> categoryNamesMappings,
                                                                                   string woocommerceUrl, string consumerKey, string consumerSecret)
        {
            var insertCategoriestRootResponse = new WooInsertCategoriesRootResponse();

            var requestUrl  = $"{woocommerceUrl}/wp-json/wc/v3/products/categories/batch";
            var oAuthClient = OAuthRequest.ForRequestToken(consumerKey, consumerSecret);

            oAuthClient.RequestUrl = requestUrl;
            oAuthClient.Method     = "POST";
            var auth = oAuthClient.GetAuthorizationHeader();

            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("Authorization", auth);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*"));
                client.DefaultRequestHeaders.UserAgent.ParseAdd("PostmanRuntime/7.26.8");
                client.DefaultRequestHeaders.Connection.Add("keep-alive");
                client.Timeout = new TimeSpan(1, 0, 0);

                var requestBody = JsonConvert.SerializeObject(new WooInsertCategoriesRootRequest
                {
                    Update = new List <object>(),
                    Delete = new List <object>(),
                    Create = categoryNamesMappings.Select(el => new WooCreateCategoryRequest
                    {
                        Name   = el.Name,
                        Parent = el.WoocommerceParentId,
                        Slug   = el.Slug
                    }).ToList()
                });

                var response = await client.PostAsync(requestUrl, new StringContent(requestBody, Encoding.UTF8, "application/json"));

                var responseSting = await response.Content.ReadAsStringAsync();

                insertCategoriestRootResponse = JsonConvert.DeserializeObject <WooInsertCategoriesRootResponse>(responseSting);
            }

            return(insertCategoriestRootResponse);
        }
Esempio n. 13
0
        private async Task <ButchInsertProductResponse> InsertButchProducts(string woocommerceUrl, string consumerKey, string consumerSecret, List <ProductRequest> products)
        {
            ButchInsertProductResponse butchInsertProductResponse = null;

            var requestUrl  = $"{woocommerceUrl}/wp-json/wc/v3/products/batch";
            var oAuthClient = OAuthRequest.ForRequestToken(consumerKey, consumerSecret);

            oAuthClient.RequestUrl = requestUrl;
            oAuthClient.Method     = "POST";
            var auth = oAuthClient.GetAuthorizationHeader();

            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("Authorization", auth);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*"));
                client.DefaultRequestHeaders.UserAgent.ParseAdd("PostmanRuntime/7.26.8");
                client.DefaultRequestHeaders.Connection.Add("keep-alive");
                client.Timeout = new TimeSpan(1, 0, 0);

                var requestBody = JsonConvert.SerializeObject(new ButchInsertProductsRequest
                {
                    Update = new List <object>(),
                    Delete = new List <object>(),
                    Create = products
                });

                var start = DateTime.Now;

                var response = await client.PostAsync(requestUrl, new StringContent(requestBody, Encoding.UTF8, "application/json"));

                var end = DateTime.Now;

                Console.WriteLine($"Products: count = {products.Count()}, start = {start}, end = {end}, duration = {end - start}");

                var responseSting = await response.Content.ReadAsStringAsync();

                butchInsertProductResponse = JsonConvert.DeserializeObject <ButchInsertProductResponse>(responseSting);
            }

            return(butchInsertProductResponse);
        }
Esempio n. 14
0
        private async Task <ButchInsertProductAttributeTermResponse> InsertBatchProductAttributeTerms(IEnumerable <ZlBrand> brands, string woocommerceUrl, string consumerKey, string consumerSecret, int attributeId)
        {
            ButchInsertProductAttributeTermResponse attributeTermResponse = null;

            var requestUrl  = $"{woocommerceUrl}/wp-json/wc/v3/products/attributes/{attributeId}/terms/batch";
            var oAuthClient = OAuthRequest.ForRequestToken(consumerKey, consumerSecret);

            oAuthClient.RequestUrl = requestUrl;
            oAuthClient.Method     = "POST";
            var auth = oAuthClient.GetAuthorizationHeader();

            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("Authorization", auth);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*"));
                client.DefaultRequestHeaders.UserAgent.ParseAdd("PostmanRuntime/7.26.8");
                client.DefaultRequestHeaders.Connection.Add("keep-alive");
                client.Timeout = new TimeSpan(1, 0, 0);

                var requestBody = JsonConvert.SerializeObject(new ButchInsertProductAttributeTermRequest
                {
                    Delete = new List <object>(),
                    Update = new List <object>(),
                    Create = brands.Select(br => new WooProductAttributeTermRequest
                    {
                        Name = br.Name
                    }).ToList()
                });

                var response = await client.PostAsync(requestUrl, new StringContent(requestBody, Encoding.UTF8, "application/json"));

                var responseStr = await response.Content.ReadAsStringAsync();

                attributeTermResponse = JsonConvert.DeserializeObject <ButchInsertProductAttributeTermResponse>(responseStr);
            }

            return(attributeTermResponse);
        }
Esempio n. 15
0
        public void Can_get_request_token_with_query()
        {
            var client = OAuthRequest.ForRequestToken(_consumerKey, _consumerSecret, _callbackUrl);

            client.RequestUrl = string.Format(_baseUrl, "request_token");

            var auth = client.GetAuthorizationQuery();

            var url = client.RequestUrl + "?" + auth;

            var request = (HttpWebRequest)WebRequest.Create(url);

            HttpWebResponse response;

            try
            {
                response = (HttpWebResponse)request.GetResponse();

                var reader  = new StreamReader(response.GetResponseStream());
                var content = reader.ReadToEnd();
            }
            catch (System.Exception ex)
            {
                if (ex is WebException wex)
                {
                    var reader = new StreamReader(wex.Response.GetResponseStream());
                    _ = reader.ReadToEnd();
                }

                throw;
            }

            Assert.IsNotNull(response);

            Assert.AreEqual(200, (int)response.StatusCode);
        }
Esempio n. 16
0
        private object request(string method, string endpoint, NameValueCollection parameters = null)
        {
            // Normalize method string
            method = method.ToUpper();

            // Build an empty collection for parameters (if necessary)
            if (parameters == null)
            {
                parameters = new NameValueCollection();
            }

            // can't have null parameters, or oauth signing will barf
            foreach (String key in parameters.AllKeys)
            {
                if (parameters[key] == null)
                {
                    parameters[key] = "";
                }
            }

            var client = OAuthRequest.ForRequestToken(this.consumerKey, this.consumerSecret);

            client.RequestUrl = this.baseUrl + endpoint;
            client.Method     = method;

            string auth = client.GetAuthorizationHeader(parameters);

            // FIXME: OAuth library puts extraneous comma at end, workaround: remove it if present
            auth = auth.TrimEnd(new char[] { ',' });

            using (WebClientProxy wClient = (WebClientProxy)Activator.CreateInstance(webClientProxyType)) {
                wClient.Headers.Add("Authorization", auth);
                wClient.Headers.Add("User-Agent",
                                    string.Format("Toopher-DotNet/{0} (DotNet {1})", VERSION, Environment.Version.ToString()));
                if (parameters.Count > 0)
                {
                    wClient.QueryString = parameters;
                }

                string response;
                try {
                    if (method.Equals("POST"))
                    {
                        var responseArray = wClient.UploadValues(client.RequestUrl, client.Method, parameters);
                        response = Encoding.UTF8.GetString(responseArray);
                    }
                    else
                    {
                        response = wClient.DownloadString(client.RequestUrl);
                    }
                } catch (WebException wex) {
                    IHttpWebResponse httpResp = HttpWebResponseWrapper.create(wex.Response);
                    string           error_message;
                    using (Stream stream = httpResp.GetResponseStream()) {
                        StreamReader reader = new StreamReader(stream, Encoding.UTF8);
                        error_message = reader.ReadToEnd();
                    }

                    String statusLine = httpResp.StatusCode.ToString() + " : " + httpResp.StatusDescription;

                    if (String.IsNullOrEmpty(error_message))
                    {
                        throw new RequestError(statusLine);
                    }
                    else
                    {
                        try {
                            // Attempt to parse JSON response
                            var json = (JsonObject)SimpleJson.SimpleJson.DeserializeObject(error_message);
                            parseRequestError(json);
                        } catch (RequestError e) {
                            throw e;
                        } catch (Exception) {
                            throw new RequestError(statusLine + " : " + error_message);
                        }
                    }

                    throw new RequestError(error_message, wex);
                }

                try {
                    return(SimpleJson.SimpleJson.DeserializeObject(response));
                } catch (Exception ex) {
                    throw new RequestError("Could not parse response", ex);
                }
            }
        }
Esempio n. 17
0
        private static OAuthCredentials GenerateOAuthAccessToken(string consumerKey, string secret)
        {
            string baseUrl      = "http://api.smugmug.com";
            string requestUrl   = "/services/oauth/1.0a/getRequestToken";
            string authorizeUrl = "/services/oauth/1.0a/authorize";
            string accessUrl    = "/services/oauth/1.0a/getAccessToken";

            string requestToken       = null;
            string requestTokenSecret = null;
            string accesstoken        = null;
            string accessTokenSecret  = null;

            #region Request Token
            OAuthRequest oAuthRequest = OAuthRequest.ForRequestToken(consumerKey, secret, "oob");
            oAuthRequest.RequestUrl = baseUrl + requestUrl;
            string         auth    = oAuthRequest.GetAuthorizationHeader();
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(oAuthRequest.RequestUrl);
            request.Headers.Add("Authorization", auth);
            HttpWebResponse response       = (HttpWebResponse)request.GetResponse();
            Stream          responseStream = response.GetResponseStream();
            StreamReader    readStream     = new StreamReader(responseStream, System.Text.Encoding.UTF8);
            string          result         = readStream.ReadToEnd();
            foreach (string token in result.Split('&'))
            {
                string[] splitToken = token.Split('=');

                switch (splitToken[0])
                {
                case "oauth_token":
                    requestToken = splitToken[1];
                    break;

                case "oauth_token_secret":
                    requestTokenSecret = splitToken[1];
                    break;

                default:
                    break;
                }
            }
            response.Close();
            #endregion

            #region Authorization
            string authorizationUrl = String.Format("{0}{1}?mode=auth_req_token&oauth_token={2}&Access=Full&Permissions=Modify", baseUrl, authorizeUrl, requestToken);
            System.Diagnostics.Process.Start(authorizationUrl);

            Console.WriteLine("Enter the six-digit code: ");
            string verifier = Console.ReadLine();
            #endregion

            #region Access Token
            oAuthRequest            = OAuthRequest.ForAccessToken(consumerKey, secret, requestToken, requestTokenSecret, verifier);
            oAuthRequest.RequestUrl = baseUrl + accessUrl;
            auth    = oAuthRequest.GetAuthorizationHeader();
            request = (HttpWebRequest)WebRequest.Create(oAuthRequest.RequestUrl);
            request.Headers.Add("Authorization", auth);
            response       = (HttpWebResponse)request.GetResponse();
            responseStream = response.GetResponseStream();
            readStream     = new StreamReader(responseStream, System.Text.Encoding.UTF8);
            result         = readStream.ReadToEnd();
            foreach (string token in result.Split('&'))
            {
                string[] splitToken = token.Split('=');

                switch (splitToken[0])
                {
                case "oauth_token":
                    accesstoken = splitToken[1];
                    break;

                case "oauth_token_secret":
                    accessTokenSecret = splitToken[1];
                    break;

                default:
                    break;
                }
            }
            response.Close();
            #endregion

            return(new OAuthCredentials(consumerKey, secret, accesstoken, accessTokenSecret));
        }