I am creating an app in which I have to use paypal payment, after successful payment I have to generate payment detail, so I need access token.
I get the method how to get access token, I tried in hurl. It and I successfully get that access token using Client ID and Client Secret. Till this there is no problem.
But when I put those credentials (Client_ID and Client_Secret) in my code it always returns with invalid client credential.
NSURL *URL = [NSURL URLWithString:#"https://api.sandbox.paypal.com/v1/oauth2/token"];
// NSURLRequest *request = [NSURLRequest requestWithURL:URL
// cachePolicy:NSURLRequestUseProtocolCachePolicy
// timeoutInterval:30.0];
NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:URL];
NSString *client_id = #"xxxxxxxxxxxxxx";
NSString *client_secret = #"xxxxxxxxxxxxxx";
[request setHTTPMethod:#"POST"];
NSString *authStr = [NSString stringWithFormat:#"%#:%#", client_id, client_secret];
NSData *authData = [authStr dataUsingEncoding:NSASCIIStringEncoding];
NSString *authValue = [NSString stringWithFormat:#"Basic %#", [authData base64EncodingWithLineLength:80]];
[request setValue:authValue forHTTPHeaderField:#"Authorization"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"en_US" forHTTPHeaderField:#"Accept-Language"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:#"client_credentials",#"grant_type", nil];
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil];
request.HTTPBody = jsonData;
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
Below is the log I prints in didFinishLoading
2015-07-14 14:54:25.130 paypalNativeDemo[1478:61010] {"error":"invalid_client","error_description":"Invalid client credentials"}
Sandbox credentials are different than live. Make sure you're using your sandbox client_id if you are talking to sandbox.
Generally this error is due to the REST app not yet being approved. I would suggest contacting PayPal Support through the number in your account and advise the agent that you are calling to check the status of your REST app.
Related
I need to show Garmin health data in my app. Garmin documentation ask developer to implement connection thorough oauth 1.0 connection with the app and garmin account. So, when i apply GET/PUSH request with the https://connectapi.garmin.com/oauth-service/oauth/request_token? url, its shows the following error. Fortunately , i am getting proper response in the postman.
Step 1 :
Postman request :
https://connectapi.garmin.com/oauth-service/oauth/request_token?oauth_consumer_key=3f58949f-e54d-4211-a735-e52cc0ab8f4d&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1531983278&oauth_nonce=cW1Xhs&oauth_version=1.0&oauth_signature=WveKS0cnl7w4ZNknL0WD4f7wBFU=
Response :
oauth_token=48d03142-ffe3-4adc-ae0e-6c3d7bdd1e18&oauth_token_secret=EY67QDeBqHNvCzlCt0HU5yQ1LkVkGOMK0b4
In my Code , I apply both GET/POST request, it shows following error :
Garmin Connect API Server - Error report HTTP Status 400 - Inadequate OAuth consumer credentials.type Status reportmessage Inadequate OAuth consumer credentials.description The request sent by the client was syntactically incorrect.Garmin Connect API Server
My code is like :
NSError *error;
NSString *urlString = #"https://connectapi.garmin.com/oauth-service/oauth/request_token?";
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSString * parameterString = [NSString stringWithFormat:#"oauth_consumer_key=3f58949f-e54d-4211-a735-e52cc0ab8f4d&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1531983278&oauth_nonce=cW1Xhs&oauth_version=1.0&oauth_signature=pfZzKhniC9zCFZdIx8d0gyIsw3Y"];
//3f58949f-e54d-4211-a735-e52cc0ab8f4d
// NSLog(#"%#",parameterString);
[request setHTTPMethod:#"GET"];
[request setURL:url];
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
//Even i apply push and set this data, nothing works!
// [request addValue:#"3f58949f-e54d-4211-a735-e52cc0ab8f4d" forHTTPHeaderField:#"oauth_consumer_key"];
// [request addValue:#"HMAC-SHA1" forHTTPHeaderField:#"oauth_signature_method"];
// [request addValue:#"1531983278" forHTTPHeaderField:#"oauth_timestamp"];
// [request addValue:#"cW1Xhs" forHTTPHeaderField:#"oauth_nonce"];
// [request addValue:#"1.0" forHTTPHeaderField:#"oauth_version"];
// [request addValue:#"pfZzKhniC9zCFZdIx8d0gyIsw3Y" forHTTPHeaderField:#"oauth_signature"];
// [request addValue:#"" forHTTPHeaderField:#"oauth_consumer_key"];
NSData *postData = [parameterString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:postData];
NSData *finalDataToDisplay = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
NSMutableDictionary *abc = [NSJSONSerialization JSONObjectWithData: finalDataToDisplay
options: NSJSONReadingMutableContainers
error: &error];
How i can overcome this response issue ? Does anyone face similar issue ? Any idea to make work oauth 1.0 authentication in iOS Swift/Objective Project successfully ?
So, I have to methods to approach a web service:
A GET:
- (NSDictionary *)getDataFromURL:(NSString*)url {
NSString * serverAddress =[NSString stringWithFormat:url,mySchoolURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL
URLWithString:serverAddress]
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
timeoutInterval:10
];
[request setHTTPMethod: #"GET"];
NSError *requestError = nil;
NSURLResponse *urlResponse = nil;
NSData *response = [NSURLConnection
sendSynchronousRequest:request
returningResponse:&urlResponse
error:&requestError];
NSError* error = nil;
NSDictionary *output = [NSJSONSerialization JSONObjectWithData:response options:kNilOptions error:nil];
return output;
}
and a POST:
-(NSData*)postData:(NSDictionary*)requestData toUrl:(NSString*)destination {
NSError *error;
NSData *postdata = [NSJSONSerialization dataWithJSONObject:requestData options:0 error:&error];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postdata length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:destination,mySchoolURL]]];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postdata];
[request setHTTPMethod:#"POST"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
return nil;
}
Somehow, the HTTP header of the POST method does include the cookie's SessionID, while the GET one doesn't.
I have to admit that I don't fully understand the innards of cookies and the like, but several sources on the web claim that I should't worry about the cookies at all, since they are taken care of automatically.
Anyway, the web service I'm talking to expects a Session ID in both POST and GET situations, so now I'm forced to start understanding what's going on.
Could any of you help me out here?
The concrete question is: how to I pass a Session_ID to a URL using a GET method?
Thanks ahead
Okay so one way to do this is by simply adding the cookies to the HTTP headers. When doing this the correctness of the URL is key. If the protocol is wrong, some cookies may not be included. You will need to get all available cookies, and then create a dictionary for the headers with he available cookies. Then you simply add those headers to your request by calling setAllHTTPHeaderFields:. I placed a quick example of how to do this below, however you can learn more about how cookies work at the Apple Documentation Class Reference
NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:request.URL];
NSDictionary *headers = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];
[request setAllHTTPHeaderFields:headers];
I really hope this helps you out. I would recommend reading the Apples Documentation to help you out as much as possible. I wish you the best of luck!
I came to the last stage of development of my app and here is the bit that I've never done before.
My friend has developed and API for my app to send and receive data, using django rest framework.
I need to authenticate my app to connect to it, send some data and receive data.
What I have found so far is:
NSURL *url = [NSURL URLWithString:#"http://localhost:8080/my/path/to/api/login/"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSString *authStr = [NSString stringWithFormat:#"%#:%#", #"myUsername", #"myPassword"];
NSData *authData = [authStr dataUsingEncoding:NSASCIIStringEncoding];
NSString *authValue = [NSString stringWithFormat:#"Basic %#", authData];
[request setValue:authValue forHTTPHeaderField:#"Authorization"];
[request setHTTPMethod:#"GET"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
//------------------------------------------------------------------------------------------------------------------------------------//
//EDIT: Added this based on answer form #Quver.
NSURLResponse *response1;
NSError *responseError;
NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response1 error:&responseError];
if (result.length > 0 && responseError == nil)
{
NSDictionary *greeting = [NSJSONSerialization JSONObjectWithData:result
options:0
error:NULL];
NSLog(#"Got response form server: %#", greeting);
}
This equals output like:
<0a0a3c68 746d6c3e 0a0a2020 20203c68 6561643e 0a202020 20202020 200a2020 20202020 20200a20 20202020 + ~50 lines of similar stuff. Hope this helps.
//-----------------------------------------------------------------------------------------------------------------------------------------//
I guess this is the way to create request. What should I do next? And how do I know that I have connected?
Then, if I have connected, how do I get data form there? (I have a url that gives me json as output - this is what I want to get). Assume the url to be http://localhost:8080/url/that/gives/json/.
Thank you for any help. Hope this is enough information for the question. I will add anything else required.
NSURLResponse *response;
NSError *responseError;
NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&responseError];
Add this to get response. You already prepared request, now it's time to send it with NSURLConnection. I you sync request insted of async, becouse of using GCD for whole metod request + sqlite update.
After a few days of searching I have found a way.
First, we need a token for authentication. I am generating it through terminal for now:
curl -X POST -d "grant_type=password&username=<your username>&password=<your password>" http://<client secret>:<client id>#url/to/token/page
Then, in your view controller where you want to connect:
//always put </> at the end of link
NSURL *aUrl = [NSURL URLWithString: #"http://where/you/trying/to/conect"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:30.0];
[request addValue:[NSString stringWithFormat:#"<type> <your token>"] forHTTPHeaderField:#"Authorization"];
[request setHTTPMethod:#"GET"];
NSError *error = nil;
self.response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error: &error];
This will return any json that the page supposed to return. This might not be the most secure way, but this is exactly what I need for now. I will look at more secure solutions like OAuth 2, later.
Hope this helps to someone.
I have an urban airship account and my iOS app ist already configured with the system. My device token is on the server and if I send a test notification from the server I get the notification on my iphone.
BUT how can I send a message FROM my iphone to another user?
I haven't found any stuff about sending through iphone.
This is my code:
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"https://go.urbanairship.com/api/push/"]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSDictionary *push;
push = #{#"aps":#{#"alert":#"How are you?"},#"device_tokens":#[#"87892382J393FS77789S90909N82022312332"]};
and then I have to send it as json or something else???
As documentation on http://docs.urbanairship.com/reference/api/v3/intro.html says, requests are http ones with JSON body.
You need to authorize first. From documentation:
The username portion is the application key. The password portion is
either the application secret, or master secret.
You can find in this question how to authorize on iOS:
NSString *authStr = [NSString stringWithFormat:#"%#:%#", [self username], [self password]];
NSData *authData = [authStr dataUsingEncoding:NSASCIIStringEncoding];
NSString *authValue = [NSString stringWithFormat:#"Basic %#", [authData base64EncodingWithLineLength:80]];
[request setValue:authValue forHTTPHeaderField:#"Authorization"];
And then I guess you should do like this:
#import "JSONKit.h"
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"https://go.urbanairship.com/api/push/"]];
request.HTTPMethod = #"POST";
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSDictionary *push = #{#"aps":#{#"alert":#"How are you?"},#"device_tokens":#[#"87892382J393FS77789S90909N82022312332"]};
request.HTTPBody = [push.JSONString dataUsingEncoding:NSUTF8StringEncoding];
[NSURLConnection sendSynchronousRequest:req returningResponse:nil error:nil];
Note that you need JSONKit to serialize your dictionary into string
OK this is my actually Method:
- (IBAction)sendPush:(id)sender {
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"https://go.urbanairship.com/api/push/"]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSString *authStr = [NSString stringWithFormat:#"app key:app secret"];
NSData *authData = [authStr dataUsingEncoding:NSASCIIStringEncoding];
NSString *authValue = [NSString stringWithFormat:#"Basic %#", [authData base64EncodedDataWithOptions:nil]];
[request setValue:authValue forHTTPHeaderField:#"Authorization"];
NSDictionary *push = #{#"aps":#{#"alert":#"How are you?"},#"device_tokens":#[#"87892382J393FS77789S90909N82022312332"]};
request.HTTPBody = [push.JSONString dataUsingEncoding:NSUTF8StringEncoding];
NSLog(#"push: %#",push);
NSLog(#"request: %#",request);
[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
}
If I comment the line 6-10 out then I get for the NSLog:
2013-11-06 12:59:13.238 myApp[7273:907] push: {
aps = {
alert = "How are you?";
};
"device_tokens" = (
87892382J393FS77789S90909N82022312332
);
}
2013-11-06 12:59:13.241 myApp[7273:907] request: <NSMutableURLRequest https://go.urbanairship.com/api/push/>
I really don't know why it doesn't works!!!
Just FYI, doing this would present a risk in a publicly released app.
Any push through UA requires your master secret to authenticate. If you added your master secret to the app, it would be viewable to a savvy hacker, who could then use it to send unauthorized pushes on your behalf. It has happened to people before.
It's not generally recommended.
This is an Example using the API V3
-(void)richPushNotification{
NSDictionary *push = #{
#"audience" : #{
#"device_token" : deviceToken
},
#"device_types" : #[ #"ios" ],
#"notification" : #{
#"ios" : #{
#"alert":Message,
#"sound":#"default",
#"badge":#"auto",
}
},
#"message": #{
#"title": Message,
#"body": #"<html><body><h1>blah blah</h1> etc...</html>",
#"content_type": #"text/html",
#"extra": #{
#"offer_id" : #"608f1f6c-8860-c617-a803-b187b491568e"
}
}
};
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"https://go.urbanairship.com/api/push/"]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/vnd.urbanairship+json; version=3;" forHTTPHeaderField:#"Accept"];
NSString *authStr = [NSString stringWithFormat:#"%#:%#", appKey, appMasterSecret];
NSData *authData = [authStr dataUsingEncoding:NSASCIIStringEncoding];
NSString *authValue = [NSString stringWithFormat:#"Basic %#", [authData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed]];
[request setValue:authValue forHTTPHeaderField:#"Authorization"];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:push
options:0 // Pass 0 if you don't care about the readability of the generated string
error:NULL];
request.HTTPBody = jsonData;
[NSURLConnection connectionWithRequest:request delegate:self];
}
And The Response:
- (void) connection:(NSURLConnection *) connection didReceiveResponse:(NSURLResponse *) response {
NSHTTPURLResponse * res = (NSHTTPURLResponse *) response;
NSLog(#"response: %#",res);
NSLog(#"res %li\n",(long)res.statusCode);
if (res.statusCode == 202) {
//Show Alert Message Sent
}else{
//Handle Error
}
}
I am currently connecting my iOS native app to a facebook page in order to post a message to that wall. I can access the wall but for some reason there's no message text set. I asked the user for 'publish_stream' permissions.
Any idea what I'm doing wrong? Here's my code:
NSMutableDictionary *message = [NSDictionary dictionaryWithObjectsAndKeys:#"some text", #"message", #"http://path/to/itunes/", #"link", nil];
NSString *changeJSON = [message JSONRepresentation];
NSLog(#"changeJSON: %#", changeJSON);
NSData *myPostData = [changeJSON dataUsingEncoding:NSUTF8StringEncoding];
NSString *myURL = [NSString stringWithFormat:#"https://graph.facebook.com/pageId/feed?access_token=%#", facebook.accessToken];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:myURL] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10.0];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [myPostData length] ] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: myPostData];
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil ];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];
NSLog(#"return string: %#", returnString);
[facebook logout:self];
The string which is encoded to a NSData object is the following:
{"message":"some text","link":"http://path/to/itunes/"}
Thanks and have a nice day :-)
It looks like you're attempting to post JSON to the GraphAPI? If so, you can't post JSON to Facebook, but instead have to use parameters when posting (either query string or HTTP request parameters).
All posting actions are done via HTTP POST with parameters and all responses are done in JSON. You can read more on this via the Graph API reference under publishing.
See: POST Reference.