I am trying to integrate "tumblr" into my application.I am able to get the access token successfully. But, when I try to post, I am getting the following error
{"meta":{"status":401,"msg":"Not Authorized"},"response":[]}
I am using the OAuthConsumer client for iOS, which I have pulled if from MGTwitterEngine.
This is what I have tried.
#import "ViewController.h"
#define consumer_key #"u9iZvT8KIlrTtUrh3vUeXXXXXXXXXXXXXAfgpThGyom8Y6MKKCnU"
#define consumer_secret #"xfA10mQKmALlpsnrFXXXXXXXXXXXXXXXXXXXXXXXXXX"
#define request_token_url #"http://www.tumblr.com/oauth/request_token"
#define access_token_url #"http://www.tumblr.com/oauth/access_token"
#define authorize_url #"http://www.tumblr.com/oauth/authorize?oauth_token=%#"
#define base_url #"http://api.tumblr.com/v2/user/XXXXXXXXXXXXX.tumblr.com/info"
#define user_info #"http://api.tumblr.com/v2/user/info"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (IBAction)postIt:(id)sender
{
NSURL *postURL = [NSURL URLWithString:#"http://api.tumblr.com/v2/blog/xxxxxxxx.tumblr.com/post"];
OAMutableURLRequest *oRequest = [[OAMutableURLRequest alloc] initWithURL:postURL
consumer:self.consumer
token:self.accessToken
realm:nil
signatureProvider:nil];
[oRequest setHTTPMethod:#"POST"];
[oRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
OARequestParameter *statusParam = [[OARequestParameter alloc] initWithName:#"body"
value:#"Sample Body"];
OARequestParameter *statusParam2 = [[OARequestParameter alloc] initWithName:#"type"
value:#"text"];
NSArray *params = [NSArray arrayWithObjects:statusParam,statusParam2, nil];
[oRequest setParameters:params];
OAAsynchronousDataFetcher *fetcher = [OAAsynchronousDataFetcher asynchronousFetcherWithRequest:oRequest
delegate:self
didFinishSelector:#selector(sendStatusTicket:didFinishWithData:)
didFailSelector:#selector(sendStatusTicket:didFailWithError:)];
NSLog(#"URL = %#",[oRequest.URL absoluteString]);
[fetcher start];
}
- (void)didReceiveAccessToken:(OAServiceTicket *)ticker data:(NSData *)responseData
{
}
- (void)webView:(UIWebView*)webView didFailLoadWithError:(NSError*)error {
// ERROR!
}
- (void)sendStatusTicket:(OAServiceTicket *)ticker didFinishWithData:(NSData *)responseData
{
if (ticker.didSucceed) {
NSLog(#"Success");
}
NSString *responseBody = [[NSString alloc] initWithData:responseData
encoding:NSUTF8StringEncoding];
NSLog(#"Description = %#",responseBody);
}
- (void)sendStatusTicket:(OAServiceTicket *)ticker didFailWithError:(NSError *)error
{
NSLog(#"Error = %#",[error localizedDescription]);
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
- (IBAction)login:(id)sender
{
self.consumer = [[OAConsumer alloc] initWithKey:consumer_key secret:consumer_secret];
NSURL *url = [NSURL URLWithString:request_token_url];
OAMutableURLRequest *request = [[OAMutableURLRequest alloc] initWithURL:url
consumer:self.consumer
token:nil // we don't have a Token yet
realm:nil // our service provider doesn't specify a realm
signatureProvider:nil]; // use the default method, HMAC-SHA1
[request setHTTPMethod:#"POST"];
OADataFetcher *fetcher = [[OADataFetcher alloc] init];
[fetcher fetchDataWithRequest:request
delegate:self
didFinishSelector:#selector(requestTokenTicket:didFinishWithData:)
didFailSelector:#selector(requestTokenTicket:didFailWithError:)];
}
- (void)requestTokenTicket:(OAServiceTicket *)ticket didFinishWithData:(NSData *)data {
if (ticket.didSucceed)
{
NSString *responseBody = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
self.accessToken= [[OAToken alloc] initWithHTTPResponseBody:responseBody];
NSURL *author_url = [NSURL URLWithString:[ NSString stringWithFormat:authorize_url,self.accessToken.key]];
OAMutableURLRequest *oaR = [[OAMutableURLRequest alloc] initWithURL:author_url consumer:nil token:nil realm:nil signatureProvider:nil];
UIWebView *webView =[[UIWebView alloc] initWithFrame:[UIScreen mainScreen].bounds];
[[[UIApplication sharedApplication] keyWindow] addSubview:webView];
webView.delegate=self;
[webView loadRequest:oaR];
}
}
// This is to get oAuth_verifier from the url
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
NSString *url = [[request URL] absoluteString];
NSString *keyOne = #"oauth_token";
NSString *keyTwo = #"oauth_verifier";
NSRange r1 =[url rangeOfString:keyOne];
NSRange r2 =[url rangeOfString:keyTwo];
if (r1.location!=NSNotFound && r2.location!=NSNotFound) {
// Extract oauth_verifier from URL query
NSString* verifier = nil;
NSArray* urlParams = [[[request URL] query] componentsSeparatedByString:#"&"];
for (NSString* param in urlParams) {
NSArray* keyValue = [param componentsSeparatedByString:#"="];
NSString* key = [keyValue objectAtIndex:0];
if ([key isEqualToString:#"oauth_verifier"]) {
verifier = [keyValue objectAtIndex:1];
break;
}
}
if (verifier) {
NSURL* accessTokenUrl = [NSURL URLWithString:#"http://www.tumblr.com/oauth/access_token"];
OAMutableURLRequest* accessTokenRequest =[[OAMutableURLRequest alloc] initWithURL:accessTokenUrl
consumer:self.consumer
token:self.accessToken
realm:nil
signatureProvider:nil];
OARequestParameter* verifierParam =[[OARequestParameter alloc] initWithName:#"oauth_verifier" value:verifier];
[accessTokenRequest setHTTPMethod:#"POST"];
[accessTokenRequest setParameters:[NSArray arrayWithObjects:verifierParam,nil]];
OADataFetcher* dataFetcher = [[OADataFetcher alloc] init];
[dataFetcher fetchDataWithRequest:accessTokenRequest
delegate:self
didFinishSelector:#selector(requestTokenTicketForAuthorization:didFinishWithData:)
didFailSelector:#selector(requestTokenTicket:didFailWithError:)];
} else {
// ERROR!
}
[webView removeFromSuperview];
return NO;
}
return YES;
}
- (void)requestTokenTicketForAuthorization:(OAServiceTicket *)ticket didFinishWithData:(NSData *)data
{
if (ticket.didSucceed)
{
NSString *responseBody = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
self.accessToken = [self.accessToken initWithHTTPResponseBody:responseBody];
accessText=self.accessToken.key;
accessSecret=self.accessToken.secret;
}
else
{
NSString *responseBody = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
NSLog(#"Response = %#",responseBody);
}
}
- (void)requestTokenTicket:(OAServiceTicket *)ticket didFailWithError:(NSError *)error
{
NSLog(#"Error = %#",[error localizedDescription]);
}
#end
Whats the mistake I am making here? Why I am getting that error? Did I follow the steps properly?
Please XXX out your consumer_key and consumer_secret to avoid unwanted use of them.
Code wise there are a few things you might want to look for here.
Are you able to use an oauth 'GET' request such as "http://api.tumblr.com/v2/user/info"?
If you can receive a successful 'GET' request then your access token is valid and you can look at how you're sending your post parameters.
Make sure you are passing in your parameters as HTTP Body as well as signature parameters. Correct parameter ordering is likely provided by the library.
NSString *postbody = #"body=myBodyText&type=text";
[oRequest setHTTPBody:[postbody dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:TRUE]];
Related
I am trying to integrate payu money payment gateway in my app.
Payumoney collect all information and done transaction and return back to my custom defined url webpage.
My problem is how to get the response code after successful transaction from payu money gateway?
int i = arc4random() % 9999999999;
NSString *strHash = [self createSHA512:[NSString stringWithFormat:#"%d%#",i,[NSDate date]]];
NSString *txnid1 = [strHash substringToIndex:20];
NSLog(#"tnx1 id %#",txnid1);
// NSString *key = #"JBZaLc";
// NSString* salt = #"GQs7yium";
NSString *key = #"gtKFFx";
NSString* salt = #"eCwWELxi";
NSString *amount = dataMoney.usrAmount;
NSString *productInfo = #"App Products Info ";
NSString *firstname = dataMoney.usrName;
NSString *email = dataMoney.usrEmail;
NSString *phone = dataMoney.usrMobile;
NSString *surl = #"https://dl.dropboxusercontent.com/s/dtnvwz5p4uymjvg/success.html";
NSString *furl = #"https://dl.dropboxusercontent.com/s/z69y7fupciqzr7x/furlWithParams.html";
NSString *hashValue = [NSString stringWithFormat:#"%#|%#|%#|%#|%#|%#|||||||||||%#",key,txnid1,amount,productInfo,firstname,email,salt];
NSString *hash = [self createSHA512:hashValue];
NSDictionary *parameters = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:txnid1,key,amount,productInfo,firstname,email,phone,surl,furl,hash, nil] forKeys:[NSArray arrayWithObjects:#"txnid",#"key",#"amount",#"productinfo",#"firstname",#"email",#"phone",#"surl",#"furl",#"hash", nil]];
__block NSString *post = #"";
[parameters enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
if ([post isEqualToString:#""]) {
post = [NSString stringWithFormat:#"%#=%#",key,obj];
}else{
post = [NSString stringWithFormat:#"%#&%#=%#",post,key,obj];
}
}];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"https://test.payu.in/_payment"]]];
// change URL for live
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
[request setHTTPBody:postData];
[web_view_PayU loadRequest:request];
#define Merchant_Key #"your merchant key "
#define Salt #"your salt key"
#define Base_URL #"https://secure.payu.in"
> //this base url in case of origional payment key's if you want to integarate with
test key's write base Url can check in payumoney Faq
**
#define Success_URL #"https://www.google.co.in/"
#define Failure_URL #"http://www.bing.com/"
#define Product_Info #"Denim Jeans"
#define Paid_Amount #"1549.00"
#define Payee_Name #"Suraj Mirajkar"
-(void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:YES];
[self setTitle:#"Make A Payment"];
[self initPayment];
}
- (void)viewDidLoad {
[super viewDidLoad];
activityIndicatorView = [[UIActivityIndicatorView alloc] init];
activityIndicatorView.center = self.view.center;
[activityIndicatorView setColor:[UIColor blackColor]];
[self.view addSubview:activityIndicatorView];
}
-(void)initPayment {
int i = arc4random() % 9999999999;
NSString *strHash = [self createSHA512:[NSString stringWithFormat:#"%d%#",i,[NSDate date]]];// Generatehash512(rnd.ToString() + DateTime.Now);
NSString *txnid1 = [strHash substringToIndex:20];
strMIHPayID = txnid1;
NSString *key = Merchant_Key;
NSString *amount =[[NSUserDefaults standardUserDefaults]
stringForKey:#"orderprice"];
//NSString *amount = Paid_Amount;
NSString *productInfo = Product_Info;
NSString *firstname = Payee_Name;
NSString *email = [NSString stringWithFormat:#"suraj%d#yopmail.com",i];
//ADD A fake mail For Payment for testing purpose
// Generated a fake mail id for testing
NSString *phone = #"9762159571";
NSString *serviceprovider = #"payu_paisa";
NSString *hashValue = [NSString stringWithFormat:#"%#|%#|%#|%#|%#|%#|||||||||||%#",key,txnid1,amount,productInfo,firstname,email,Salt];
NSString *hash = [self createSHA512:hashValue];
NSDictionary *parameters = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:txnid1,key,amount,productInfo,firstname,email,phone,Success_URL,Failure_URL,hash,serviceprovider
, nil] forKeys:[NSArray arrayWithObjects:#"txnid",#"key",#"amount",#"productinfo",#"firstname",#"email",#"phone",#"surl",#"furl",#"hash",#"service_provider", nil]];
NSLog(#"%#",parameters);
__block NSString *post = #"";
[parameters enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
if ([post isEqualToString:#""]) {
post = [NSString stringWithFormat:#"%#=%#",key,obj];
} else {
post = [NSString stringWithFormat:#"%#&%#=%#",post,key,obj];
}
}];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#/_payment",Base_URL]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
[request setHTTPBody:postData];
[_webviewPaymentPage loadRequest:request];
[activityIndicatorView startAnimating];
}
-(NSString *)createSHA512:(NSString *)string {
const char *cstr = [string cStringUsingEncoding:NSUTF8StringEncoding];
NSData *data = [NSData dataWithBytes:cstr length:string.length];
uint8_t digest[CC_SHA512_DIGEST_LENGTH];
CC_SHA512(data.bytes, (CC_LONG)data.length, digest);
NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA512_DIGEST_LENGTH * 2];
for(int i = 0; i < CC_SHA512_DIGEST_LENGTH; i++) {
[output appendFormat:#"%02x", digest[i]];
}
return output;
}
#pragma UIWebView - Delegate Methods
-(void)webViewDidStartLoad:(UIWebView *)webView {
NSLog(#"WebView started loading");
}
-(void)webViewDidFinishLoad:(UIWebView *)webView {
[activityIndicatorView stopAnimating];
if (webView.isLoading) {
return;
}
NSURL *requestURL = [[_webviewPaymentPage request] URL];
NSLog(#"WebView finished loading with requestURL: %#",requestURL);
NSString *getStringFromUrl = [NSString stringWithFormat:#"%#",requestURL];
if ([self containsString:getStringFromUrl :Success_URL]) {
[self performSelector:#selector(delayedDidFinish:) withObject:getStringFromUrl afterDelay:0.0];
} else if ([self containsString:getStringFromUrl :Failure_URL]) {
// FAILURE ALERT
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Sorry !!!" message:#"Your transaction failed. Please try again!" delegate:self cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
alert.tag = 1;
[alert show];
}
}
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
[activityIndicatorView stopAnimating];
NSURL *requestURL = [[_webviewPaymentPage request] URL];
NSLog(#"WebView failed loading with requestURL: %# with error: %# & error code: %ld",requestURL, [error localizedDescription], (long)[error code]);
if (error.code == -1009 || error.code == -1003 || error.code == -1001) { //error.code == -999
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Oops !!!" message:#"Please check your internet connection!" delegate:self cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
alert.tag = 1;
[alert show];
}
}
- (void)delayedDidFinish:(NSString *)getStringFromUrl {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSMutableDictionary *mutDictTransactionDetails = [[NSMutableDictionary alloc] init];
[mutDictTransactionDetails setObject:strMIHPayID forKey:#"Transaction_ID"];
[mutDictTransactionDetails setObject:#"Success" forKey:#"Transaction_Status"];
[mutDictTransactionDetails setObject:Payee_Name forKey:#"Payee_Name"];
[mutDictTransactionDetails setObject:Product_Info forKey:#"Product_Info"];
[mutDictTransactionDetails setObject:Paid_Amount forKey:#"Paid_Amount"];
[self navigateToPaymentStatusScreen:mutDictTransactionDetails];
});
}
#pragma UIAlertView - Delegate Method
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if (alertView.tag == 1 && buttonIndex == 0) {
// Navigate to Payment Status Screen
NSMutableDictionary *mutDictTransactionDetails = [[NSMutableDictionary alloc] init];
[mutDictTransactionDetails setObject:Payee_Name forKey:#"Payee_Name"];
[mutDictTransactionDetails setObject:Product_Info forKey:#"Product_Info"];
[mutDictTransactionDetails setObject:Paid_Amount forKey:#"Paid_Amount"];
[mutDictTransactionDetails setObject:strMIHPayID forKey:#"Transaction_ID"];
[mutDictTransactionDetails setObject:#"Failed" forKey:#"Transaction_Status"];
[self navigateToPaymentStatusScreen:mutDictTransactionDetails];
}
}
- (BOOL)containsString: (NSString *)string : (NSString*)substring {
return [string rangeOfString:substring].location != NSNotFound;
}
- (void)navigateToPaymentStatusScreen: (NSMutableDictionary *)mutDictTransactionDetails {
dispatch_async(dispatch_get_main_queue(), ^{
PaymentStatusViewController *paymentStatusViewController = [[UIStoryboard storyboardWithName:#"Main" bundle:nil] instantiateViewControllerWithIdentifier:#"PaymentStatusScreenID"];
paymentStatusViewController.mutDictTransactionDetails = mutDictTransactionDetails;
[self.navigationController pushViewController:paymentStatusViewController animated:YES];
});
}
Important Note : you can check your Merchant key and Salt in seller Dashboard after Login ... Go To my account and check your merchant key and salt
I already successfully integrated Google+ to my iOS app. But with the latest Apple store updates, the app is not allowed to open the browser to initiate the Google authentication using safari so i tried uiwebview for googleplus authentication and i am getting the access token but i cannot able to get the username and email address of the person logged in.Below i added my source,
NSString *client_id = #"***************************";;
NSString *secret = #"*******************************";
NSString *callbakc = #"https://www.example.com/oauth2callback";;
NSString *scope = #"https://www.googleapis.com/auth/userinfo.email+https://www.googleapis.com/auth/userinfo.profile+https://www.google.com/reader/api/0/subscription";
NSString *visibleactions = #"http://schemas.google.com/AddActivity";
#interface MainViewController ()
#end
#implementation MainViewController
#synthesize webview,isLogin,isReader;
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *url = [NSString stringWithFormat:#"https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=%#&redirect_uri=%#&scope=%#&data-requestvisibleactions=%#",client_id,callbakc,scope,visibleactions];
[webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
}
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
// [indicator startAnimating];
NSLog(#"dgfduiussdiff %# ",[[request URL] host]);
if ([[[request URL] host] isEqualToString:#"www.example.com"]) {
// Extract oauth_verifier from URL query
NSString* verifier = nil;
NSArray* urlParams = [[[request URL] query] componentsSeparatedByString:#"&"];
for (NSString* param in urlParams) {
NSArray* keyValue = [param componentsSeparatedByString:#"="];
NSString* key = [keyValue objectAtIndex:0];
if ([key isEqualToString:#"code"]) {
verifier = [keyValue objectAtIndex:1];
NSLog(#"verifier %#",verifier);
break;
}
}
if (verifier) {
NSString *data = [NSString stringWithFormat:#"code=%#&client_id=%#&client_secret=%#&redirect_uri=%#&grant_type=authorization_code", verifier,client_id,secret,callbakc];
NSString *url = [NSString stringWithFormat:#"https://accounts.google.com/o/oauth2/token"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[data dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
receivedData = [[NSMutableData alloc] init];
} else {
// ERROR!
}
[webView removeFromSuperview];
return NO;
}
return YES;
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSError* error;
[receivedData appendData:data];
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:receivedData
options:kNilOptions
error:&error];
NSLog(#"verifier %#",json);
}
- (void)connection:(NSURLConnection *)connection didFailWithError: (NSError *)error{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:[NSString stringWithFormat:#"%#", error]
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *response = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
SBJsonParser *jResponse = [[SBJsonParser alloc]init];
NSDictionary *tokenData = [jResponse objectWithString:response];
// WebServiceSocket *dconnection = [[WebServiceSocket alloc] init];
// dconnection.delegate = self;
NSString *pdata = [NSString stringWithFormat:#"type=3&token=%#&secret=123&login=%#", [tokenData objectForKey:#"refresh_token"], self.isLogin];
// NSString *pdata = [NSString stringWithFormat:#"type=3&token=%#&secret=123&login=%#",[tokenData accessToken.secret,self.isLogin];
// [dconnection fetch:1 withPostdata:pdata withGetData:#"" isSilent:NO];
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:#"Google Access TOken"
message:pdata
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
After executing the above source i getting the below response printed in nslog,
verifier 4/kMcSZ2l-d_XXPo24NSdsMnugoP_MGDGPP4D5C1LRTfY
2015-07-21 18:04:16.103 TechnoGerms.com[8981:189233] verifier {
"access_token" = "ya29.twG9kyMElyC8BgAxujF98WKN0BQ246Ey6zsKQEgSpKsNEb5JOS3QRl12La6XBy1geZnL";
"expires_in" = 3600;
"id_token" = "eyJhbGciOiJSUzI1NiIsImtpZCI6ImRhNjYyNWIzNmJjMDlkMzAwMzUzYjI4YTc0MWNlMTc1MjVhNGMzM2IifQ.eyJpc3MiOiJhY2NvdW50cy5nb29nbGUuY29tIiwic3ViIjoiMTE0MjE4NDEwODI0NzM1ODkyMDg0IiwiYXpwIjoiMTY5NzY2MjI4OTY4LWtoNzI1dTFpZWdzNHN1bnFhOThhcHUxMHU4djhhcmFmLmFwcHMuZ29vZ2xldXNlcmNvbnRlbnQuY29tIiwiZW1haWwiOiJhcmp1bkBsaW5rd2FyZS5pbiIsImF0X2hhc2giOiJQVnJxTURpNDViZnVGTm9kTmlsSFlRIiwiZW1haWxfdmVyaWZpZWQiOnRydWUsImF1ZCI6IjE2OTc2NjIyODk2OC1raDcyNXUxaWVnczRzdW5xYTk4YXB1MTB1OHY4YXJhZi5hcHBzLmdvb2dsZXVzZXJjb250ZW50LmNvbSIsImhkIjoibGlua3dhcmUuaW4iLCJpYXQiOjE0Mzc0ODIwNTUsImV4cCI6MTQzNzQ4NTY1NX0.uSMrV8rOz4T4i5MhiCeQueNVGLv4NBLP-gtOcyow8t4BY9qvUO78sG4y0jPhbclPdX1kUZjzMVTeah2nU9fTYyl50dlj5FzWNy7LyM-a1GC2jEwkgWMgHdRPh6l7dqMrjQ9sU1rF-ZaiWfG7C9VJTJ76uEWRiSKKA9EFQtBil3xBtmDH07UMRxkbri2jBwaCPAWgjU8-dTarrxNESrwrO_nptaRzfGeaTyQBIYCAk6_9deXmblPgteER1OHoa65xb1OVK3ZPeZ3_dj9gjlXSyGp2ho5WIFGf2xRvW4XoROpUYqhLvrS3s-YrrZ8J5X5-3mafrs1qDjJYJogctbW7dg";
"token_type" = Bearer;
}
How i can get the username and email of person logged in by using the access token which i got above ? Please give any suggestions as i dont get any solution on google.
Thanks for your support
if you want to fetch the whole profile of the google+ user, you can use the below URL
https://www.googleapis.com/plus/v1/people/me/?access_token={YOUR_ACCESS_TOKEN}
Then call the GET method. You will be given by an array containing authorized profile details.
Another method is that, if you want to store the authorized users email, its already present in the field as id_token. It is a base64_encoded data with some fields. If you decode the id yo will get some information about the user.For example in your result you found id_token as
eyJhbGciOiJSUzI1NiIsImtpZCI6ImRhNjYyNWIzNmJjMDlkMzAwMzUzYjI4YTc0MWNlMTc1MjVhNGMzM2IifQ.eyJpc3MiOiJhY2NvdW50cy5nb29nbGUuY29tIiwic3ViIjoiMTE0MjE4NDEwODI0NzM1ODkyMDg0IiwiYXpwIjoiMTY5NzY2MjI4OTY4LWtoNzI1dTFpZWdzNHN1bnFhOThhcHUxMHU4djhhcmFmLmFwcHMuZ29vZ2xldXNlcmNvbnRlbnQuY29tIiwiZW1haWwiOiJhcmp1bkBsaW5rd2FyZS5pbiIsImF0X2hhc2giOiJQVnJxTURpNDViZnVGTm9kTmlsSFlRIiwiZW1haWxfdmVyaWZpZWQiOnRydWUsImF1ZCI6IjE2OTc2NjIyODk2OC1raDcyNXUxaWVnczRzdW5xYTk4YXB1MTB1OHY4YXJhZi5hcHBzLmdvb2dsZXVzZXJjb250ZW50LmNvbSIsImhkIjoibGlua3dhcmUuaW4iLCJpYXQiOjE0Mzc0ODIwNTUsImV4cCI6MTQzNzQ4NTY1NX0.uSMrV8rOz4T4i5MhiCeQueNVGLv4NBLP-gtOcyow8t4BY9qvUO78sG4y0jPhbclPdX1kUZjzMVTeah2nU9fTYyl50dlj5FzWNy7LyM-a1GC2jEwkgWMgHdRPh6l7dqMrjQ9sU1rF-ZaiWfG7C9VJTJ76uEWRiSKKA9EFQtBil3xBtmDH07UMRxkbri2jBwaCPAWgjU8-dTarrxNESrwrO_nptaRzfGeaTyQBIYCAk6_9deXmblPgteER1OHoa65xb1OVK3ZPeZ3_dj9gjlXSyGp2ho5WIFGf2xRvW4XoROpUYqhLvrS3s-YrrZ8J5X5-3mafrs1qDjJYJogctbW7dg
The above id_token contains 2 parts separated by '.'. The first part is thebase64_encoded key and the second part is metadata.
you can decode both the data as
$key=base64_decode(eyJhbGciOiJSUzI1NiIsImtpZCI6ImRhNjYyNWIzNmJjMDlkMzAwMzUzYjI4YTc0MWNlMTc1MjVhNGMzM2IifQ)
will give you the key
$data=base64_decode(eyJpc3MiOiJhY2NvdW50cy5nb29nbGUuY29tIiwic3ViIjoiMTE0MjE4NDEwODI0NzM1ODkyMDg0IiwiYXpwIjoiMTY5NzY2MjI4OTY4LWtoNzI1dTFpZWdzNHN1bnFhOThhcHUxMHU4djhhcmFmLmFwcHMuZ29vZ2xldXNlcmNvbnRlbnQuY29tIiwiZW1haWwiOiJhcmp1bkBsaW5rd2FyZS5pbiIsImF0X2hhc2giOiJQVnJxTURpNDViZnVGTm9kTmlsSFlRIiwiZW1haWxfdmVyaWZpZWQiOnRydWUsImF1ZCI6IjE2OTc2NjIyODk2OC1raDcyNXUxaWVnczRzdW5xYTk4YXB1MTB1OHY4YXJhZi5hcHBzLmdvb2dsZXVzZXJjb250ZW50LmNvbSIsImhkIjoibGlua3dhcmUuaW4iLCJpYXQiOjE0Mzc0ODIwNTUsImV4cCI6MTQzNzQ4NTY1NX0.uSMrV8rOz4T4i5MhiCeQueNVGLv4NBLP-gtOcyow8t4BY9qvUO78sG4y0jPhbclPdX1kUZjzMVTeah2nU9fTYyl50dlj5FzWNy7LyM-a1GC2jEwkgWMgHdRPh6l7dqMrjQ9sU1rF-ZaiWfG7C9VJTJ76uEWRiSKKA9EFQtBil3xBtmDH07UMRxkbri2jBwaCPAWgjU8-dTarrxNESrwrO_nptaRzfGeaTyQBIYCAk6_9deXmblPgteER1OHoa65xb1OVK3ZPeZ3_dj9gjlXSyGp2ho5WIFGf2xRvW4XoROpUYqhLvrS3s-YrrZ8J5X5-3mafrs1qDjJYJogctbW7dg)
will give you the metadata.
while decoding the data ,it will give the result as
{"iss":"accounts.google.com","sub":"114218410824735892084","azp":"169766228968-kh725u1iegs4sunqa98apu10u8v8araf.apps.googleusercontent.com","email":"arjun#linkware.in","at_hash":"PVrqMDi45bfuFNodNilHYQ","email_verified":true,"aud":"169766228968-kh725u1iegs4sunqa98apu10u8v8araf.apps.googleusercontent.com","hd":"linkware.in","iat":1437482055,"exp":1437485655}
Above result you can find the email filed. I hope this will help you.
I am using tumbler login authentication via oauth. I am following this url: http://codegerms.com/login-with-tumblr-in-uiwebview-using-xcode-6-part-3/
for login authentication and get Access token and Secret Key for Tumblr API in iOS via login in UIWebview.
I am using this block of code.
- (void)viewDidLoad {
[super viewDidLoad];
// clientID = #"Tjta51N6kF6Oxmm1f3ytpUvMPRAE1bRgCgG90SOa0bJMlSlLeT";
// secret = #"lrlQPNx3Yb1nRxp4qreYXvUURkGUmYCBoQacOmLTDRJAc7awRN";
clientID = #"sdF0Y6bQoJYwfIB1Mp7WECwobAgnq5tmkRjo7OXyKHDg3opY7Y";
secret = #"qJNGrRjyriZBeBhcgJz0MAcD9WAYXUW1tLbLrbYE4ZclzAUH9g";
redirect = #"tumblr://authorized";
[self.WebView setBackgroundColor:[UIColor clearColor]];
[self.WebView setOpaque:NO];
[self connectTumblr];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)connectTumblr {
consumer = [[OAConsumer alloc]initWithKey:clientID secret:secret];
NSURL* requestTokenUrl = [NSURL URLWithString:#"http://www.tumblr.com/oauth/request_token"];
OAMutableURLRequest* requestTokenRequest = [[OAMutableURLRequest alloc] initWithURL:requestTokenUrl
consumer:consumer
token:nil
realm:nil
signatureProvider:nil] ;
OARequestParameter* callbackParam = [[OARequestParameter alloc] initWithName:#"oauth_callback" value:redirect] ;
[requestTokenRequest setHTTPMethod:#"POST"];
[requestTokenRequest setParameters:[NSArray arrayWithObject:callbackParam]];
OADataFetcher* dataFetcher = [[OADataFetcher alloc] init] ;
[dataFetcher fetchDataWithRequest:requestTokenRequest
delegate:self
didFinishSelector:#selector(didReceiveRequestToken:data:)
didFailSelector:#selector(didFailOAuth:error:)];
}
- (void)didReceiveRequestToken:(OAServiceTicket*)ticket data:(NSData*)data {
NSString* httpBody = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
requestToken = [[OAToken alloc] initWithHTTPResponseBody:httpBody];
NSURL* authorizeUrl = [NSURL URLWithString:#"https://www.tumblr.com/oauth/authorize"];
OAMutableURLRequest* authorizeRequest = [[OAMutableURLRequest alloc] initWithURL:authorizeUrl
consumer:nil
token:nil
realm:nil
signatureProvider:nil];
NSString* oauthToken = requestToken.key;
OARequestParameter* oauthTokenParam = [[OARequestParameter alloc] initWithName:#"oauth_token" value:oauthToken] ;
[authorizeRequest setParameters:[NSArray arrayWithObject:oauthTokenParam]];
// UIWebView* webView = [[UIWebView alloc] initWithFrame:[UIScreen mainScreen].bounds];
// webView.scalesPageToFit = YES;
// [[[UIApplication sharedApplication] keyWindow] addSubview:webView];
// webView.delegate = self;
[self.WebView loadRequest:authorizeRequest];
}
#pragma mark UIWebViewDelegate
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
NSLog(#"scheme: %#",[[request URL] scheme]);
if ([[[request URL] scheme] isEqualToString:#"tumblr"]) {
// Extract oauth_verifier from URL query
NSString* verifier = nil;
NSArray* urlParams = [[[request URL] query] componentsSeparatedByString:#"&"];
for (NSString* param in urlParams) {
NSArray* keyValue = [param componentsSeparatedByString:#"="];
NSString* key = [keyValue objectAtIndex:0];
if ([key isEqualToString:#"oauth_verifier"]) {
verifier = [keyValue objectAtIndex:1];
break;
}
}
if (verifier) {
NSURL* accessTokenUrl = [NSURL URLWithString:#"https://www.tumblr.com/oauth/access_token"];
OAMutableURLRequest* accessTokenRequest = [[OAMutableURLRequest alloc] initWithURL:accessTokenUrl
consumer:consumer
token:requestToken
realm:nil
signatureProvider:nil];
OARequestParameter* verifierParam = [[OARequestParameter alloc] initWithName:#"oauth_verifier" value:verifier];
[accessTokenRequest setHTTPMethod:#"POST"];
[accessTokenRequest setParameters:[NSArray arrayWithObject:verifierParam]];
OADataFetcher* dataFetcher = [[OADataFetcher alloc] init];
[dataFetcher fetchDataWithRequest:accessTokenRequest
delegate:self
didFinishSelector:#selector(didReceiveAccessToken:data:)
didFailSelector:#selector(didFailOAuth:error:)];
} else {
// ERROR!
}
[webView removeFromSuperview];
return NO;
}
return YES;
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
NSLog(#"webView error: %#",error);
// ERROR!
}
- (void)webViewDidStartLoad:(UIWebView *)webView {
[spinner setHidden:NO];
[spinner startAnimating];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView {
[spinner setHidden:YES];
[spinner stopAnimating];
}
- (void)didReceiveAccessToken:(OAServiceTicket*)ticket data:(NSData*)data {
NSString* httpBody = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
accessToken = [[OAToken alloc] initWithHTTPResponseBody:httpBody];
NSString *OAuthKey = accessToken.key; // HERE YOU WILL GET ACCESS TOKEN
NSString *OAuthSecret = accessToken.secret; //HERE YOU WILL GET SECRET TOKEN
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:#"Tumblr Token"
message:OAuthSecret
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
Every thing is working fine but when logged in then
if ([[[request URL] scheme] isEqualToString:#"tumblr"]) {
}
should called in shouldStartLoadWithRequest delegate method
but the given condition is not satisfied. so that I am unable to verify oauth_verifier and unable to get accessToken.
Please Advice Thanks.
You must be use https instead of http for every url of Tumblr.It will work perfectly.
Thanks.
I have integrated google plus in my ios app ,I am able to get access token.I have used authentication flow to integrate google plus.So now after getting access token how can i get user profile details like username, email id, profile pic etc?
My code to get access token is as below:
-(IBAction)btnGooglePlusClicked:(UIButton *)sender
{
IBwebView.hidden = FALSE;
NSString *url = [NSString stringWithFormat:#"https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=%#&redirect_uri=%#&scope=%#&data-requestvisibleactions=%#",GOOGLE_PLUS_CLIENT_ID,GOOGLE_PLUS_CALL_BACK_URL,GOOGLE_PLUS_SCOPE,GOOGLE_PLUS_VISIBLE_ACTIONS];
[IBwebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
}
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
// [indicator startAnimating];
if ([[[request URL] host] isEqualToString:#"localhost"]) {
// Extract oauth_verifier from URL query
NSString* verifier = nil;
NSArray* urlParams = [[[request URL] query] componentsSeparatedByString:#"&"];
for (NSString* param in urlParams) {
NSArray* keyValue = [param componentsSeparatedByString:#"="];
NSString* key = [keyValue objectAtIndex:0];
if ([key isEqualToString:#"code"]) {
verifier = [keyValue objectAtIndex:1];
NSLog(#"verifier %#",verifier);
break;
}
}
if (verifier) {
NSString *data = [NSString stringWithFormat:#"code=%#&client_id=%#&client_secret=%#&redirect_uri=%#&grant_type=authorization_code", verifier,GOOGLE_PLUS_CLIENT_ID,GOOGLE_PLUS_CLIENT_SECRET,GOOGLE_PLUS_CALL_BACK_URL];
NSString *url = [NSString stringWithFormat:#"https://accounts.google.com/o/oauth2/token"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[data dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
receivedData = [[NSMutableData alloc] init];
} else {
// ERROR!
}
[webView removeFromSuperview];
return NO;
}
return YES;
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[receivedData appendData:data];
NSLog(#"verifier %#",receivedData);
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:[NSString stringWithFormat:#"%#", error]
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *response = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
SBJsonParser *jResponse = [[SBJsonParser alloc]init];
NSDictionary *tokenData = [jResponse objectWithString:response];
// WebServiceSocket *dconnection = [[WebServiceSocket alloc] init];
// dconnection.delegate = self;
NSString *pdata = [NSString stringWithFormat:#"type=3&token=%#&secret=123&login=%#", [tokenData objectForKey:#"refresh_token"], self.isLogin];
// NSString *pdata = [NSString stringWithFormat:#"type=3&token=%#&secret=123&login=%#",[tokenData accessToken.secret,self.isLogin];
// [dconnection fetch:1 withPostdata:pdata withGetData:#"" isSilent:NO];
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:#"Google Access TOken"
message:pdata
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
I feel the the method you are using will not help to get the profile detail.
I suggest to use the proper method which ensures the best results.
Please check this out : https://developers.google.com/+/mobile/ios/
This will surely help you to get required outcome.
Hi I want share text in LinkedIn through my app. My code is below here...
This method when I click the btn linkedIn share..
- (void)linkedBtnEvent
{
if(oAuthLoginView != nil) {
oAuthLoginView.delegate = nil;
oAuthLoginView = nil;
}
oAuthLoginView = [[OAuthLoginView alloc] initWithNibName:nil bundle:nil];
oAuthLoginView.delegate=self;
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(loginViewDidFinish:)
name:#"loginViewDidFinish"
object:self.oAuthLoginView];
[self presentViewController:self.oAuthLoginView animated:YES completion:nil];
}
This are the method to handle share after login..
-(void) loginViewDidFinish:(NSNotification*)notification
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
[self profileApiCall];
}
- (void)profileApiCall
{
NSURL *url = [NSURL URLWithString:#"https://api.linkedin.com/v1/people/~"];
OAMutableURLRequest *request =
[[OAMutableURLRequest alloc] initWithURL:url
consumer:oAuthLoginView.consumer
token:oAuthLoginView.accessToken
callback:nil
signatureProvider:nil];
[request setValue:#"json" forHTTPHeaderField:#"x-li-format"];
OADataFetcher *fetcher = [[OADataFetcher alloc] init];
[fetcher fetchDataWithRequest:request
delegate:self
didFinishSelector:#selector(profileApiCallResult:didFinish:)
didFailSelector:#selector(profileApiCallResult:didFail:)];
}
- (void)profileApiCallResult:(OAServiceTicket *)ticket didFinish:(NSData *)data
{
NSString *responseBody = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
NSDictionary *profile = [responseBody objectFromJSONString];
if ( profile )
{
NSLog(#"%#", [[NSString alloc] initWithFormat:#"%# %#",
[profile objectForKey:#"firstName"], [profile objectForKey:#"lastName"]]);
}
// The next thing we want to do is call the network updates
[self networkApiCall];
}
- (void)profileApiCallResult:(OAServiceTicket *)ticket didFail:(NSData *)error
{
NSLog(#"%#",[error description]);
}
- (void)networkApiCall
{
NSURL *url = [NSURL URLWithString:#"https://api.linkedin.com/v1/people/~/network/updates?scope=self&count=1&type=STAT"];
OAMutableURLRequest *request =
[[OAMutableURLRequest alloc] initWithURL:url
consumer:oAuthLoginView.consumer
token:oAuthLoginView.accessToken
callback:nil
signatureProvider:nil];
[request setValue:#"json" forHTTPHeaderField:#"x-li-format"];
OADataFetcher *fetcher = [[OADataFetcher alloc] init];
[fetcher fetchDataWithRequest:request
delegate:self
didFinishSelector:#selector(networkApiCallResult:didFinish:)
didFailSelector:#selector(networkApiCallResult:didFail:)];
}
- (void)networkApiCallResult:(OAServiceTicket *)ticket didFinish:(NSData *)data
{
if (isSharedLinked)
{
NSLog(#"Shared Successfully");
linkedBtn.enabled = NO;
}
else
{
isSharedLinked = YES;
[self performSelector:#selector(postTextLinkedIn) withObject:nil afterDelay:1];
}
}
- (void)networkApiCallResult:(OAServiceTicket *)ticket didFail:(NSData *)error
{
NSLog(#"%#",[error description]);
}
- (void)postTextLinkedIn
{
NSURL *url = [NSURL URLWithString:#"https://api.linkedin.com/v1/people/~/shares"];
OAMutableURLRequest *request =
[[OAMutableURLRequest alloc] initWithURL:url
consumer:oAuthLoginView.consumer
token:oAuthLoginView.accessToken
callback:nil
signatureProvider:nil];
NSDictionary *update = [[NSDictionary alloc] initWithObjectsAndKeys:
[[NSDictionary alloc]
initWithObjectsAndKeys:
#"anyone",#"code",nil], #"visibility",
#"Wow its working... Share the text in Linked In", #"comment", nil];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSString *updateString = [update JSONString];
[request setHTTPBodyWithString:updateString];
[request setHTTPMethod:#"POST"];
OADataFetcher *fetcher = [[OADataFetcher alloc] init];
[fetcher fetchDataWithRequest:request
delegate:self
didFinishSelector:#selector(postUpdateApiCallResult:didFinish:)
didFailSelector:#selector(postUpdateApiCallResult:didFail:)];
}
- (void)postUpdateApiCallResult:(OAServiceTicket *)ticket didFinish:(NSData *)data
{
// The next thing we want to do is call the network updates
[self networkApiCall];
}
- (void)postUpdateApiCallResult:(OAServiceTicket *)ticket didFail:(NSData *)error
{
NSLog(#"%#",[error description]);
}
It shows no error it always haow it share successfully in LinkedIn but no text share in that..
Please help me to fix this issue... I cant figure what mistake I done..
You need to add "rw_nus" in "scope". This only permit the app to share updates... This is your mistake otherwise all your code correct man..
- (void)requestTokenFromProvider
{
OAMutableURLRequest *request =
[[[OAMutableURLRequest alloc] initWithURL:requestTokenURL
consumer:self.consumer
token:nil
callback:linkedInCallbackURL
signatureProvider:nil] autorelease];
[request setHTTPMethod:#"POST"];
OARequestParameter *nameParam = [[OARequestParameter alloc] initWithName:#"scope"
value:#"r_fullprofile+r_contactinfo+r_emailaddress+r_network+r_basicprofile+rw_nus"];
NSArray *params = [NSArray arrayWithObjects:nameParam, nil];
[request setParameters:params];
OARequestParameter * scopeParameter=[OARequestParameter requestParameter:#"scope" value:#"r_fullprofile r_contactinfo r_emailaddress r_network r_fullprofile rw_nus"];
[request setParameters:[NSArray arrayWithObject:scopeParameter]];
OADataFetcher *fetcher = [[[OADataFetcher alloc] init] autorelease];
[fetcher fetchDataWithRequest:request
delegate:self
didFinishSelector:#selector(requestTokenResult:didFinish:)
didFailSelector:#selector(requestTokenResult:didFail:)];
}
Replace this is in your oAuthloginView.m
You can use a great lib for LinkedIn sharing: https://www.cocoacontrols.com/controls/linkedin-share
or directly from GitHub: https://github.com/pmilanez/MIS-Linkedin-Share
It is covered with MIT License and can be used in commercial project as well.
Hope this helps.