Loading Instagram posts on your website – using Powershell with cURL

Spent some time yesterday including Instagram posts on one of my websites (this one if you’re interested). In order to get this going you need to use cURL, run from a command line, which was new to me. Windows 10 and later allows you to do this from Powershell, but I had to mess around a bit before it works, so here goes if anyone else needs this.

To start off you need to create an Instagram App. The Instagram instructions here are fine, so I won’t go through that.

My trouble started at Step 5 – ‘Exchange the Code for a Token’. Instagram gives this example code:

curl -X POST \
  http://api.instagram.com/oauth/access_token \
  -F client_id=684477648739411 \
  -F client_secret=eb8c7... \
  -F grant_type=authorization_code \
  -F redirect_uri=http://yoursite.com/auth/ \
  -F code=AQDp3TtBQQ...

…but this needs amending to use in Powershell, to:

curl.exe  '-X'  'POST' 'http://api.instagram.com/oauth/access_token' '-F' 'client_id=684477648739411' '-F' 'client_secret=eb8c713c492d1f9c19d7120e94ffcb205' '-F' 'grant_type=authorization_code' '-F' 'redirect_uri=http://www.yoursite.com/' '-F' 'code=AQDp3TtBQQh297S2as5YbDNAU9h3772mvryptCeWWT28z-Xadqq4YfA_YiGXui-cNnLjT7Wg_mrC0OAe0Q5l5x1RvdMarGvFIC1fv7I_kz32oGfKn-R1YlTEyLnPCKksGHeVgw7aJ3iLgXaS8QB9q-WNdG8PiWICz5Icwb4XULBNXs9DONlkIA1i94lNXoKsnkbLL13aMJLGpiiMksitRuZSRblwKrI1dEi7xqeHPcd9VJQ'

This took me about an hour to work out… Similarly, the request for a long-lived token needs to be formatted like this:

curl.exe '-i' '-X' 'GET' 'http://graph.instagram.com/access_token?grant_type=ig_exchange_token&client_secret=eb8c713c492d1f9c19d7120e94ffcb205&access_token=IGQVJYclF4WUllREZABbU9rWm1TS2F0am12cWRUVWxIbURLQXc2eXZAyaTVmNnU5a0ZAFTlU4bkFCOG5sd0JwWFMwZA0VYR0ZAFcnVBZAzZAoVFFwdVN5bmVaWmNGQm42X3VvSEJNc0ZAfWG1zbjB3OThFbm9SNk1wZAHZArOVJVQnQw'

Once you’ve got the access token then you’re off and running. I was using PHP to call the Instagram data from Opencart, so I created a custom module, stored the access token as an Opencart setting and included this code to call Instagram (in a model file, called by the module controller):

	public function getInstagramContents() {
		$fields = "media_type,media_url,permalink,thumbnail_url";//call the fields you want
		$token = $this->config->get('instagram_access_token');//get the stored token
		$limit = 4;//get the four most recent posts
		$json_feed = @file_get_contents($json_feed_url);
		$contents = json_decode($json_feed, true, 512, JSON_BIGINT_AS_STRING);
		return $contents;

If you’ve got this far you’re probably OK with the restof it, but if the rest of the Opencart stuff is useful let me know in the contents below.

Tags: , ,

Useful? Interesting? Leave me a comment

I've yet to find a way of allowing code snippets to be pasted into Wordpress comments - so if you're trying to do this you'd be better off using the contact form.