Created
March 26, 2016 16:36
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$auth_redirect = $modx->makeUrl($modx->resource->id, '', '', 'full'); | |
// token | |
if (isset($_GET['code'])) { | |
$code = $_GET['code']; | |
$ctx = stream_context_create(array( | |
'http' => array( | |
'method' => 'POST', | |
'header' => 'Content-type: application/x-www-form-urlencoded', | |
'content' => http_build_query(array( | |
'client_id' => $client_id, | |
'client_secret' => $client_secret, | |
'grant_type' => 'authorization_code', | |
'redirect_uri' => $auth_redirect, | |
'code' => $code | |
)) | |
) | |
)); | |
$response = file_get_contents('https://api.instagram.com/oauth/access_token', false, $ctx); | |
$json = json_decode($response, true); | |
if (isset($json['access_token'])) { | |
$token = $json['access_token']; | |
$modx->runProcessor('system/settings/update', array( | |
'key' => 'insta_token', | |
'value' => $token, | |
'namespace' => 'core' | |
)); | |
$modx->setOption('insta_token', $token); | |
echo 'access granted'; | |
} else { | |
$modx->log(xPDO::LOG_LEVEL_ERROR,'[Insta] Error retrieving token.'); | |
} | |
return; | |
} | |
// auth | |
if (!isset($_GET['fetch'])) { | |
$authUrl = 'https://api.instagram.com/oauth/authorize/?' . http_build_query(array( | |
'client_id' => $client_id, | |
'redirect_uri' => $auth_redirect, | |
'scope' => 'basic public_content', | |
// 'scope' => 'public_content', | |
'response_type' => 'code' | |
)); | |
$modx->sendRedirect($authUrl); | |
return; | |
} | |
if (isset($_GET['fetch'])) { | |
$token = $modx->getOption('insta_token'); | |
if ($token) { | |
$tagUrl = 'https://api.instagram.com/v1/tags/' . $tag_name . '/media/recent?count=12&access_token=' . $token; | |
try { | |
$response = file_get_contents($tagUrl); | |
$json = json_decode($response, true); | |
if (isset($json['data']) && is_array($json['data'])) { | |
$images = array(); | |
foreach ($json['data'] as $image) { | |
if ($image['type'] != 'image') | |
continue; | |
$images[] = array( | |
'src' => $image['images']['low_resolution']['url'], | |
'href' => $image['link'] | |
); | |
} | |
echo json_encode($images); | |
} | |
} catch (Exception $ex) { | |
$modx->log(xPDO::LOG_LEVEL_ERROR,'[Insta] Error fetching media: ' . $ex->getMessage()); | |
} | |
} else { | |
$modx->log(xPDO::LOG_LEVEL_ERROR,'[Insta] Authentication required.'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment