Create a Subscription in instagram with c# - c#

I followed this link OAuth 2.0 In .NET With Instagram API, and it helped me fix my issue with getting my access token.
My code is this:
NameValueCollection parameters = new NameValueCollection
{
{"client_id", ClientId},
{"client_secret", ClientSecretId},
{"object", "user"},
{"aspect", "media"},
{"verify_token", "thisIsANormalSubscription"},
{"callback_url", CallbackURI}
};
WebClient client = new WebClient();
var result = client.UploadValues(SubscriptionURI, parameters);
SubscriptionURI = "https://api.instagram.com/v1/subscriptions".
I'm following the guide from instagram(http://instagram.com/developer/realtime/) including all the parameters for the POST request. But I only get the 400 error when it does the client.UploadValues.
PS:This is my first post, so might not be as appealing for the eye as I would wish

if you have your access token you can use this plugin I found, it gets the most recent photos from a user.
Instagram .NET

If you're using the Instasharp Client API (https://github.com/InstaSharp/InstaSharp) you can do something like this:
public InstagramConfig Config
{
get
{
return new InstagramConfig(InstagramAuthorisationModel.ApplicationId, InstagramAuthorisationModel.Secret);
}
}
public void YourSubscribeMethod(string searchTerm)
{
var result = await new Subscription(Config).CreateTag(searchTerm))
}
where InstagramAuthorisationModel is a class that holds your registered application id and secret
You can create subscriptions for Geography, (CreateGeography), User (CreateUser) and (CreateLocation) methods.

Related

How to correctly get access token in ShopifySharp .Net library?

I use https://github.com/nozzlegear/ShopifySharp .Net library to work with Shopify Api. I just create dev webshop and I want to test some GET methods. In documentation I saw next code:
string code = Request.QueryString["code"];
string myShopifyUrl = Request.QueryString["shop"];
string accessToken = await AuthorizationService.Authorize(code, myShopifyUrl, shopifyApiKey, shopifySecretKey);
All parameters I understand except first , what code is this , where I should get it?? Thanks
This is basically Authorization code
It is with respect to concept of "OAuth"
Refer:
https://help.shopify.com/api/getting-started/authentication/oauth
You should create a method in your controller which will receive a callback from Shopify:
public ActionResult Callback(string code, string shop) {
string accessToken = await AuthorizationService.Authorize(code, myShopifyUrl, shopifyApiKey, shopifySecretKey);
}
Then when you building authorization URL, you should set variable redirectUrl to the method above:
//This is the user's store URL.
string usersMyShopifyUrl = "https://example.myshopify.com";
// A URL to redirect the user to after they've confirmed app installation.
// This URL is required, and must be listed in your app's settings in your Shopify app dashboard.
// It's case-sensitive too!
string redirectUrl = "https://example.com/my/redirect/url";
//An array of the Shopify access scopes your application needs to run.
var scopes = new List<AuthorizationScope>()
{
AuthorizationScope.ReadCustomers,
AuthorizationScope.WriteCustomers
};
//Or, use an array of string permissions
var scopes = new List<string>()
{
"read_customers",
"write_customers"
}
//All AuthorizationService methods are static.
string authUrl = AuthorizationService.BuildAuthorizationUrl(scopes, usersMyShopifyUrl, shopifyApiKey, redirectUrl);
And once user will be redirected to authorization URL, it will open Shopify page where user will be able to install app. Then Shopify will redirect him to your callback method with code and shop parameters

Using Facebook SDK to publish on user feed / wall

I'm trying to understand if it is possible to post on the users' wall from my Facebook application.
At the moment I have:
One Facebook app with the permission to write on the users' wall
A BackEnd with Fairbooks SDK Installed
Actually I'm following this approach:
public static string GetToken()
{
var fb = new Facebook.FacebookClient();
dynamic result = fb.Get("oauth/access_token", new
{
client_id = APP_ID,
client_secret = APP_S,
grant_type = "client_credentials"
});
return result.access_token;
}
public static void Post(string Message, long UserID)
{
var token = GetToken();
var client = new FacebookClient(token);
client.Post("/" + UserID + "/photos", new { url = "url", caption = Message });
}
My final goal is to post on facebook when the user interact with my API without client-side popups. Is this possible?
This line of code calls for an application access token
dynamic result = fb.Get("oauth/access_token", new
{
client_id = APP_ID,
client_secret = APP_S,
grant_type = "client_credentials"
});
It makes no sense to use this if you haven't first retrieved a user access token in advance. Only then can you make calls on behalf of the user.
My final goal is to post on facebook when the user interact with my API without client-side popups. Is this possible?
This will never be possible by design. All 3rd party applications must invoke a client-side activity for the user in some format. It cannot be automated.

Shopify and Private Applications

I have created a private app for use on my website (The idea is the website will act as the front end using shopify's api to connect to the store).
When I create the application, if I edit it there is an example url which looks like this:
https://926b44aa1af222f2089ffa4988bc146b:49a28c7ccfa3b29b2a9af8019b2723cc#kudos-6.myshopify.com/admin/products.json
f you click that link, you can see the products I have set up.
Now, if I take that URL and put it into my website using jQuery $.get, I get an error stating Invalid API key or access token (unrecognized login or wrong password which is really infuriating as you can imaging.
I tried to add a header using the ApiPassword which looks like this:
"X-Shopify-Access-Token": "49a28c7ccfa3b29b2a9af8019b2723cc"
But I get the same error.
Now this is probably due to not allowing cross origin headers, etc. So I created a function in c#:
public string Get()
{
using (var wc = new WebClient())
{
return wc.DownloadString("https://926b44aa1af222f2089ffa4988bc146b:49a28c7ccfa3b29b2a9af8019b2723cc#kudos-6.myshopify.com/admin/products.json");
}
}
Which I expected to work, but it doesn't. I get the same error.
So I tried:
public string Get()
{
using (var wc = new WebClient())
{
wc.Headers.Add("X-Shopify-Access-Token", "926b44aa1af222f2089ffa4988bc146b");
return wc.DownloadString("https://926b44aa1af222f2089ffa4988bc146b:49a28c7ccfa3b29b2a9af8019b2723cc#kudos-6.myshopify.com/admin/products.json");
}
}
and guess what, I get the same error.
So I tried using the secret:
public string Get()
{
using (var wc = new WebClient())
{
wc.Headers.Add("X-Shopify-Access-Token", "e63081c23cd05b64205dbdb670d60241");
return wc.DownloadString("https://926b44aa1af222f2089ffa4988bc146b:49a28c7ccfa3b29b2a9af8019b2723cc#kudos-6.myshopify.com/admin/products.json");
}
}
Same error.
Can anyone tell me why?
So, for anyone else having this problem, here is the solution:
First, add these lines to your WebApiConfig:
config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
config.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.None;
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
config.Formatters.Remove(config.Formatters.XmlFormatter);
Then, use your Api password as the access token like this:
public string Get()
{
using (var wc = new WebClient())
{
wc.Headers.Add("X-Shopify-Access-Token", "49a28c7ccfa3b29b2a9af8019b2723cc");
return wc.DownloadString("https://kudos-6.myshopify.com/admin/orders.json");
}
}
and that is it. If you do it like that, it will work.
I had a same issue and fixed it by adding a header information.. I am accessing API through windows service..
So I have created a custom app in Shopify and
I was getting authentication error as I was only passing in API Key and APi password.
You need to attach Admin API token to the header and also use API key and API password.
var restSharpClient = new RestClient(_shopifyBaseStoreURL);
restSharpClient.Authenticator = new HttpBasicAuthenticator(_privateAppAPIKey, _privateAppPassword);
restSharpClient.AddDefaultHeader("X-Shopify-Access-Token", "shpXXXX");
I also added in.when making a GET / PUT request..
restSharpRequest.Method = Method.GET;
restSharpRequest.AddHeader("content-type", "application/json");
restSharpRequest.AddHeader("Accept", "application/json");
restSharpRequest.AddHeader("X - Shopify - Access - Token", "shxxxxxxxxxxxxxxxx");
You can retrieve products using jQuery like this:
$.ajax({
type: 'GET',
url: 'http://yourshop.myshopify.com/products.json',
dataType: 'jsonp',
success: function(data) {
console.log(data);
}
});
You should STOP and quit this pattern while you are ahead. Do you not see the folly of putting your API token with access to your shop in a public website? There is nothing stopping any Tom, Dick or Jane from molesting your shop and ruining your e-commerce day.
Instead, make yourself a front-end that uses an App Proxy to access your backend goods. At least that is secure, and ensures no one can mess with your shop.

Retrieve instagram access token on page load

I want to show my user feed on my website and what I intend to do is to authenticate my own user account each time a user visits the page, and in that way buypass that the user have to log in to his instagram account.
My problem is that I'm having a hard time retrieving the instagram access token through a HttpWebRequest..
See the following NON working code sample:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.instagram.com/oauth/authorize?client_id=xxxxxxxxxxxxxxxxxxxxxx&redirect_uri=http://mywebsite.com&response_type=token");
request.Method = "POST";
request.AllowAutoRedirect = false;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string redirectUrl = response.ResponseUri.ToString();
HttpContext.Current.Response.Write(redirectUrl);
HttpContext.Current.Response.End();
If I paste the url in my browser I get a redirect to http://mysite.com/#access_token=xxxxxxxxxxxxxx and everything seems fine, but when I try to execute the code above, I can't retrieve the correct uri due to some in between redirects before the final url.
Any help would be much appriciated..
I recommend you to use Instasharp library. InstaSharp is a C# library that wraps the Instagram API and makes it easy to write applications with Instagram data. It has a very easy method to get access token for a user. Check its API.
Unfortunately the documentation for Instasharp currently provided has a few errors. I.e. The documentation says OAuthInfo, when such a class does not exist.
Here is some code that works for me.
Notice you don't seem to need to pass a User Object at all (not sure why you would need to anyway)
Also note, that the authenticated and non authenticated methods allow you pass different params, count being the most important one. I've noticed that regardless of the count you pass, an arbitrary number of results is returned, e.g. 33 for authenticated and 13 for authenticated for the same search term. InstagramResult is my wrapper class for the object and Config holds the InstagramAuthorisationModel and InstagramAuthorisationModel holds the static keys created when signing up for a developer account.
public class InstagramService : IInstagramService
...
public InstagramConfig Config
{
get{return new InstagramConfig("https://api.instagram.com/v1", "https://api.instagram.com/oauth", InstagramAuthorisationModel.ApplicationId, InstagramAuthorisationModel.Secret, InstagramAuthorisationModel.RedirectUri);}
}
private AuthInfo UserAuthInfo()
{
return new AuthInfo()
{
// User =new UserInfo(){},
Access_Token = GetInstagramAccessToken()
};
}
public string GetInstagramAccessToken()
{
return _socialMediaRepository.GetInstagramAccessToken(_userApiKey);
}
public List<InstagramResult> Search(string searchTag, int count)
{
var auth = UserAuthInfo();
var tags = new InstaSharp.Endpoints.Tags.Authenticated(Config, auth);
var searchresult = tags.Recent(searchTag);
return searchresult.Data.Select(media => new InstagramResult()
{
Media = media,
image = media.Images.LowResolution.Url
})
.ToList();
}
..

Getting OAuth2 refresh token

I'm trying to use Google's Calendar API to demo out an OAuth2 integration that we'll need to do with another third party. I'm using the DotNetOpenAuth library, and I've been able to get the initial redirect to Google for the Allow / Deny prompt and get the authorization code back.
I now need to get the access token and refresh token, but I only seem to get an access token back, refresh token is null.
This is my controller action method where Google redirects back to after the user Accepts or Denies:
public ActionResult ProcessResponse(string state, string code, string error)
{
var oAuthClient =
new WebServerClient(
new AuthorizationServerDescription
{
TokenEndpoint = new Uri("https://accounts.google.com/o/oauth2/token"),
AuthorizationEndpoint = new Uri("https://accounts.google.com/o/oauth2/auth"),
ProtocolVersion = ProtocolVersion.V20
},
_applicationId,
_secret)
{
AuthorizationTracker = new TokenManager()
};
var authState = oAuthClient.ProcessUserAuthorization();
var accessToken = authState.AccessToken;
var refreshToken = authState.RefreshToken;
return View(new[] { accessToken, refreshToken });
}
Any ideas?
EDIT:
To get the authorization code, I setup the oAuthClient identically to what I did above, and use this method:
oAuthClient.RequestUserAuthorization(new[] { "https://www.googleapis.com/auth/calendar" }, returnUrl);
I had a similar problem, and solved mine by hand-coding the HttpRequest and HttpResponse handling. See code at: https://stackoverflow.com/a/11361759/29156

Categories

Resources