Integrating Paypal SDK for iOS - ios

I'm trying to integrate the PayPal sdk for iOS app. I have installed it through Cocoapods ... Now I want to link some of the binary files .Should I have to download them and add manually or what is the case? Please let me know the steps to do so...
Thank you...

Follow the below code:-
#import "PayPalMobile.h"
#property(nonatomic, strong, readwrite) PayPalConfiguration *payPalConfig;
#property(nonatomic, strong, readwrite) NSString *environment;
Implement the delegates
<PayPalPaymentDelegate, PayPalFuturePaymentDelegate>
Call the below method named configPaypalPayment and implement the delegate methods as follows:-
#pragma mark - paypal
- (void)configPaypalPayment {
_environment = PayPalEnvironmentSandbox;
[PayPalMobile preconnectWithEnvironment:_environment];
// Set up payPalConfig
_payPalConfig = [[PayPalConfiguration alloc] init];
_payPalConfig.acceptCreditCards = YES;
_payPalConfig.merchantName = #"Andmine";
_payPalConfig.merchantPrivacyPolicyURL = [NSURL URLWithString:#"https://www.paypal.com/webapps/mpp/ua/privacy-full&#8221"];
_payPalConfig.merchantUserAgreementURL = [NSURL URLWithString:#"https://www.paypal.com/webapps/mpp/ua/useragreement-full&#8221"];
_payPalConfig.languageOrLocale = [NSLocale preferredLanguages][0];
_payPalConfig.payPalShippingAddressOption = PayPalShippingAddressOptionNone;
}
#pragma mark -
#pragma mark PayPalPaymentDelegate methods
- (void)payPalPaymentViewController:
(PayPalPaymentViewController *)paymentViewController
didCompletePayment:(PayPalPayment *)completedPayment {
NSLog(#"PayPal Payment Success!");
[self sendCompletedPaymentToServer:completedPayment]; // Payment was processed
// successfully; send to
// server for
// verification and
// fulfillment
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)payPalPaymentDidCancel:
(PayPalPaymentViewController *)paymentViewController {
NSLog(#"PayPal Payment Canceled");
// self.resultText = nil;
// self.successView.hidden = YES;
[self dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark Proof of payment validation
- (void)sendCompletedPaymentToServer:(PayPalPayment *)completedPayment {
// TODO: Send completedPayment.confirmation to server
NSLog(#"Here is your proof of payment:\n\n%#\n\nSend this to your server for "
#"confirmation and fulfillment.",
completedPayment.confirmation);
}
#pragma mark - Authorize Future Payments
- (IBAction)getUserAuthorizationForFuturePayments:(id)sender {
PayPalFuturePaymentViewController *futurePaymentViewController =
[[PayPalFuturePaymentViewController alloc]
initWithConfiguration:self.payPalConfig
delegate:self];
[self presentViewController:futurePaymentViewController
animated:YES
completion:nil];
}
#pragma mark PayPalFuturePaymentDelegate methods
- (void)payPalFuturePaymentViewController:
(PayPalFuturePaymentViewController *)futurePaymentViewController
didAuthorizeFuturePayment:
(NSDictionary *)futurePaymentAuthorization {
NSLog(#"PayPal Future Payment Authorization Success!");
// self.resultText = [futurePaymentAuthorization description];
// [self showSuccess];
[self sendFuturePaymentAuthorizationToServer:futurePaymentAuthorization];
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)payPalFuturePaymentDidCancel:
(PayPalFuturePaymentViewController *)futurePaymentViewController {
NSLog(#"PayPal Future Payment Authorization Canceled");
// self.successView.hidden = YES;
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)sendFuturePaymentAuthorizationToServer:(NSDictionary *)authorization {
// TODO: Send authorization to server
NSLog(#"Here is your authorization:\n\n%#\n\nSend this to your server to "
#"complete future payment setup.",
authorization);
}

Related

PayPal payment stuck "processing"

I've implemented the latest PayPal API but every time I try to run the payment through PayPal's sandbox the payment just gets stuck on "Processing." Totally stumped. Thanks!
-(void)payWithPayPal {
NSString *shortDescription = [NSString stringWithFormat:#"%i %#", [Global sharedInstance].currentOrder.itemQuantity, [Global sharedInstance].currentOrder.boozeBrand];
NSDecimalNumber *paymentDecimal = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:#"%.02f", [Global sharedInstance].currentOrder.itemPrice]];
NSString *sku = [NSString stringWithFormat:#"DBAR-%i", [Global sharedInstance].currentOrder.orderNumber];
NSString *name = [NSString stringWithFormat:#"%#", [Global sharedInstance].currentOrder.boozeBrand];
PayPalItem *item = [PayPalItem itemWithName:name
withQuantity:[Global sharedInstance].currentOrder.itemQuantity
withPrice:paymentDecimal
withCurrency:#"USD"
withSku:sku];
float priceFloat = [item.price floatValue];
float totalFloat = priceFloat * item.quantity;
NSDecimalNumber *total = [NSDecimalNumber decimalNumberWithString:[NSString stringWithFormat:#"%.02f", totalFloat]];
PayPalPayment *payment = [[PayPalPayment alloc] init];
payment.amount = total;
payment.currencyCode = #"USD";
payment.shortDescription = shortDescription;
payment.items = nil; // if not including multiple items, then leave payment.items as nil
payment.paymentDetails = nil; // if not including payment details, then leave payment.paymentDetails as nil
if (!payment.processable) {NSLog(#"Payment not processable.");}
// Update payPalConfig re accepting credit cards.
PayPalPaymentViewController *paymentViewController = [[PayPalPaymentViewController alloc] initWithPayment:payment configuration:self.payPalConfiguration delegate:self];
[self presentViewController:paymentViewController animated:YES completion:nil];
}
#pragma mark - PayPalDelegate
-(void)payPalPaymentViewController:(PayPalPaymentViewController *)paymentViewController willCompletePayment:(PayPalPayment *)completedPayment completionBlock:(PayPalPaymentDelegateCompletionBlock)completionBlock {
NSLog(#"Payment processing.");
//Stuck on this forever - this is what I'm trying to get past
}
-(void)payPalPaymentViewController:(PayPalPaymentViewController *)paymentViewController didCompletePayment:(PayPalPayment *)completedPayment {
//Never gets here
}
You issue is in the completion block of willCompletePayment, you need to return the completion block after you have complete the processing in that
to call the didCompletePayment
From Paypal code documentation
Your code MUST finish by calling the completionBlock.
completionBlock Block to execute when your processing is done.
so your code will be like
- (void)payPalPaymentViewController:(nonnull PayPalPaymentViewController *)paymentViewController
willCompletePayment:(nonnull PayPalPayment *)completedPayment
completionBlock:(nonnull PayPalPaymentDelegateCompletionBlock)completionBlock {
//do all the code you want
completionBlock();
}
After you write this completion block it will go to didCompletePayment, which can be like this:
- (void)payPalPaymentViewController:(PayPalPaymentViewController *)paymentViewController didCompletePayment:(PayPalPayment *)completedPayment {
NSLog(#"PayPal Payment Success!");
self.resultText = [completedPayment description];
[self showSuccess];
[self dismissViewControllerAnimated:YES completion:nil];
}
Another Option
By checking the code of Paypal example, it is not compulsory to implement the willCompletePayment method, you can skip this method and directly write didCompletePayment
in this way your code can be like this:
- (void)payPalPaymentViewController:(PayPalPaymentViewController *)paymentViewController didCompletePayment:(PayPalPayment *)completedPayment {
NSLog(#"PayPal Payment Success!");
self.resultText = [completedPayment description];
[self showSuccess];
[self sendCompletedPaymentToServer:completedPayment]; // Payment was processed successfully; send to your server for verification and fulfillment
[self dismissViewControllerAnimated:YES completion:nil];
}
Code documentation for the didCompletePayment from Paypal
Your code MAY deal with the completedPayment, if it did not already do
so within your optional
payPalPaymentViewController:willCompletePayment:completionBlock:
method.
By using that method you don't need to call willCompletePayment method and you will not face the issue which you have faced.

How to integrate PayPal/Apple Pay payment module in iOS App?

I am doing R&D on How to integrate PayPal/Apple Pay payment module in iOS App.
For example in my app i want to integrate PayPal/Apple pay for payment, then what should I do ? What are the process.
IF anyone can guide how to do it. Please suggest me the steps.
Any reference link then also welcome.
It depends on the payment solution you've integrated.
PayPal will support funding source of account balance or credit card/debit card/bank that is linked to the account. While unlike the PayPal wallet, there's no "balance" thing in the Apple Pay/Apple Wallet, which works purely with card tokenization (cards that you setup in your Wallet App).
In this use case, your app won't necessarily to check whether $20 is available in the wallet (either PayPal or Apple Pay), instead it will initiate the payment request, and get the response from the payment gateway to process your orders
in AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[PayPalMobile initializeWithClientIdsForEnvironments:#{PayPalEnvironmentProduction : #"YOUR_CLIENT_ID_FOR_PRODUCTION",
PayPalEnvironmentSandbox : #"AeB0tbkw-z4Ys3NvxekUZxnVNk26WXRodQBETFG4x-HtQAuqBf5k4edWOn2zia_l8RWBFJGEUNSVWJWg"}];
return YES;
}
with your Controller
in your .h File set delegate
#interface MyCart : UITableViewController
#property(nonatomic, strong, readwrite) PayPalConfiguration *payPalConfig;
in your .m File
- (void)viewDidLoad {
NSString *environment=#"sandbox";
self.environment = environment;
[PayPalMobile preconnectWithEnvironment:environment];
_payPalConfig = [[PayPalConfiguration alloc] init];
_payPalConfig.acceptCreditCards = YES;
_payPalConfig.merchantName = #"ScanPay";
_payPalConfig.merchantPrivacyPolicyURL = [NSURL URLWithString:#"https://www.paypal.com/webapps/mpp/ua/privacy-full"];
_payPalConfig.merchantUserAgreementURL = [NSURL URLWithString:#"https://www.paypal.com/webapps/mpp/ua/useragreement-full"];
_payPalConfig.languageOrLocale = [NSLocale preferredLanguages][0];
_payPalConfig.payPalShippingAddressOption = PayPalShippingAddressOptionPayPal;
}
Code with purchase button event
-(IBAction)btnCheckoutTapped
{
// UIAlertView *alt=[[UIAlertView alloc]initWithTitle:#"ScanPay" message:#"Under Development" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
// [alt show];
NSDecimalNumber *subtotal = [[NSDecimalNumber alloc]initWithDouble:Price];
// Optional: include payment details
NSDecimalNumber *shipping = [[NSDecimalNumber alloc] initWithString:#"0.00"];
NSDecimalNumber *tax = [[NSDecimalNumber alloc] initWithString:#"0.00"];
PayPalPaymentDetails *paymentDetails = [PayPalPaymentDetails paymentDetailsWithSubtotal:subtotal
withShipping:shipping
withTax:tax];
NSDecimalNumber *total = [[subtotal decimalNumberByAdding:shipping] decimalNumberByAdding:tax];
PayPalPayment *payment = [[PayPalPayment alloc] init];
payment.amount = total;
payment.currencyCode = #"USD";
payment.shortDescription = #"You Pay";
payment.paymentDetails = paymentDetails; // if not including payment details, then leave payment.paymentDetails as nil
if (!payment.processable) {
// This particular payment will always be processable. If, for
// example, the amount was negative or the shortDescription was
// empty, this payment wouldn't be processable, and you'd want
// to handle that here.
}
// Update payPalConfig re accepting credit cards.
self.payPalConfig.acceptCreditCards = YES;
PayPalPaymentViewController *paymentViewController = [[PayPalPaymentViewController alloc] initWithPayment:payment
configuration:self.payPalConfig
delegate:self];
[self presentViewController:paymentViewController animated:YES completion:nil];
}
PayPalPaymentDelegate methods
- (void)payPalPaymentViewController:(PayPalPaymentViewController *)paymentViewController didCompletePayment:(PayPalPayment *)completedPayment {
NSLog(#"PayPal Payment Success!");
[self ErrorWithString:#"PayPal Payment Success!"];
self.resultText = [completedPayment description];
//[self showSuccess];
[self sendCompletedPaymentToServer:completedPayment]; // Payment was processed successfully; send to server for verification and fulfillment
[self dismissViewControllerAnimated:YES completion:nil];
ReceiptScreen *obj=[self.storyboard instantiateViewControllerWithIdentifier:#"ReceiptScreen"];
[self.navigationController pushViewController:obj animated:YES];
}
- (void)payPalPaymentDidCancel:(PayPalPaymentViewController *)paymentViewController {
NSLog(#"PayPal Payment Canceled");
self.resultText = nil;
// self.successView.hidden = YES;
[self dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark Proof of payment validation
- (void)sendCompletedPaymentToServer:(PayPalPayment *)completedPayment {
// TODO: Send completedPayment.confirmation to server
NSLog(#"Here is your proof of payment:\n\n%#\n\nSend this to your server for confirmation and fulfillment.", completedPayment.confirmation);
}
PayPal - Here is complete PayPal sample code suggested by https://developer.paypal.com, PayPal Developer Guide and Sample code
Apple Pay - You can check it apple's demo code
I hope you are looking for it. :)

Setup Paypal client ID for credentials IOS SDK 2.1.6

Im using Paypal SDK in my app. I set my environment into PayPalEnvironmentSandbox but when I run my app theres an alert saying "There was a problem communicating with the Paypal servers. Please Try again". I googled a lot of times, other said that I need to change the clientId but i dont know how to change the client Id, I have a test account on sandbox in paypal but i dont know how to implement them in my app. I read the documentation and they said that I need to change may Client Id something like that but i dont know how. Need your help guys thank you. I am using iOS paypal SDK 2.1.6.
Code:
#import "ZZMainViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "PayPalMobile.h"
// Set the environment:
// - For live charges, use PayPalEnvironmentProduction (default).
// - To use the PayPal sandbox, use PayPalEnvironmentSandbox.
// - For testing, use PayPalEnvironmentNoNetwork.
//#define kPayPalEnvironment PayPalEnvironmentNoNetwork
#define kPayPalEnvironment PayPalEnvironmentSandbox
#interface ZZMainViewController ()
#property(nonatomic, strong, readwrite) IBOutlet UIButton *payNowButton;
#property(nonatomic, strong, readwrite) IBOutlet UIButton *payFutureButton;
#property(nonatomic, strong, readwrite) IBOutlet UIView *successView;
#property(nonatomic, strong, readwrite) PayPalConfiguration *payPalConfig;
#end
#implementation ZZMainViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
// Set up payPalConfig
_payPalConfig = [[PayPalConfiguration alloc] init];
_payPalConfig.acceptCreditCards = YES;
_payPalConfig.languageOrLocale = #"en";
_payPalConfig.merchantName = #"Awesome Shirts, Inc.";
_payPalConfig.merchantPrivacyPolicyURL = [NSURL URLWithString:#"https://www.paypal.com/webapps/mpp/ua/privacy-full"];
_payPalConfig.merchantUserAgreementURL = [NSURL URLWithString:#"https://www.paypal.com/webapps/mpp/ua/useragreement-full"];
// Setting the languageOrLocale property is optional.
//
// If you do not set languageOrLocale, then the PayPalPaymentViewController will present
// its user interface according to the device's current language setting.
//
// Setting languageOrLocale to a particular language (e.g., #"es" for Spanish) or
// locale (e.g., #"es_MX" for Mexican Spanish) forces the PayPalPaymentViewController
// to use that language/locale.
//
// For full details, including a list of available languages and locales, see PayPalPaymentViewController.h.
_payPalConfig.languageOrLocale = [NSLocale preferredLanguages][0];
// Do any additional setup after loading the view, typically from a nib.
self.successView.hidden = YES;
// use default environment, should be Production in real life
//self.environment = kPayPalEnvironment;
//self.environment = PayPalEnvironmentSandbox;
[PayPalMobile preconnectWithEnvironment:PayPalEnvironmentSandbox];
NSLog(#"PayPal iOS SDK version: %#", [PayPalMobile libraryVersion]);
[self pay];
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:YES];
// Preconnect to PayPal early
[PayPalMobile preconnectWithEnvironment:PayPalEnvironmentSandbox];
}
#pragma mark - Receive Single Payment
- (void)pay {
// Remove our last completed payment, just for demo purposes.
self.resultText = nil;
// Note: For purposes of illustration, this example shows a payment that includes
// both payment details (subtotal, shipping, tax) and multiple items.
// You would only specify these if appropriate to your situation.
// Otherwise, you can leave payment.items and/or payment.paymentDetails nil,
// and simply set payment.amount to your total charge.
// Optional: include multiple items
PayPalItem *item1 = [PayPalItem itemWithName:#"Old jeans with holes"
withQuantity:2
withPrice:[NSDecimalNumber decimalNumberWithString:#"84.99"]
withCurrency:#"USD"
withSku:#"Hip-00037"];
PayPalItem *item2 = [PayPalItem itemWithName:#"Free rainbow patch"
withQuantity:1
withPrice:[NSDecimalNumber decimalNumberWithString:#"0.00"]
withCurrency:#"USD"
withSku:#"Hip-00066"];
PayPalItem *item3 = [PayPalItem itemWithName:#"Long-sleeve plaid shirt (mustache not included)"
withQuantity:1
withPrice:[NSDecimalNumber decimalNumberWithString:#"37.99"]
withCurrency:#"USD"
withSku:#"Hip-00291"];
NSArray *items = #[item1, item2, item3];
NSDecimalNumber *subtotal = [PayPalItem totalPriceForItems:items];
// Optional: include payment details
NSDecimalNumber *shipping = [[NSDecimalNumber alloc] initWithString:#"5.99"];
NSDecimalNumber *tax = [[NSDecimalNumber alloc] initWithString:#"2.50"];
PayPalPaymentDetails *paymentDetails = [PayPalPaymentDetails paymentDetailsWithSubtotal:subtotal
withShipping:shipping
withTax:tax];
NSDecimalNumber *total = [[subtotal decimalNumberByAdding:shipping] decimalNumberByAdding:tax];
PayPalPayment *payment = [[PayPalPayment alloc] init];
payment.amount = total;
payment.currencyCode = #"USD";
payment.shortDescription = #"Hipster clothing";
payment.items = items; // if not including multiple items, then leave payment.items as nil
payment.paymentDetails = paymentDetails; // if not including payment details, then leave payment.paymentDetails as nil
if (!payment.processable) {
// This particular payment will always be processable. If, for
// example, the amount was negative or the shortDescription was
// empty, this payment wouldn't be processable, and you'd want
// to handle that here.
}
// Update payPalConfig re accepting credit cards.
self.payPalConfig.acceptCreditCards = self.acceptCreditCards;
PayPalPaymentViewController *paymentViewController = [[PayPalPaymentViewController alloc] initWithPayment:payment
configuration:self.payPalConfig
delegate:self];
[self presentViewController:paymentViewController animated:YES completion:nil];
}
#pragma mark PayPalPaymentDelegate methods
- (void)payPalPaymentViewController:(PayPalPaymentViewController *)paymentViewController didCompletePayment:(PayPalPayment *)completedPayment {
NSLog(#"PayPal Payment Success!");
self.resultText = [completedPayment description];
[self showSuccess];
[self sendCompletedPaymentToServer:completedPayment]; // Payment was processed successfully; send to server for verification and fulfillment
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)payPalPaymentDidCancel:(PayPalPaymentViewController *)paymentViewController {
NSLog(#"PayPal Payment Canceled");
self.resultText = nil;
self.successView.hidden = YES;
[self dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark Proof of payment validation
- (void)sendCompletedPaymentToServer:(PayPalPayment *)completedPayment {
// TODO: Send completedPayment.confirmation to server
NSLog(#"Here is your proof of payment:\n\n%#\n\nSend this to your server for confirmation and fulfillment.", completedPayment.confirmation);
}
#pragma mark - Authorize Future Payments
- (IBAction)getUserAuthorization:(id)sender {
PayPalFuturePaymentViewController *futurePaymentViewController = [[PayPalFuturePaymentViewController alloc] initWithConfiguration:self.payPalConfig delegate:self];
[self presentViewController:futurePaymentViewController animated:YES completion:nil];
}
#pragma mark PayPalFuturePaymentDelegate methods
- (void)payPalFuturePaymentViewController:(PayPalFuturePaymentViewController *)futurePaymentViewController didAuthorizeFuturePayment:(NSDictionary *)futurePaymentAuthorization {
NSLog(#"PayPal Future Payment Authorization Success!");
self.resultText = futurePaymentAuthorization[#"code"];
[self showSuccess];
[self sendAuthorizationToServer:futurePaymentAuthorization];
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)payPalFuturePaymentDidCancel:(PayPalFuturePaymentViewController *)futurePaymentViewController {
NSLog(#"PayPal Future Payment Authorization Canceled");
self.successView.hidden = YES;
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)sendAuthorizationToServer:(NSDictionary *)authorization {
// TODO: Send authorization to server
NSLog(#"Here is your authorization:\n\n%#\n\nSend this to your server to complete future payment setup.", authorization);
}
#pragma mark - Helpers
- (void)showSuccess {
self.successView.hidden = NO;
self.successView.alpha = 1.0f;
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.5];
[UIView setAnimationDelay:2.0];
self.successView.alpha = 0.0f;
[UIView commitAnimations];
}
#pragma mark - Flipside View Controller
- (void)flipsideViewControllerDidFinish:(ZZFlipsideViewController *)controller {
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
[self dismissViewControllerAnimated:YES completion:nil];
} else {
[self.flipsidePopoverController dismissPopoverAnimated:YES];
self.flipsidePopoverController = nil;
}
}
- (void)popoverControllerDidDismissPopover:(UIPopoverController *)popoverController {
self.flipsidePopoverController = nil;
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([[segue identifier] isEqualToString:#"pushSettings"]) {
[[segue destinationViewController] setDelegate:self];
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
UIPopoverController *popoverController = [(UIStoryboardPopoverSegue *)segue popoverController];
self.flipsidePopoverController = popoverController;
popoverController.delegate = self;
}
}
}
- (IBAction)togglePopover:(id)sender {
if (self.flipsidePopoverController) {
[self.flipsidePopoverController dismissPopoverAnimated:YES];
self.flipsidePopoverController = nil;
} else {
[self performSegueWithIdentifier:#"showAlternate" sender:sender];
}
}
#end
Dave from PayPal here.
To set your client IDs (one for Sandbox, one for Live), see step 1 in our Sample Code:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// ...
[PayPalMobile initializeWithClientIdsForEnvironments:#{PayPalEnvironmentProduction : #"YOUR_CLIENT_ID_FOR_PRODUCTION",
PayPalEnvironmentSandbox : #"YOUR_CLIENT_ID_FOR_SANDBOX"}];
// ...
return YES;
}
For Swift development
[PayPalMobile initializeWithClientIdsForEnvironments:#{PayPalEnvironmentProduction :#"YOUR_CLIENT_ID_FOR_PRODUCTION",
PayPalEnvironmentSandbox : #"ATIXyxAAjtL8-HdqfLq0kTCeefUi1SNI_xkfWktHelloqznRxsrm_Hello"}];
Will not work you need to do instead
PayPalMobile.initializeWithClientIdsForEnvironments([PayPalEnvironmentProduction: "ID1", PayPalEnvironmentSandbox: "ID2"])
To get a client_id you need to register & create an app at https://developer.paypal.com/webapps/developer/applications/myapps. You will then get sandbox (and live) credentials.
you have to change inside appdelegate.m file.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { #warning "Enter your credentials"
[PayPalMobile initializeWithClientIdsForEnvironments:#{PayPalEnvironmentProduction : #"YOUR_CLIENT_ID_FOR_PRODUCTION",
PayPalEnvironmentSandbox : #"ATIXyxAAjtL8-HdqfLq0kTCeefUi1SNI_xkfWktHelloqznRxsrm_Hello"}]; return YES;}

PayPal iOS SDK 2.0.5 is not authenticating email id and password correctly

hii everyone i am new on this professional site.actually i have a problem in PayPal iOS SDK 2.0.5. This sdk is downloaded from github and now when I tried to logged in paypal then it is not authenticating Can anyone tell that why is this happening and payment is also not transferred in business account from personal account
Thankx
Please help me
here is the link
https://github.com/paypal/PayPal-iOS-SDK/archive/master.zip
#define kPayPalEnvironment PayPalEnvironmentNoNetwork
#interface ZZMainViewController ()
#property(nonatomic, strong, readwrite) IBOutlet UIButton *payNowButton;
#property(nonatomic, strong, readwrite) IBOutlet UIButton *payFutureButton;
#property(nonatomic, strong, readwrite) IBOutlet UIView *successView;
#property(nonatomic, strong, readwrite) PayPalConfiguration *payPalConfig;
#end
#implementation ZZMainViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.title = #"PayPal SDK Demo";
// Set up payPalConfig
_payPalConfig = [[PayPalConfiguration alloc] init];
_payPalConfig.acceptCreditCards = YES;
_payPalConfig.languageOrLocale = #"en";
_payPalConfig.merchantName = #"Awesome Shirts, Inc.";
_payPalConfig.merchantPrivacyPolicyURL = [NSURL URLWithString:#"https://www.paypal.com/webapps/mpp/ua/privacy-full"];
_payPalConfig.merchantUserAgreementURL = [NSURL URLWithString:#"https://www.paypal.com/webapps/mpp/ua/useragreement-full"];
// Setting the languageOrLocale property is optional.
//
// If you do not set languageOrLocale, then the PayPalPaymentViewController will present
// its user interface according to the device's current language setting.
//
// Setting languageOrLocale to a particular language (e.g., #"es" for Spanish) or
// locale (e.g., #"es_MX" for Mexican Spanish) forces the PayPalPaymentViewController
// to use that language/locale.
//
// For full details, including a list of available languages and locales, see PayPalPaymentViewController.h.
_payPalConfig.languageOrLocale = [NSLocale preferredLanguages][0];
// Do any additional setup after loading the view, typically from a nib.
self.successView.hidden = YES;
// use default environment, should be Production in real life
self.environment = kPayPalEnvironment;
NSLog(#"PayPal iOS SDK version: %#", [PayPalMobile libraryVersion]);
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:YES];
// Preconnect to PayPal early
[PayPalMobile preconnectWithEnvironment:self.environment];
}
#pragma mark - Receive Single Payment
- (IBAction)pay {
// Remove our last completed payment, just for demo purposes.
self.resultText = nil;
PayPalPayment *payment = [[PayPalPayment alloc] init];
payment.amount = [[NSDecimalNumber alloc] initWithString:#"9.95"];
payment.currencyCode = #"USD";
payment.shortDescription = #"Hipster t-shirt";
if (!payment.processable) {
// This particular payment will always be processable. If, for
// example, the amount was negative or the shortDescription was
// empty, this payment wouldn't be processable, and you'd want
// to handle that here.
}
// Update payPalConfig re accepting credit cards.
self.payPalConfig.acceptCreditCards = self.acceptCreditCards;
PayPalPaymentViewController *paymentViewController = [[PayPalPaymentViewController alloc] initWithPayment:payment
configuration:self.payPalConfig
delegate:self];
[self presentViewController:paymentViewController animated:YES completion:nil];
}
- (void)payPalPaymentViewController:(PayPalPaymentViewController *)paymentViewController didCompletePayment:(PayPalPayment *)completedPayment {
NSLog(#"PayPal Payment Success!");
self.resultText = [completedPayment description];
[self showSuccess];
[self sendCompletedPaymentToServer:completedPayment]; // Payment was processed successfully; send to server for verification and fulfillment
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)payPalPaymentDidCancel:(PayPalPaymentViewController *)paymentViewController {
NSLog(#"PayPal Payment Canceled");
self.resultText = nil;
self.successView.hidden = YES;
[self dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark Proof of payment validation
- (void)sendCompletedPaymentToServer:(PayPalPayment *)completedPayment {
// TODO: Send completedPayment.confirmation to server
NSLog(#"Here is your proof of payment:\n\n%#\n\nSend this to your server for c onfirmation and fulfillment.", completedPayment.confirmation);
}
#pragma mark - Authorize Future Payments
- (IBAction)getUserAuthorization:(id)sender {
PayPalFuturePaymentViewController *futurePaymentViewController = [[PayPalFuturePaymentViewController alloc] initWithConfiguration:self.payPalConfig delegate:self];
[self presentViewController:futurePaymentViewController animated:YES completion:nil];
}
#pragma mark PayPalFuturePaymentDelegate methods
- (void)payPalFuturePaymentViewController:(PayPalFuturePaymentViewController *)futurePaymentViewController didAuthorizeFuturePayment:(NSDictionary *)futurePaymentAuthorization {
NSLog(#"PayPal Future Payment Authorization Success!");
self.resultText = futurePaymentAuthorization[#"code"];
[self showSuccess];
[self sendAuthorizationToServer:futurePaymentAuthorization];
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)payPalFuturePaymentDidCancel:(PayPalFuturePaymentViewController *)futurePaymentViewController {
NSLog(#"PayPal Future Payment Authorization Canceled");
self.successView.hidden = YES;
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)sendAuthorizationToServer:(NSDictionary *)authorization {
// TODO: Send authorization to server
NSLog(#"Here is your authorization:\n\n%#\n\nSend this to your server to complete future payment setup.", authorization);
}
#pragma mark - Helpers
- (void)showSuccess {
self.successView.hidden = NO;
self.successView.alpha = 1.0f;
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.5];
[UIView setAnimationDelay:2.0];
self.successView.alpha = 0.0f;
[UIView commitAnimations];
}
#pragma mark - Flipside View Controller
- (void)flipsideViewControllerDidFinish:(ZZFlipsideViewController *)controller {
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
[self dismissViewControllerAnimated:YES completion:nil];
} else {
[self.flipsidePopoverController dismissPopoverAnimated:YES];
self.flipsidePopoverController = nil;
}
}
- (void)popoverControllerDidDismissPopover:(UIPopoverController *)popoverController {
self.flipsidePopoverController = nil;
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([[segue identifier] isEqualToString:#"pushSettings"]) {
[[segue destinationViewController] setDelegate:self];
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
UIPopoverController *popoverController = [(UIStoryboardPopoverSegue *)segue popoverController];
self.flipsidePopoverController = popoverController;
popoverController.delegate = self;
}
}
}
- (IBAction)togglePopover:(id)sender {
if (self.flipsidePopoverController) {
[self.flipsidePopoverController dismissPopoverAnimated:YES];
self.flipsidePopoverController = nil;
} else {
[self performSegueWithIdentifier:#"showAlternate" sender:sender];
}
}
#end
You are not authenticating the email and password because you have your environment set to PayPalEnvironmentNoNetwork. Setting it to NoNetwork sets it to a "mock" environment and just simulates the actions. You'll need to set the environment to either Live or Sandbox in order to process/authenticate with those environments. The below code is the relevant snippet that you need to look at...
// Set the environment:
// - For live charges, use PayPalEnvironmentProduction (default).
// - To use the PayPal sandbox, use PayPalEnvironmentSandbox.
// - For testing, use PayPalEnvironmentNoNetwork.
#define kPayPalEnvironment PayPalEnvironmentSandbox

FBSessionDelegate methods not firing

I'm attempting to implement the latest Facebook Connect SDK and I'm having some troubles. For some reason the delegate callbacks for FBSessionDelegate protocol are not being fired. I've followed the instructions on the git Facebook page and tried to mimic the Facebook sample app but no luck. I'm going crazy here so I'm gonna post my code and maybe somebody will see something silly that I've missed.
#import <Foundation/Foundation.h>
#import "FBConnect.h"
#interface FacebookWrapper : UIViewController <FBSessionDelegate, FBRequestDelegate, FBDialogDelegate>{
Facebook* _facebook;
NSArray* _permissions;
}
#property(readonly) Facebook *facebook;
- (void)login;
#end
#import "FacebookWrapper.h"
static NSString* kAppId = #"1234455667778";
#implementation FacebookWrapper
#synthesize facebook = _facebook;
- (id)init {
if (self = [super init]) {
_permissions = [[NSArray arrayWithObjects: #"read_stream", #"offline_access",nil] retain];
_facebook = [[Facebook alloc] initWithAppId:kAppId];
}
return self;
}
- (void)dealloc {
[_facebook release];
[_permissions release];
[super dealloc];
}
- (void)login {
[_facebook authorize:_permissions delegate:self];
}
- (void)fbDidLogin {
NSLog(#"Did Log In");
}
- (void)fbDidNotLogin:(BOOL)cancelled {
NSLog(#"Failed to log in");
}
- (void)fbDidLogout {
NSLog(#"Logged Out");
}
And to call this from another class,
FacebookWrapper *fw = [[FacebookWrapper alloc] init];
[fw login];
The behavior that I'm seeing on the phone is as expected. The Facebook app launches on init and permissions are requested. The phone then brings my app back to the foreground but the delegates for FBSessionDelegate are never fired. I've tried this in the Facebook sample app using my app ID and it worked fine. I have no idea what the difference is.
I figured out the problem. In the App Delegate you need to override handleOpenURL.
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
return [[facebookWrapper facebook] handleOpenURL:url];
}
If you're creating a wrapper class as I am you'll need an instance of it in the app delegate so you can call the hanleOpenURL method in the Facebook class. Also notice that there is a public readonly property for my Facebook instance in my FacebookWrapper class so I can call handlOpenURL.
By doing this your app will know where to continue when it returns from getting permissions inside of the Facebook app.
I have developed wrapper class which will be very helpful to you.
First download latest SDK of Facebook.
Create one class named as "FacebookHelper"
Add following code in .h file:
#import <Foundation/Foundation.h>
#import "FBConnect.h"
#protocol FBApiCallDelegate;
typedef enum FBApiCallType
{
FBApiCallNone = 0,
FBApiCallGetUserInfo = 1,
FBApiCallGetUserFriend = 2,
FBApiCallPostMessage = 3,
FBApiCallPostPicture = 4,
FBApiCallShareLink = 5,
FBApiCallPostAll = 6,
FBApiCallPostMessageFriendWall = 7
} FBApiCallType;
#interface FacebookHelper : NSObject<FBRequestDelegate, FBDialogDelegate, FBSessionDelegate> {
Facebook *objFacebook;
NSArray *arrPermission;
id<FBApiCallDelegate> apiCallDelegate;
FBApiCallType currentApiCallType;
NSString *strMessage;
NSString *strUrlTitle;
NSString *strUrl;
NSString *strCaption;
NSString *strPictureUrl;
UIImage *image;
}
#property(readonly) Facebook *objFacebook;
#property (nonatomic, assign) id<FBApiCallDelegate> apiCallDelegate;
#property (nonatomic, assign) FBApiCallType currentApiCallType;
#property (nonatomic, retain) NSString *strMessage;
#property (nonatomic, retain) NSString *strUrlTitle;
#property (nonatomic, retain) NSString *strUrl;
#property (nonatomic, retain) NSString *strCaption;
#property (nonatomic, retain) NSString *strPictureUrl;
#property (nonatomic, retain) UIImage *image;
+ (FacebookHelper *) sharedInstance;
- (void)releaseObjects;
//Store Authentication
- (void)storeAuthData:(NSString *)accessToken expiresAt:(NSDate *)expiresAt;
- (void)removeAuthData;
//Public Methods
-(BOOL)isLoggedIn;
-(void)loginToFacebook;
-(void)logoutFromFacebook;
//Facebook Methods
-(void)getUserInfo; //Get User Info
-(void)getUserFriends; //Get User's Friend List
-(void)postMessageToWall; //Post Message to FB Wall
-(void)postPictureToWall; //Post Picture to FB Wall
-(void)shareLinkOnWall; //Share Link on FB Wall
-(void)postAllToWall; //Post All - Message, Link, Caption, PhotoUrl
-(void)postMessageToFriendWall; //Post Message to Friend Wall
//String Methods
- (BOOL)isEmptyString:(NSString *)strValue;
- (NSString *) trimWhiteSpace:(NSString *)strValue;
// Default AlertView
-(void)showAlertView:(NSString *)pstrTitle withMessage:(NSString *)pstrMessage delegate:(id)pDelegate;
#end
#protocol FBApiCallDelegate <NSObject>
#optional
//Get User Info Delegate
-(void)finishUserInfoResponse:(id)result;
-(void)failedUserInfoResponse:(NSError *)error;
//Get User's Friend List
-(void)finishUserFriendResponse:(id)result;
-(void)failedUserFriendResponse:(NSError *)error;
//Post Message to FB Wall Delegate
-(void)finishPostMessageResponse:(id)result;
-(void)failedPostMessageResponse:(NSError *)error;
//Post Picture to FB Wall
-(void)finishPostPictureResponse:(id)result;
-(void)failedPostPictureResponse:(NSError *)error;
//Share Link on FB Wall
-(void)finishShareLinkResponse:(id)result;
-(void)failedShareLinkResponse:(NSError *)error;
//Post All - Message, Link, Caption, PhotoUrl
-(void)finishPostAllResponse:(id)result;
-(void)failedPostAllResponse:(NSError *)error;
//Post Message to Friend Wall Delegate
-(void)finishPostMsgFriendWallResponse:(id)result;
-(void)failedPostMsgFriendWallResponse:(NSError *)error;
#end
Add following code in .m file:
#import "FacebookHelper.h"
#implementation FacebookHelper
#synthesize objFacebook;
#synthesize apiCallDelegate, currentApiCallType;
#synthesize strMessage, strUrlTitle, strUrl, strCaption, strPictureUrl, image;
#pragma mark -
#pragma mark Singleton Variables
static FacebookHelper *singletonHelper = nil;
#pragma mark -
#pragma mark Singleton Methods
- (id)init {
if (!g_kFacebookAppId) {
NSLog(#"%#", msgFBAppIDMissing);
exit(1);
return nil;
}
if ((self = [super init])) {
arrPermission = [[NSArray arrayWithObjects: #"read_stream", #"publish_stream", #"offline_access", #"email", #"read_friendlists", #"friends_birthday",nil] retain];
}
return self;
}
+ (FacebookHelper *)sharedInstance {
#synchronized(self) {
if (singletonHelper == nil) {
[[self alloc] init]; // assignment not done here
}
}
return singletonHelper;
}
+ (id)allocWithZone:(NSZone *)zone {
#synchronized(self) {
if (singletonHelper == nil) {
singletonHelper = [super allocWithZone:zone];
// assignment and return on first allocation
return singletonHelper;
}
}
// on subsequent allocation attempts return nil
return nil;
}
- (id)copyWithZone:(NSZone *)zone {
return self;
}
- (id)retain {
return self;
}
- (unsigned)retainCount {
return UINT_MAX; // denotes an object that cannot be released
}
//- (void)release {
- (void)dealloc {
[self releaseObjects];
[super dealloc];
}
- (id)autorelease {
return self;
}
- (void)releaseObjects {
[self.strMessage release];
[self.strUrlTitle release];
[self.strUrl release];
[self.strCaption release];
[self.strPictureUrl release];
[self.image release];
[objFacebook release];
objFacebook = nil;
}
#pragma mark -
#pragma mark FBDelegate(FBSessionDelegate) Methods
/**
* Called when the user has logged in successfully.
*/
- (void)fbDidLogin {
NSLog(#"FB login OK");
[self storeAuthData:objFacebook.accessToken expiresAt:objFacebook.expirationDate];
switch(currentApiCallType)
{
case FBApiCallGetUserInfo:
[self getUserInfo];
break;
case FBApiCallGetUserFriend:
[self getUserFriends];
break;
case FBApiCallPostMessage:
[self postMessageToWall];
break;
case FBApiCallPostPicture:
[self postPictureToWall];
break;
case FBApiCallShareLink:
[self shareLinkOnWall];
break;
case FBApiCallPostAll:
[self postAllToWall];
break;
case FBApiCallPostMessageFriendWall:
[self postMessageToFriendWall];
break;
}
}
/**
* Called when the user canceled the authorization dialog.
*/
-(void)fbDidNotLogin:(BOOL)cancelled {
NSLog(#"FB did not login");
[self removeAuthData];
}
/**
* Called when the request logout has succeeded.
*/
- (void)fbDidLogout {
NSLog(#"FB logout OK");
[self removeAuthData];
}
-(void)fbDidExtendToken:(NSString *)accessToken expiresAt:(NSDate *)expiresAt {
NSLog(#"token extended");
[self storeAuthData:accessToken expiresAt:expiresAt];
}
/**
* Called when the session has expired.
*/
- (void)fbSessionInvalidated {
[self showAlertView:msgFBSessionInvalidateTitle withMessage:msgFBSessionInvalidateMessage delegate:nil];
[self fbDidLogout];
}
#pragma mark -
#pragma mark FBRequestDelegate Methods
/**
* Called when the Facebook API request has returned a response. This callback
* gives you access to the raw response. It's called before
* (void)request:(FBRequest *)request didLoad:(id)result,
* which is passed the parsed response object.
*/
- (void)request:(FBRequest *)request didReceiveResponse:(NSURLResponse *)response {
NSLog(#"received response");
}
/**
* Called when a request returns and its response has been parsed into
* an object. The resulting object may be a dictionary, an array, a string,
* or a number, depending on the format of the API response. If you need access
* to the raw response, use:
*
* (void)request:(FBRequest *)request
* didReceiveResponse:(NSURLResponse *)response
*/
- (void)request:(FBRequest *)request didLoad:(id)result {
NSLog(#"FB request OK");
switch(currentApiCallType)
{
case FBApiCallGetUserInfo:
if([self.apiCallDelegate respondsToSelector:#selector(finishUserInfoResponse:)])
[self.apiCallDelegate finishUserInfoResponse:result];
break;
case FBApiCallGetUserFriend:
if ([self.apiCallDelegate respondsToSelector:#selector(finishUserFriendResponse:)])
[self.apiCallDelegate finishUserFriendResponse:result];
break;
case FBApiCallPostMessage:
if ([self.apiCallDelegate respondsToSelector:#selector(finishPostMessageResponse:)])
[self.apiCallDelegate finishPostMessageResponse:result];
break;
case FBApiCallPostPicture:
if ([self.apiCallDelegate respondsToSelector:#selector(finishPostPictureResponse:)])
[self.apiCallDelegate finishPostPictureResponse:result];
break;
case FBApiCallShareLink:
if ([self.apiCallDelegate respondsToSelector:#selector(finishShareLinkResponse:)])
[self.apiCallDelegate finishShareLinkResponse:result];
break;
case FBApiCallPostAll:
if ([self.apiCallDelegate respondsToSelector:#selector(finishPostAllResponse:)])
[self.apiCallDelegate finishPostAllResponse:result];
break;
case FBApiCallPostMessageFriendWall:
if ([self.apiCallDelegate respondsToSelector:#selector(finishPostMsgFriendWallResponse:)])
[self.apiCallDelegate finishPostMsgFriendWallResponse:result];
break;
}
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
currentApiCallType = FBApiCallNone;
}
/**
* Called when an error prevents the Facebook API request from completing
* successfully.
*/
/*- (void)request:(FBRequest *)request didFailWithError:(NSError *)error {
NSLog(#"FB error: %#", [error localizedDescription]);
}*/
- (void)request:(FBRequest *)request didFailWithError:(NSError *)error {
NSLog(#"Err message: %#", [[error userInfo] objectForKey:#"error_msg"]);
/*NSLog(#"Err code: %#", [error code]);
NSLog(#"Err desc: %#", [error description]);
NSLog(#"FB error: %#", [error localizedDescription]);*/
switch(currentApiCallType)
{
case FBApiCallGetUserInfo:
if ([self.apiCallDelegate respondsToSelector:#selector(failedUserInfoResponse:)])
[self.apiCallDelegate failedUserInfoResponse:error];
break;
case FBApiCallGetUserFriend:
if ([self.apiCallDelegate respondsToSelector:#selector(failedUserFriendResponse:)])
[self.apiCallDelegate failedUserFriendResponse:error];
break;
case FBApiCallPostMessage:
if ([self.apiCallDelegate respondsToSelector:#selector(failedPostMessageResponse:)])
[self.apiCallDelegate failedPostMessageResponse:error];
break;
case FBApiCallPostPicture:
if ([self.apiCallDelegate respondsToSelector:#selector(failedPostPictureResponse:)])
[self.apiCallDelegate failedPostPictureResponse:error];
break;
case FBApiCallShareLink:
if ([self.apiCallDelegate respondsToSelector:#selector(failedShareLinkResponse:)])
[self.apiCallDelegate failedShareLinkResponse:error];
break;
case FBApiCallPostAll:
if ([self.apiCallDelegate respondsToSelector:#selector(failedPostAllResponse:)])
[self.apiCallDelegate failedPostAllResponse:error];
case FBApiCallPostMessageFriendWall:
if ([self.apiCallDelegate respondsToSelector:#selector(failedPostMsgFriendWallResponse:)])
[self.apiCallDelegate failedPostMsgFriendWallResponse:error];
break;
}
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
currentApiCallType = FBApiCallNone;
}
/**
* Called when a UIServer Dialog successfully return.
*/
- (void)dialogDidComplete:(FBDialog *)dialog {
NSLog(#"Published successfully on FB");
}
#pragma mark -
#pragma mark Store/Remove Authentication
- (void)storeAuthData:(NSString *)accessToken expiresAt:(NSDate *)expiresAt {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:accessToken forKey:g_kFacebookAccessToken];
[defaults setObject:expiresAt forKey:g_kFacebookExpirationDate];
[defaults synchronize];
}
- (void)removeAuthData{
// Remove saved authorization information if it exists and it is
// ok to clear it (logout, session invalid, app unauthorized)
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults removeObjectForKey:g_kFacebookAccessToken];
[defaults removeObjectForKey:g_kFacebookExpirationDate];
[defaults synchronize];
/*
[[NSUserDefaults standardUserDefaults] setObject:#"" forKey:g_kFacebookAccessToken];
[[NSUserDefaults standardUserDefaults] setObject:#"" forKey:g_kFacebookExpirationDate];
[[NSUserDefaults standardUserDefaults] synchronize];*/
/*
[[NSUserDefaults standardUserDefaults] setObject:nil forKey:g_kFacebookAccessToken];
[[NSUserDefaults standardUserDefaults] setObject:nil forKey:g_kFacebookExpirationDate];
[[NSUserDefaults standardUserDefaults] synchronize];*/
}
#pragma mark -
#pragma mark Public Methods
-(BOOL)isLoggedIn
{
if(objFacebook == nil)
objFacebook = [[[Facebook alloc] initWithAppId:g_kFacebookAppId andDelegate:self] retain];
NSString *strAccessToken = [[NSUserDefaults standardUserDefaults] stringForKey:g_kFacebookAccessToken];
NSLog(#"Access Token = %#", strAccessToken);
//if(![strAccessToken isEmptyString])
if(![self isEmptyString:strAccessToken])
{
objFacebook.accessToken = [[NSUserDefaults standardUserDefaults] stringForKey:g_kFacebookAccessToken];
objFacebook.expirationDate = (NSDate *) [[NSUserDefaults standardUserDefaults] objectForKey:g_kFacebookExpirationDate];
}
if([objFacebook isSessionValid])
return YES;
else
return NO;
return NO;
}
-(void)loginToFacebook
{
if(![self isLoggedIn])
[objFacebook authorize:arrPermission];
}
-(void)logoutFromFacebook {
[objFacebook logout:self];
[self removeAuthData];
[self releaseObjects];
}
#pragma mark -
#pragma mark Facebook Methods
-(void)getUserInfo
{
currentApiCallType = FBApiCallGetUserInfo;
if([self isLoggedIn])
{
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:#"name,picture",#"fields",nil];
[objFacebook requestWithGraphPath:#"me" andParams:params andDelegate:self];
}
else
[self loginToFacebook];
}
-(void)getUserFriends
{
currentApiCallType = FBApiCallGetUserFriend;
if([self isLoggedIn])
{
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:#"picture,id,name,birthday,link,gender,last_name,first_name",#"fields",nil];
[objFacebook requestWithGraphPath:#"me/friends" andParams:params andDelegate:self];
}
else
[self loginToFacebook];
}
-(void)postMessageToWall
{
currentApiCallType = FBApiCallPostMessage;
if([self isLoggedIn])
{
NSMutableDictionary *params = [[[NSMutableDictionary alloc] init] autorelease];
[params setObject:#"status" forKey:#"type"];
[params setObject:self.strMessage forKey:#"message"];
[objFacebook requestWithGraphPath:#"me/feed" andParams:params andHttpMethod:#"POST" andDelegate:self];
}
else
[self loginToFacebook];
}
-(void)postPictureToWall
{
currentApiCallType = FBApiCallPostPicture;
if([self isLoggedIn])
{
NSMutableDictionary *params = [[[NSMutableDictionary alloc] init] autorelease];
[params setObject:self.image forKey:#"source"];
[params setObject:self.strMessage forKey:#"message"];
[objFacebook requestWithGraphPath:#"me/photos" andParams:params andHttpMethod:#"POST" andDelegate:self];
}
else
[self loginToFacebook];
}
-(void)shareLinkOnWall
{
currentApiCallType = FBApiCallShareLink;
if([self isLoggedIn])
{
NSMutableDictionary *params = [[[NSMutableDictionary alloc] init] autorelease];
[params setObject:#"link" forKey:#"type"];
[params setObject:self.strUrl forKey:#"link"];
[params setObject:self.strMessage forKey:#"description"];
[objFacebook requestWithGraphPath:#"me/feed" andParams:params andHttpMethod:#"POST" andDelegate:self];
}
else
[self loginToFacebook];
}
-(void)postAllToWall
{
currentApiCallType = FBApiCallPostAll;
if([self isLoggedIn])
{
NSMutableDictionary *params = [[[NSMutableDictionary alloc] init] autorelease];
[params setObject:self.strMessage forKey:#"description"];
[params setObject:self.strUrlTitle forKey:#"name"];
[params setObject:self.strUrl forKey:#"link"];
[params setObject:self.strCaption forKey:#"caption"];
[params setObject:self.strPictureUrl forKey:#"picture"];
[objFacebook requestWithGraphPath:#"me/feed" andParams:params andHttpMethod:#"POST" andDelegate:self];
}
else
[self loginToFacebook];
}
-(void)postMessageToFriendWall
{
currentApiCallType = FBApiCallPostMessageFriendWall;
if([self isLoggedIn])
{
NSString *strGraphPath = [NSString stringWithFormat:#"%#/feed", #"100002305497328"];
//NSString *strGraphPath = [NSString stringWithFormat:#"%#/feed", #"100002560928461"];
NSMutableDictionary *params = [[[NSMutableDictionary alloc] init] autorelease];
[params setObject:self.strMessage forKey:#"message"];
[objFacebook requestWithGraphPath:strGraphPath andParams:params andHttpMethod:#"POST" andDelegate:self];
}
else
[self loginToFacebook];
}
#pragma mark -
#pragma mark String Methods
- (BOOL)isEmptyString:(NSString *)strValue
{
NSString *copy;
if (strValue == nil)
return (YES);
if ([strValue isEqualToString:#""])
return (YES);
if ([strValue isEqualToString:#"(null)"])
return (YES);
copy = [[strValue copy] autorelease];
//if ([[copy trimWhiteSpace] isEqualToString: #""])
if ([[self trimWhiteSpace:copy] isEqualToString: #""])
return (YES);
return (NO);
} /*stringIsEmpty*/
- (NSString *) trimWhiteSpace:(NSString *)strValue
{
NSMutableString *s = [[strValue mutableCopy] autorelease];
CFStringTrimWhitespace ((CFMutableStringRef) s);
return (NSString *) [[s copy] autorelease];
} /*trimWhiteSpace*/
#pragma mark -
#pragma mark Default AlertView
-(void)showAlertView:(NSString *)pstrTitle withMessage:(NSString *)pstrMessage delegate:(id)pDelegate
{
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:pstrTitle message:pstrMessage delegate:pDelegate cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
[alertView release];
}
#end
That's it. Now our Facebook wrapper class is ready.
Create 3 below class for better organization.
FacebookGlobal.h
Add below data:
#define g_kFacebookAppId #"<Your AppID>"
#define g_kFacebookAppSecret #"<Your Secret>"
#define g_kPostMessage #"<Message>"
#define g_kPostUrlTitle #"<Title>"
#define g_kPostUrl #"<Url>"
#define g_kPostCaption #"<Caption>"
#define g_kPostPictureUrl #"<Image Url>"
FacebookKey.h
Add below data:
#define g_kFacebookAccessToken #"FBAccessTokenKey"
#define g_kFacebookExpirationDate #"FBExpirationDateKey"
FacebookMessage.h
Add below data:
//AppID Missing
#define msgFBAppIDMissing #"Missing AppID"
//Session Invalidated
#define msgFBSessionInvalidateTitle #"Auth Exception"
#define msgFBSessionInvalidateMessage #"Your session has expired."
Import below files in your .pch files:
#import "FacebookGlobal.h"
#import "FacebookKey.h"
#import "FacebookMessage.h"
#import "FacebookHelper.h"
Now, you are ready for use.
In your view controller, add below delegate:
<FBApiCallDelegate>
In your view controller .m file, add below methods to call as well delegate:
- (void)viewWillAppear:(BOOL)animated {
/*
FacebookHelper *fbHelper = [FacebookHelper sharedInstance];
[fbHelper logoutFromFacebook];
*/
//Get User Info
FacebookHelper *fbHelper = [FacebookHelper sharedInstance];
fbHelper.apiCallDelegate = self;
[fbHelper getUserInfo];
/*
//Get User's Friend List
FacebookHelper *fbHelper = [FacebookHelper sharedInstance];
fbHelper.apiCallDelegate = self;
[fbHelper getUserFriends];
*/
/*
//Post Message to FB Wall
FacebookHelper *fbHelper = [FacebookHelper sharedInstance];
fbHelper.apiCallDelegate = self;
fbHelper.strMessage = g_kPostMessage;
[fbHelper postMessageToWall];
*/
/*
//Post Picture to FB Wall
FacebookHelper *fbHelper = [FacebookHelper sharedInstance];
fbHelper.apiCallDelegate = self;
fbHelper.strMessage = g_kPostMessage;
fbHelper.image = [UIImage imageNamed:#"postPicture.jpg"];
[fbHelper postPictureToWall];
*/
/*
//Share Link on FB Wall
FacebookHelper *fbHelper = [FacebookHelper sharedInstance];
fbHelper.apiCallDelegate = self;
fbHelper.strUrl = g_kPostUrl;
fbHelper.strMessage = g_kPostMessage;
[fbHelper shareLinkOnWall];
*/
/*
//Post All to FB Wall
FacebookHelper *fbHelper = [FacebookHelper sharedInstance];
fbHelper.apiCallDelegate = self;
fbHelper.strMessage = g_kPostMessage;
fbHelper.strUrlTitle = g_kPostUrlTitle;
fbHelper.strUrl = g_kPostUrl;
fbHelper.strCaption = g_kPostCaption;
fbHelper.strPictureUrl = g_kPostPictureUrl;
[fbHelper postAllToWall];
*/
/*
//Post Message to Friend Wall
FacebookHelper *fbHelper = [FacebookHelper sharedInstance];
fbHelper.apiCallDelegate = self;
fbHelper.strMessage = g_kPostMessage;
[fbHelper postMessageToFriendWall];
*/
}
#pragma mark -
#pragma mark Get User Info Delegate
-(void)finishUserInfoResponse:(id)result{
NSLog(#"UserInfo response successed!");
NSLog(#"%#", result);
}
-(void)failedUserInfoResponse:(NSError *)error{
NSLog(#"UserInfo response failed!");
}
#pragma mark -
#pragma mark Get User's Friend List
-(void)finishUserFriendResponse:(id)result{
NSLog(#"User FriendList response successed!");
NSLog(#"%#", result);
}
-(void)failedUserFriendResponse:(NSError *)error{
NSLog(#"User FriendList response failed!");
}
#pragma mark -
#pragma mark Post Message to FB Wall Delegate
-(void)finishPostMessageResponse:(id)result{
NSLog(#"Post message successed!");
NSLog(#"%#", result);
}
-(void)failedPostMessageResponse:(NSError *)error{
NSLog(#"Post message failed!");
}
#pragma mark -
#pragma mark Post Picture to FB Wall
-(void)finishPostPictureResponse:(id)result{
NSLog(#"Post picture successed!");
NSLog(#"%#", result);
}
-(void)failedPostPictureResponse:(NSError *)error{
NSLog(#"Post picture failed!");
}
#pragma mark -
#pragma mark Share Link on FB Wall
-(void)finishShareLinkResponse:(id)result{
NSLog(#"Share link successed!");
NSLog(#"%#", result);
}
-(void)failedShareLinkResponse:(NSError *)error{
NSLog(#"Share link failed!");
}
#pragma mark -
#pragma mark Post All - Message, Link, Caption, PhotoUrl
-(void)finishPostAllResponse:(id)result{
NSLog(#"Post all successed!");
NSLog(#"%#", result);
}
-(void)failedPostAllResponse:(NSError *)error{
NSLog(#"Post all failed!");
}
#pragma mark -
#pragma mark Post Message to Friend Wall Delegate
-(void)finishPostMsgFriendWallResponse:(id)result{
NSLog(#"Post message to friend wall successed!");
NSLog(#"%#", result);
}
-(void)failedPostMsgFriendWallResponse:(NSError *)error{
NSLog(#"Post message to friend wall failed!");
}
Happy Coding :)
Enjoy.

Resources