-
-
Notifications
You must be signed in to change notification settings - Fork 599
Bojan Stefanovic edited this page Apr 17, 2018
·
8 revisions
- Instagram works only with the http callback URL: API with only HTTP scheme into callback URL
- Using "Client-Side (Implicit) Authentication"
- You must use responseType "token"
- Also, be sure to uncheck the "Disable implicit OAuth" box or else this method will not work.
- The Access token will be accessed from the URL fragment: http://your-redirect-uri#access_token=ACCESS-TOKEN
- Use the internal web web browser technique to access the token. (See the demo app on how to do it in the webview delegate). The server redirect technique won't work as the token is in a url fragment which doesn't make it into the URL when calling a server app.
Swift
let oAuthRedirectUrl = "http://your_server/the_php_script"
let instagram = OAuth2Swift(
consumerKey: "key",
consumerSecret: "secret",
authorizeUrl: "https://api.instagram.com/oauth/authorize",
responseType: "code" // important! Must be "code" for server-side. Client-side does not work for Instagram due to url fragment
)
...
self.instagram.authorizeURLHandler = SafariURLHandler(viewController: vc, oauthSwift: instagram)
let handle = self.instagram.authorize(
withCallbackURL: URL(string: self.oAuthRedirectUrl)!,
scope: "public_content", state: "INSTAGRAM\(arc4random())",
success: { credential, response, parameters in
// TODO: Save params to UserDefaults
print(parameters)
print("AUTHORIZED INSTAGRAM === \(credential.oauthToken) ")
}, failure: { error in
print(error)
print("OAUTH FAILURE: " + error.localizedDescription)
})
PHP:
<?php
$code = $_GET['code'];
if($code == "")
DIE("ERROR");
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => "https://api.instagram.com/oauth/access_token",
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => array(
client_id => "client_key",
client_secret => "client_secret",
grant_type => "authorization_code",
redirect_uri => "http://your_server/this_script_url_same_as_above",
code => $code
)
));
$resp = curl_exec($curl);
curl_close($curl);
if(!$resp || $resp === ""){
header("Location: your-app-name://oauth-swift/instagram?error=1&error_description=Sorry,%20there%20was%20an%20error");
die;
}
$json = json_decode($resp, true);
$accessToken = $json["access_token"];
$userId = $json["user"]["id"];
$userName = $json["user"]["username"];
header("Location: your-app-name://oauth-swift/instagram?access_token=$accessToken&user_id=$userId&username=$userName");
?>
[ [ [