Wednesday, December 11, 2013

Using the Shopify API from .NET

If you're looking for a way to talk to Shopify from .NET (either C# or VB.NET), you'll probably come across this "lightweight" .NET client.

Word of warning: it's 10 MB, and pretty hard-core.

If you're writing a private app (as opposed to a public one), things are much simpler; you don't need all the OAuth stuff for starters. After a bit of trial and error, I got this to work:

public string GetCustomers()
{
const string url = "https://your-store.myshopify.com/admin/customers.json";
var req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "GET";
req.ContentType = "application/json";
req.Credentials = GetCredential(url);
req.PreAuthenticate = true;
using (var resp = (HttpWebResponse)req.GetResponse())
{
if (resp.StatusCode != HttpStatusCode.OK)
{
string message = String.Format("Call failed. Received HTTP {0}", resp.StatusCode);
throw new ApplicationException(message);
}
var sr = new StreamReader(resp.GetResponseStream());
return sr.ReadToEnd();
}
}
private static CredentialCache GetCredential(string url)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
var credentialCache = new CredentialCache();
credentialCache.Add(new Uri(url), "Basic", new NetworkCredential("your-api-key", "your-password"));
return credentialCache;
}



To generate an API key and password, go to http://your-store.myshopify.com/admin/apps, and click "Create a private API key" at the bottom.

6 comments:

  1. Hello,
    I have used this for fetching my shopify store details like customers, orders datas for the .net windows service through the above code..
    Its works awesomely..
    Thanks to U sir...

    ReplyDelete
  2. Hi,
    I tried above code but i got error ''The request was aborted: Could not create SSL/TLS secure channel.'' please help me.

    ReplyDelete
  3. @Vikram: you need to add this line to enable SSL/TLS:

    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

    ReplyDelete
  4. This works great! Thanks ever so much!

    ReplyDelete
  5. hi i tried this but unable to run it.. "couldn't locate the web.config file".. Please help me in this

    ReplyDelete