Need to have transaction id from pay key PayPal - ios

I have successfully integrated PayPal into my iOS application using PayPal MPL library.
But the problem is how to get the transaction id from paykey which i get from callback method of PayPal.
i have tried this way but getting error of invalid request.
- (void)paymentSuccessWithKey:(NSString *)payKey andStatus:(PayPalPaymentStatus)paymentStatus
{
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"https://svcs.paypal.com/AdaptivePayments/PaymentDetails"]];
//NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"https://svcs.sandbox.paypal.com/AdaptivePayments/PaymentDetails"]];
NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:url];
NSString *parameterString = [NSString stringWithFormat:#"payKey=%#&requestEnvelope.errorLanguage=%#",payKey,#"en_US"];
NSString *msgLength = [NSString stringWithFormat:#"%d", [parameterString length]];
[theRequest addValue: msgLength forHTTPHeaderField:#"Content-Length"];
//do post request for parameter passing
[theRequest setHTTPMethod:#"POST"];
[theRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
//passing key as a http header request
[theRequest addValue:api_username forHTTPHeaderField:#"X-PAYPAL-SECURITY-USERID"];
//passing key as a http header request
[theRequest addValue:api_password forHTTPHeaderField:#"X-PAYPAL-SECURITY-PASSWORD"];
[theRequest addValue:api_signature forHTTPHeaderField:#"X-PAYPAL-SECURITY-SIGNATURE"];
[theRequest addValue:#"JSON" forHTTPHeaderField:#"X-PAYPAL-REQUEST-DATA-FORMAT"];
[theRequest addValue:#"JSON" forHTTPHeaderField:#"X-PAYPAL-RESPONSE-DATA-FORMAT"];
[theRequest addValue:app_id forHTTPHeaderField:#"X-PAYPAL-APPLICATION-ID"];
[theRequest setHTTPBody: [parameterString dataUsingEncoding:NSUTF8StringEncoding]];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&response error:&err];
NSString* s = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSDictionary *result = [s JSONValue] ;
}
i need to save the transaction id on the backend of my application for future references.
Need to know how to get it asap.
Any help would be appreciated.
Thanks & Regards
Pankaj

I dont know about iOS but for andorid , we implement PayPalResultDelegate , Serializable interface , in a class like . i am sharing my code :
class ResultDelegate implements PayPalResultDelegate, Serializable
{
private static final long serialVersionUID = 10001L;
PaypalDetailImplementation ob = new PaypalDetailImplementation() ;
public void onPaymentSucceeded(String payKey, String paymentStatus)
{
ob.resultTitle = "SUCCESS";
ob.resultInfo = "You have successfully completed your transaction.";
ob.resultExtra = "Key: " + payKey;
this.displayInformation("onPaymentSucceeded", ob.resultTitle, ob.resultInfo, ob.resultExtra) ;
}
public void onPaymentFailed(String paymentStatus, String correlationID,String payKey, String errorID, String errorMessage)
{
ob.resultTitle = "FAILURE";
ob.resultInfo = errorMessage;
ob.resultExtra = "Error ID: " + errorID + "\nCorrelation ID: "+ correlationID + "\nPay Key: " + payKey;
this.displayInformation("onPaymentFailed", ob.resultTitle, ob.resultInfo, ob.resultExtra) ;
}
public void onPaymentCanceled(String paymentStatus)
{
ob.resultTitle = "CANCELED";
ob.resultInfo = "The transaction has been cancelled.";
ob.resultExtra = "";
this.displayInformation("onPaymentCanceled", ob.resultTitle, ob.resultInfo, ob.resultExtra) ;
}
public void displayInformation ( String msg , String resultTitle , String resultInfo , String resultExtra )
{
Log.i("Result as message : ",msg);
Log.i(resultTitle,"tushar:onPaymentSucceeded");
Log.i(resultInfo,"tushar:onPaymentSucceeded");
Log.i(resultExtra,"tushar:onPaymentSucceeded");
}

First, it's critically important to make sure that you don't ship an app with the API password & signature. Otherwise a malicious user could disassemble your app, recover the credentials and perform arbitrary operations to your account. Read more about verifying a payment.
But, assuming that you implemented similar code on your server, it should work. What is the exact error that you're getting?

I got this problem solved my self.
I was making the X-PAYPAL-REQUEST-DATA-FORMAT of JSON type but when i changed it to NV i start edgetting transaction id.
Thanks to all for their answers.

Related

IOS: Dictionary Return null value/Data

in my project i am using JSON parsing to display data for this i created 2 NSDictionary dictionary 1 return success response but when i call it in second dictionary it return Null value.
i am sharing my code please help me to correct it
-(void)hdata
{
NSString *post = [NSString stringWithFormat:#"data[Users][ref_id]=%#&api_key=bf45c093e542f057c123ae7d6",refidstr];
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:#"http://192.168.0.20/hspCh/api/user_diagnose_list"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
[request setHTTPBody:postData];
NSString *str=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"str : %#",str);
NSDictionary *dict6 = [self cleanJsonToObject:responseData];
NSLog(#"str : %#",dict6); <=======it gives correct responce
diagnosisdict = [dict6 objectForKey:#"data[Users][ref_id]"];
[diagnosisdict setValue:refidstr forKey:#"data[Users][ref_id]"];
NSLog(#" for ref id =%# , data is= %#",refidstr, diagnosisdict); <======Gives null responce
}
Output of the above in console is as follows
2015-12-09 10:34:16.935 HcH[2841:32315] str : {"response":200,"diagnoses":[{"DiagnosesHospitals":{"hospital_id":"3341","id":"163075","discharges":"100.00","charge_amt":"1200.00","total_amt":"1500.00","medicare_amt":"1200.00"},"Diagnoses":{"diagnosis_name":"TRANSIENT ISCHEMIA"}}]}
2015-12-09 10:34:16.935 HcH[2841:32315] str : {
diagnoses = (
{
Diagnoses = {
"diagnosis_name" = "TRANSIENT ISCHEMIA";
};
DiagnosesHospitals = {
"charge_amt" = "1200.00";
discharges = "100.00";
"hospital_id" = 3341;
id = 163075;
"medicare_amt" = "1200.00";
"total_amt" = "1500.00";
};
}
);
response = 200;
}
2015-12-09 10:34:16.936 HcH[2841:32315] for ref id =3341 , data is= (null)
Replace this
diagnosisdict = [dict6 objectForKey:#"data[Users][ref_id]"];
with
diagnosisdict = [[[dict6 objectForKey:#"diagnoses"] objectAtIndex:0] objectForKey:#"DiagnosesHospitals"];
There is no entry in dict6 for "data[Users][ref_id]".
Using that string as a key is completely nonsensical, by the way. A key in this context is just a string, not a series of accesses in dictionaries.
It seems like what you want is dict6[#"data"][#"Users"][#"ref_id"].
However, this will also fail, because there is no entry for "data" in dict6.
It is possible that your cleanJSONToObject: method is stripping out the value of the "data" key. However, based on your statement that printing the value of dict6 gives the correct response, I assume that what you actually want to access is the value of "id" in "DiagnosesHospitals", since it sounds the most like a "ref_id".
Based on the output of the debugger, it seems as though you have a dictionary (dict6) with a "diagnoses" key pointing to an array with two dictionaries.
So, You would access the "id" field with dict6[diagnoses][0][#"DiagnosesHospitals"][#"id"], assuming that "id" is a string (I'm not sure why it has no quotes around it).
Somethings that you can get:
NSDictionary * diagnoses = dict6[#"diagnoses"];
NSString * diagnosis_name = diagnoses[0][#"Diagnoses"][#"diagnosis_name"];
NSDictionary * diagnosisdict = diagnoses[0][#"DiagnosesHospitals"];
NSString * hospital_id = diagnosisdict[#"hospital_id"];

Call function on Server from iOS app - Objective C

If you are familiar with Parse.com's Javascript SDK, this is what I am trying to do for my own server for my iOS app (Objective-c). I want to be able to send some a string to the function that is on my server, have the server run its function and then return a string to the app or some xml or JSON data.
Is this even possible?
I am new to doing something like this having an app make a call to a server. I have looked into opening a port on my server, but have been unable to find a way to receive data back to the iOS app. (I found this lib but its for OS X https://github.com/armadsen/ORSSerialPort). Also Im not sure if I have a function run with an open port on the server. So how can I set it up so I can make a call to my server and run a function?
Any help would be much appreciated.
You just need to POST data to your server.
Port could be anything you want.
Host your script with a domain url so that you can make network request publicly.
You can try this function:
-(NSData *)post:(NSString *)postString url:(NSString*)urlString{
//Response data object
NSData *returnData = [[NSData alloc]init];
//Build the Request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)[postString length]] forHTTPHeaderField:#"Content-length"];
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
//Send the Request
returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil];
//Get the Result of Request
NSString *response = [[NSString alloc] initWithBytes:[returnData bytes] length:[returnData length] encoding:NSUTF8StringEncoding];
bool debug = YES;
if (debug && response) {
NSLog(#"Response >>>> %#",response);
}
return returnData;
}
And here is how you use it:
NSString *postString = [NSString stringWithFormat:#"param=%#",param];
NSString *urlString = #"https://www.yourapi.com/yourscript.py";
NSData *returnData = [self post:postString url:urlString];
PHP
<?php
$response=array();
if(isset($_POST['param'])){
$response['success'] = true;
$response['message'] = 'received param = '.$_POST['param'];
}else{
$response['success'] = false;
$response['message'] = 'did not receive param';
}
$json = json_encode($response);
echo $json;

How to call a function of web service for login? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have a Web-Service API in PHP and i want to do login using this api in my ios application.
if (isset($_POST['tag']) && $_POST['tag'] != '')
{
// Get tag
$tag = $_POST['tag'];
// Include Database handler
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
// response Array
$response = array("tag" => $tag, "success" => 0, "error" => 0); // check for tag type
if ($tag == 'login')
{
// Request type is check Login
$email = $_POST['email'];
$password = $_POST['password']; // check for user
$user = $db->getUserByEmailAndPassword($email, $password);
if ($user != false)
{
// user found // echo json with success = 1
$response["success"] = 1;
$response["user"]["fname"] = $user["firstname"];
$response["user"]["lname"] = $user["lastname"];
$response["user"]["email"] = $user["email"];
$response["user"]["uname"] = $user["username"];
$response["user"]["uid"] = $user["unique_id"];
$response["user"]["created_at"] = $user["created_at"];
echo json_encode($response);
}
else
{
// user not found
// echo json with error = 1
$response["error"] = 1;
$response["error_msg"] = "Incorrect email or password!";
echo json_encode($response);
}
}
else
{
echo "Digitalnet API";
}
This Web-Service checks for the database query to match the email and password.
Now I have made the connection with the web service and it is returning me the response Digitalnet Api.
In the button event
- (IBAction)btnSignIn:(id)sender {
if( ([txtUserEmail.text isEqualToString:#""]) || ([txtUserPassword.text isEqualToString:#""]))
{
[self showErrorAlert];
}
NSString *post = [[NSString alloc] initWithFormat:#"email==%# AND password==%#",self.txtUserEmail.text,self.txtUserPassword.text];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSURL *url = [NSURL URLWithString:#"http://localhost/ColorPicker/index.php"]; NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
[theRequest setHTTPMethod:#"POST"];
[theRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[theRequest setValue:postLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPBody:postData];
NSURLResponse *response;
NSError *error;
NSData *urlData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&response error:&error];
NSString *str=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding]; NSLog(#"Login response: is %#",str); //getting response
else if(str != nil)
{
ColorPickerViewController *cpvc =[[ColorPickerViewController alloc] init];
[self.navigationController pushViewController:cpvc animated:YES];
}
else
{ NSLog(#"some thing went wrong");
}
}
What should I do to make login with this web-service so that the request is being sent from the application on button click, and the Api Validates the Request's with email and password and then after the user is authenticated it will allowed to move to the next screen/view.
NOTE: The Api is included with the class 'include/DB_Functions.php' which will check the user validation with mysql db so please don't be confused with the Web-Service I just need to know the logic on IPHONE.
You say, you are getting response from web- service. That means it is working fine.
I think there is some problem sending post parameters from url to the web-service.
Try something like this(just a piece of code. you need to modify it accordingly):
NSString * parameters = [NSString stringWithFormat:#"email=%#&password=%#",self.txtUserEmail.text,self.txtUserPassword.text];
[_mutableRequest setHTTPMethod:#"POST"];
NSData *requestData = [NSData dataWithBytes:[parameters UTF8String] length:[parameters length]];
[_mutableRequest setHTTPBody:requestData];
// then hit the connection using NSURLConnection

Convert NSData (retrieved from wcf ) to NSArray

I want to convert NSData, which I get it by accessing web service, to NSArray. How can I do it?
Here is the structure that I want to convert from NSData:
NSArray:
NSDictionary1 : roomName departmentName
NSDictionary2 : roomName departmentName
NSDictionary3 : roomName departmentName
NSDictionary4 : roomName departmentName
NSDictionary5 : roomName departmentName
...
GetRoomList method of the web service returns a list. The structure of the list is above. Code:
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *soapMessage = [NSString stringWithFormat:#"<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"><SOAP-ENV:Body><m:GetRoomList xmlns:m=\"http://http://portNumber/ilacDirektif.svc/\"><departId xsi:type=\"xsd:int\">0</departId><roomId xsi:type=\"xsd:int\">0</roomId></m:GetRoomList></SOAP-ENV:Body></SOAP-ENV:Envelope>"];
NSURL *url=[NSURL URLWithString:#"http://port number/ilacDirektif.svc/"];
NSMutableURLRequest *theRequest= [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30];
NSString *msgLength = [NSString stringWithFormat:#"%d", [soapMessage length]];
[theRequest addValue: #"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[theRequest addValue: #"http://tempuri.org/ilacDirektif.svc" forHTTPHeaderField:#"SOAPAction"];
[theRequest addValue: msgLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPMethod:#"POST"];
[theRequest addValue:#"port number" forHTTPHeaderField:#"Host"];
[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
NSURLResponse* response = nil;
NSData *data =[NSURLConnection sendSynchronousRequest: theRequest returningResponse: &response error: nil];
NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithFile:data];
if(array){NSLog(#"%#",array); }else{ NSLog(#"Failed"); }
if (data) {NSLog(#"%#",data);} else { NSLog(#"Failed");}
}
Error:
2013-05-31 09:59:45.208 IlacOrder[18513:11303] -[__NSCFData getFileSystemRepresentation:maxLength:]: unrecognized selector sent to
instance 0x7560860 2013-05-31 09:59:45.222 IlacOrder[18513:11303] *
Terminating app due to uncaught exception
'NSInvalidArgumentException', reason: '-[__NSCFData
getFileSystemRepresentation:maxLength:]: unrecognized selector sent to
instance 0x7560860'
* First throw call stack: (0x1c8e012 0x10cbe7e 0x1d194bd 0x1c7dbbc 0x1c7d94e 0xacc7b4 0xacc762 0xafac85 0xb22c7a 0x2a55 0xf4817 0xf4882
0xf4b2a 0x10bef5 0x10bfdb 0x10c286 0x10c381 0x10ceab 0x10d4a3 0x10d098
0x2460 0x10df705 0x16920 0x168b8 0xd7671 0xd7bcf 0xd6d38 0x4633f
0x46552 0x243aa 0x15cf8 0x1be9df9 0x1be9ad0 0x1c03bf5 0x1c03962
0x1c34bb6 0x1c33f44 0x1c33e1b 0x1be87e3 0x1be8668 0x1365c 0x1ded
0x1d15 0x1) libc++abi.dylib: terminate called throwing an exception
The function in .svc:
public List<DepartmentRoom>GetRoomList(int roomId,int departId()){
return manager.GetRoomList(roomId,departId);
}
GetRoomList:
public List<DepartmentRoom> GetRoomList(int departId,int roomId){
var cmd = OracleHelper.GetOracleCommand(_conn, StoredProcedure.Procedure1);
if (_conn.State == ConnectionState.Closed)
_conn.Open();
OracleCommandBuilder.DeriveParameters(cmd);
cmd.Parameters["P_DEPARTID"].Value = departId;
cmd.Parameters["P_ROOMID"].Value = roomId;
OracleDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
object o = cmd.Parameters["P_REF"].Value;
var roomList = new List<DepartmentRoom>();
while (dr.Read())
{
var departmentRoom = new DepartmentRoom
{
DepartId = Convert.ToInt32(dr["DEPARTID"]),
DepartmentName = dr["DEPART"].ToString(),
RoomId = Convert.ToInt32(dr["ROOMID"]),
RoomName = dr["ROOM"].ToString()
};
roomList.Add(departmentRoom);
}
return roomList;
}
Perhaps it would be worth reading the documentation of the methods and classes you are trying to use. unarchiveObjectWithFile: takes a file path as its argument, not an NSData. Finding the method in the docs that takes an NSData as its input is left to you as an exercise.
This worked for me:
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:REQIP]];
NSData *myPostData = [[NSString stringWithFormat:#"{\"departId\":%d,\"roomId\":%d}",departId,roomId] dataUsingEncoding:NSUTF8StringEncoding];
NSMutableData *myMutablePostData = [NSMutableData dataWithData:myPostData];
[request setPostBody:myMutablePostData];
[request setRequestMethod:#"GET"];
[request addRequestHeader:#"Content-Type" value:#"application/json"];
[request setDelegate:self];
[request startSynchronous];
NSMutableArray *list =[[NSMutableArray alloc]init];
id jsonObjects = [NSJSONSerialization JSONObjectWithData:[[request responseString]dataUsingEncoding:NSUTF8StringEncoding]options:NSJSONReadingMutableContainers error:nil ];
for(NSDictionary *theItem in [jsonObjects objectForKey:#"RequestMethodResult"]){
[list addObject:[[ClassModel alloc]initWithDictionary:theItem]];
}
return list;
ClassModel is the structure of the Dictionary that each object item of NSMutableArray is.

iOS POST request parameters random crash when connecting to Zend server

This question is related to this other one: Zend getParameters not returning what is in url route
The problem I'm facing is that, randomly, the Zend server does not get the parameters that are in the route, causing the login of my app crash. I.e., sometimes when printing the getParams(); function I get the user email as following:
Array (
[email] = user#email.com
(...)
)
This works fine, but some other times I get this:
Array (
[user#email.com] = 2.874983 //Longitude
(...)
)
Causing the crash of the login action.
This could be a fault in the server side or in the client side. I've put an NSLog to print the NSMutableURLRequest each time the server gets called, and I've seen that the request url is always well formed. Maybe this is a coincidence, I don't know, but sometimes trying to solve this issue I've changed the request code and it was temporarily fixed. But then, after some requests, the error was back.
The following snippet represents the code I'm using to connect to the server:
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[self._url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
NSMutableString *values = nil;
if ( params ) {
NSDictionary *parameters = params;
values = [[NSMutableString alloc] init];
for ( NSString* key in parameters ) {
NSMutableString *value = [[NSMutableString alloc] init];
[value appendString:key];
[value appendString:#"="];
[value appendString:[self urlEncodeValue:[parameters valueForKey:key]]];
[value appendString:#"&"];
[values appendString:value];
}
}
NSData *postData = [values dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLenght = [NSString stringWithFormat:#"%d", [postData length]];
if ( cookies ) {
NSDictionary *cooks = cookies;
for ( NSString* cookie in cooks) {
NSMutableString *ck = [[NSMutableString alloc] initWithString:cookie];
[ck appendString:#"="];
[ck appendString:[cooks valueForKey:cookie]];
[theRequest addValue:ck forHTTPHeaderField:#"Cookie"];
}
}
[theRequest setHTTPMethod:self._method];
if ( values ) {
[theRequest setValue:#"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[theRequest setHTTPBody: postData];
[theRequest setValue:postLenght forHTTPHeaderField:#"Content-Length"];
}
// create the connection with the request
// and start loading the data
NSLog(#"%#", theRequest);
NSURLConnection *theConnection =[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
Another important thing is that the login sends both latitude and longitude values, and it seems that it's crashing when some of those values changes.
I've solved this problem and I've posted the solution here: Zend getParameters not returning what is in url route
It was a memcached configuration problem, nothing to do with the iOS client application.

Resources