How to work with two Stripe account in 'one' app - ios

I am a newbie in iOS and also newbie in Stripe pay with iOS I want to pay Two Stripe account in iOS like as first I want to pay in One and after successfully pay in one account as soon as possible I want to pay in to second account for that I write a code like as:
"Transaction Start"
-(void)startTransaction
{
if ([self validateCustomerInfo])
{
[Stripe setDefaultPublishableKey:STRIPE_TEST_PUBLIC_KEY1];
STPCardParams *card = [[STPCardParams alloc] init];
card.number = txtCardNumber.text;
card.expMonth =[btnMonth.titleLabel.text integerValue];
card.expYear = [btnYear.titleLabel.text integerValue];
card.cvc = txtCvv.text;
[[STPAPIClient sharedClient] createTokenWithCard:card
completion:^(STPToken *token, NSError *error) {
if (error) {
[GlobalClass StopSpinner:self.view];
[AppDelegate ShowAlert:[NSString stringWithFormat:#"%#",[error localizedDescription]]];
} else {
[self postStripeToken:token];
}
}];
}
}
#Generated First Token.
-(void)postStripeToken:(STPToken*)token
{
[GlobalClass ActivateSpinner:self.view StringMSG:#"Please wait"];
NSDictionary *parameter=#{#"secretkey":STRIPE_SECRET_KEY1,#"stripeToken":token.tokenId,#"amount":#"2",#"currency":#"usd",#"description":#"iOS Transaction"};
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:#"text/html"];
[manager POST:#"http://s570166064.onlinehome.us/seadealersWS/payment/payment.php" parameters:parameter success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"Responce Object %#",responseObject);
if ([[responseObject valueForKey:#"status"]isEqualToString:#
"Success"])
{
# Here i want to Pay in second account #
[Stripe setDefaultPublishableKey:STRIPE_TEST_PUBLIC_KEY2];
STPCardParams *card = [[STPCardParams alloc] init];
card.number = txtCardNumber.text;
card.expMonth =[btnMonth.titleLabel.text integerValue];
card.expYear = [btnYear.titleLabel.text integerValue];
card.cvc = txtCvv.text;
[[STPAPIClient sharedClient] createTokenWithCard:card
completion:^(STPToken *token, NSError *error) {
if (error) {
[GlobalClass StopSpinner:self.view];
[AppDelegate ShowAlert:[NSString stringWithFormat:#"%#",[error localizedDescription]]];
} else {
[GlobalClass StopSpinner:self.view];
[GlobalClass ActivateSpinner:self.view StringMSG:#"Please wait"];
[self postStripeTokenTwo:token];
}
}];
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
[GlobalClass StopSpinner:self.view];
[AppDelegate ShowAlert:#"Please try again"];
NSLog(#"Error %#",error);
}];
}
-(void)postStripeTokenTwo:(STPToken*)token
{
NSDictionary *parameter=#{#"secretkey":STRIPE_SECRET_KEY2,#"stripeToken":token.tokenId,#"amount":#"0.5",#"currency":#"usd",#"description":#"iOS Transaction"};
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:#"text/html"];
[manager POST:#"http://s570166064.onlinehome.us/seadealersWS/payment/payment.php" parameters:parameter success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"Responce Object %#",responseObject);
if ([[responseObject valueForKey:#"status"]isEqualToString:#
"Success"])
{
[GlobalClass StopSpinner:self.view];
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
[GlobalClass StopSpinner:self.view];
[AppDelegate ShowAlert:#"Please try again"];
NSLog(#"Error %#",error);
}];
}
But for First account i get success response but for Second account it says that Your token is not valid i not want to set stripe connect.
Thank you, and sorry for bad english.

A token can only be used once and is only valid in the account that created it. You would have to use two tokens (one created per account)
Also, you should not be shipping your Stripe secret API key in your app. Strings in application code can easily be discoverable and you do not want to leak your API key. The standard approach is to send the token to a server you control and from your server send the API call.
In addition, you may want to take a look at Stripe Connect, it may be a better approach to your issue then storing api keys of multiple accounts.

This problem is exist in the older versions of Stripe SDK
In order to resolve this issue
1) upgrade the SDK to the latest version(13.2.0)
pod Stripe, '~>13.2.0'
pod install --repo-update
2) Instead of setting
STPPaymentConfiguration.shared().publishableKey = STRIPE_TEST_PUBLIC_KEY1
use
STPAPIClient.shared().publishableKey = STRIPE_TEST_PUBLIC_KEY1
3) Clean and run the project and it will work as expected.
Please refer this link for more information

Related

How to return a value from a method by delay?

I have a framework and a project. My framework is responsible for web services.
From Project user insert username and password. Then it passes these parameters by calling sendLogin method inside the framework.
Inside framework it takes a while to check and validate username and password. If username and password are correct it will get a token number from server.
Until here everything works fine. But I want to know how to send this token back to main program?
I tried completion method but I failed. Here is definition:
Project:
- (IBAction)bankLoginPressed:(id)sender
{
[registerUser sendLogin:^(NSInteger *accessCode){
NSLog(#"access code == %tu ",accessCode);
}];
}
Inside framework
typedef void (^HttpCompletionBlock) (NSInteger *);
-(void) sendLogin :(HttpCompletionBlock)completionHandler
{
NSString *string = #"https://myserver/customer_authentication";
NSDictionary *parameters = #{#"member_id": #"1234", #"access_code": #"password", #"device_id":#"874627864"};
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager POST:string parameters:parameters progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(#"JSON: %#", responseObject);
if (responseObject[#"secret_token"])
{
NSLog(#"Secret is= %#",responseObject[#"secret_token"]);
//Here I needd to send back token number????
}
}
failure:^(NSURLSessionTask *operation, NSError *error)
{
NSLog(#"Error: %#", error);
}];
}
typedef void (^HttpCompletionBlock) (NSString *token, NSError *error);
-(void) sendLogin :(HttpCompletionBlock)completionHandler
{
NSString *string = #"https://myserver/customer_authentication";
NSDictionary *parameters = #{#"member_id": #"1234", #"access_code": #"password", #"device_id":#"874627864"};
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager POST:string parameters:parameters progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(#"JSON: %#", responseObject);
if (responseObject[#"secret_token"])
{
NSLog(#"Secret is= %#",responseObject[#"secret_token"]);
//Here I needd to send back token number????
return completionHandler(responseObject[#"secret_token"],nil);
}
}
failure:^(NSURLSessionTask *operation, NSError *error)
{
NSLog(#"Error: %#", error);
return completionHandler(nil,error);
}];
}
- (IBAction)bankLoginPressed:(id)sender
{
[registerUser sendLogin:^(NSString *token, NSError *error){
if(error == nil)
{
NSLog(#"access code == %# ",token);
}
else
{
NSLog(#"Error == %# ",error);
}
}];
}

Get linkedin connections ios

Hii i'm trying to get linkedin connection. i have see some same questions but did not find any relevant solution. please help me how can i find connection using latest SDK and which permission i need for connections.
i have used argument as
#define LinkedInApiUrl #"http://api.linkedin.com/v1/people/~/connections:(id,headline,first-name,last-name)"
- (void)requestMeWithToken:(NSString *)accessToken
{
[self.client GET:[NSString stringWithFormat:#"%#?oauth2_access_token=%#&format=json",LinkedInApiUrl,accessToken] parameters:nil success:^(AFHTTPRequestOperation *operation, NSDictionary *result) {
NSLog(#"current user %#", result);
[self linkedinAuthenticationResponse:result error:nil];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"failed to fetch current user %#", error);
[self linkedinAuthenticationResponse:nil error:error];
}];
}
- (LIALinkedInHttpClient *)client
{
LIALinkedInApplication *application = [LIALinkedInApplication
applicationWithRedirectURL:[NSString stringWithFormat:#"%#",#"https://www.something.com"]
clientId:LINKEDIN_CLIENT_ID
clientSecret:LINKEDIN_CLIENT_SECRET
state:#"someState"
grantedAccess:#[ LISDK_EMAILADDRESS_PERMISSION, LISDK_BASIC_PROFILE_PERMISSION,LISDK_RW_COMPANY_ADMIN_PERMISSION,LISDK_W_SHARE_PERMISSION ]];
return [LIALinkedInHttpClient clientForApplication:application presentingViewController:self];
}

Sending attachment to comment in Zendesk (iOS)

I'm developing iOS application with Zendesk, I'm using REST v2 api and I have a problem with attachments to comments. Operation of sending attachments looks fine but when trying read attachment from comment I have a problem becouse file is corrupted (I'm sending image). I'm using AFNetworking library. Here is my code:
- (void)addAttachment:(NSData*)data withFileName:(NSString*)fileName {
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager.requestSerializer setAuthorizationHeaderFieldWithUsername:API_USER password:API_TOKEN];
[manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObject:#"text/plain"]];
[manager.requestSerializer setValue:#"image/jpeg" forHTTPHeaderField:#"Content-Type"];
NSDictionary *parameters = #{#"image":#{ #"content_type": #"image/jpeg", #"filename":fileName, #"file_data": [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength]}};
[manager POST:[NSString stringWithFormat:#"%#uploads.json?filename=%#", API_URL, fileName] parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSDictionary *dictionary = responseObject;
if (dictionary != nil && [dictionary objectForKey:#"upload"] != nil) {
NSString *token = [[dictionary objectForKey:#"upload"] objectForKey:#"token"];
if ([self.delegate respondsToSelector:#selector(didFinishedAddAttachmentWithSuccess:andToken:)]) {
[self.delegate didFinishedAddAttachmentWithSuccess:YES andToken:token];
}
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"%#", error);
if ([self.delegate respondsToSelector:#selector(didFinishedAddAttachmentWithSuccess:andToken:)]) {
[self.delegate didFinishedAddAttachmentWithSuccess:NO andToken:nil];
}
}];
}
Any suggestions?
I resolved this issue by using Zendesk Mobile SDK:
ZDKUploadProvider *uploadProvider = [[ZDKUploadProvider alloc] init];
[uploadProvider uploadAttachment:data withFilename:fileName andContentType:#"image/jpg" callback:^(ZDKUploadResponse *uploadResponse, NSError *error) {
if (uploadResponse != nil && [self.delegate respondsToSelector:#selector(didFinishedAddAttachmentWithSuccess:andToken:)]) {
[self.delegate didFinishedAddAttachmentWithSuccess:YES andToken:uploadResponse.uploadToken];
}
else {
if ([self.delegate respondsToSelector:#selector(didFinishedAddAttachmentWithSuccess:andToken:)]) {
[self.delegate didFinishedAddAttachmentWithSuccess:NO andToken:nil];
}
}
}];

handling the Response with the AFNetworking 2

i am really new to IOS development. i want to develop an application which is dealing with some web services and display in a table view. somehow i found a 3rd party library for do the networking stuffs [AFNetworking 2]. below is my code to get the json response for any given url and parameters.
-(NSDictionary*)getWebServiceResponce:(NSString *)url :(NSDictionary *)object
{
// NSDictionary *parameters = [[NSDictionary alloc] initWithObjectsAndKeys:#"47", #"caregiverPersonId", nil];
__block NSDictionary* result=Nil;
__block NSString* person=Nil;
AFSecurityPolicy *policy = [[AFSecurityPolicy alloc] init];
[policy setAllowInvalidCertificates:YES];
AFHTTPRequestOperationManager *operationManager = [AFHTTPRequestOperationManager manager];
[operationManager setSecurityPolicy:policy];
operationManager.requestSerializer = [AFJSONRequestSerializer serializer];
operationManager.responseSerializer = [AFJSONResponseSerializer serializer];
[operationManager POST:url
parameters:object
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", [responseObject description]);
person = [responseObject[#"d"]objectForKey:#"PersonId"];
// [self returnedResponce:responseObject];
result = (NSDictionary *) responseObject[#"d"];
NSLog(#"RESULT: %#", result);
NSLog(#"personm: %#", person);
[operation waitUntilFinished];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", [error description]);
//result = [error];
}
];
return result;
}
this code works perfectly.. but my point is when i put some breakpoints to check what are the values i got for several variables, it shows null. but my log shows the entire json response.
and i want to return my response object as a dictionary. because i want to do some process with the response.. can some one help me with this ?
The problem is that result is nil when it gets returned. AFNetworking uses ObjC's awesome blocks, they get executed asynchronously. Read more about it here.
You should include a callback block in your getWebServiceResponce method. I've thrown together a bit of code but you should really read more about blocks.
-(void)webServiceResponceForURL:(NSString *)url dictionary:(NSDictionary *)object success:(void (^)(NSDictionary *responseObject))success {
// NSDictionary *parameters = [[NSDictionary alloc] initWithObjectsAndKeys:#"47", #"caregiverPersonId", nil];
__block NSDictionary* result=Nil;
__block NSString* person=Nil;
AFSecurityPolicy *policy = [[AFSecurityPolicy alloc] init];
[policy setAllowInvalidCertificates:YES];
AFHTTPRequestOperationManager *operationManager = [AFHTTPRequestOperationManager manager];
[operationManager setSecurityPolicy:policy];
operationManager.requestSerializer = [AFJSONRequestSerializer serializer];
operationManager.responseSerializer = [AFJSONResponseSerializer serializer];
[operationManager POST:url
parameters:object
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", [responseObject description]);
person = [responseObject[#"d"]objectForKey:#"PersonId"];
// [self returnedResponce:responseObject];
result = (NSDictionary *) responseObject[#"d"];
NSLog(#"RESULT: %#", result);
NSLog(#"personm: %#", person);
//We are executing the block as soon as we have the results.
if (success) {
success(responseObject);
}
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", [error description]);
//result = [error];
}
];
}
Edit:
[self webServiceResponceForURL:#"foo://foo" dictionary:nil success:^(NSDictionary *responseObject) {
//your code here
}
[self webServiceResponceForURL:#"foo://foo" dictionary:nil success:^(NSDictionary *responseObject) {
//your code here
}
Here you will got complete responseObject in form NSDictionary. You can assign responseObject to instance variable. Now This instance Variable will be used at point time. in your case, it will passed on button event.

AFNetworking and DELETE requests with Rails

I'm putting the finishing touches on my own version of the heroku rails mobile iOS photo sharing app. I have implemented and successfully sent POST and GET requests via HTTP on iOS. Unfortunately, the Heroku tutorial explicitly states it won;t be going into how to write the DELETE request. Here's what I have so far:
+ (void)deletePhoto:(NSString *)owner
image:(NSString *)recordId
block:(void (^)(Photo *, NSError *))block
{
NSMutableDictionary *mutableParameters = [NSMutableDictionary dictionary];
[mutableParameters setObject:recordId forKey:#"photo[id]"];
NSLog(#"Destroying %#", recordId);
[[CloudGlyphAPIClient sharedClient] deletePath:#"/photo" parameters:mutableParameters success:^(AFHTTPRequestOperation *operation, id JSON) {
if (block) {
NSLog(#"DELETE sussessful");
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if (block) {
block(nil, error);
}
}];
}
+ (void)getPhotos:(NSString *)owner
block:(void (^)(NSSet *photos, NSError *error))block
{
NSMutableDictionary *mutableParameters = [NSMutableDictionary dictionary];
[mutableParameters setObject:owner forKey:#"photo[owner]"];
[[CloudGlyphAPIClient sharedClient] getPath:#"/photos" parameters:mutableParameters success:^(AFHTTPRequestOperation *operation, id JSON) {
NSMutableSet *mutablePhotos = [NSMutableSet set];
for (NSDictionary *attributes in [JSON valueForKeyPath:#"photos"]) {
Photo *photo = [[Photo alloc] initWithAttributes:attributes];
[mutablePhotos addObject:photo];
}
if (block) {
block([NSSet setWithSet:mutablePhotos], nil);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if (block) {
block(nil, error);
}
}];
}
I've based the DELETE request off of the GET request, except in this case we are looking for a particular image user a certain owner. I get an error that the routes file doesn't contain a path for DELETE /photos... i added the destroy method to the rails app and raked the routes.rb file.
I feel like this is a rails GOTCHA somewhere.. thanks for your help ^_^
TL;DR trying to write DELETE request for a rails app with AFNetworking
In AFNetworking, the DELETE path is a url path like this: photos/18.json is the record marked for removal. Found the answer over here:
Answer
Effectively, one can concat together a string to the url of the ActiveREcord in a table.

Resources