Coder Social home page Coder Social logo

pphkash / ios-here-sdk-dist Goto Github PK

View Code? Open in Web Editor NEW

This project forked from paypal/paypal-here-sdk-ios-distribution

0.0 1.0 0.0 900.6 MB

Add credit card (swipe & key-in) capabilities to your iOS app

Objective-C 15.47% CSS 0.74% C 0.11% HTML 83.08% JavaScript 0.61%

ios-here-sdk-dist's Introduction

ios-here-sdk-dist

The PayPal Here SDK enables iOS apps to interact with credit card swipers so that merchants can process in-person credit card transactions using a mobile app. The native libraries of the PayPal Here SDK enable you to:

  • Interact with PayPal Hardware — Detect, connect to, and listen for events coming from PayPal Here audio jack-based card swipers.
  • Process Card-Present payments — When you swipe a card through a PayPal Here swiper, card data is immediately encrypted. The encrypted package can be sent to PayPal alongside the transaction data for processing.

Developers should use the PayPal Here SDK to get world-class payment process with extremely simple integration. Some of the main benefits include

  • Low, transparent pricing: US Merchants pay just 2.7% per transaction (or 3.5% + $0.15 for keyed in transactions), including cards like American Express, with no additional hidden/monthly costs.
  • Safety & Security: PayPal's solution uses encrypted swipers, such that card data is never made available to merchants or anyone else.
  • Live customer support: Whenever you need support, we’re available to help with our customer support team. Visit our website for more information about PayPal Here.

Full class and method documentation can be found here.

As an alternative to the SDK, a developer can also use a URI framework that lets one app (or mobile webpage) link directly to the PayPal Here app to complete a payment. Using this method, the merchant will tap a button or link in one app, which will open the pre-installed PayPal Here app on their device, with the PayPal Here app pre-populating the original order information, collect a payment (card swipe) in the PayPal Here app, and return the merchant to the original app/webpage. This is available for US, UK, Austalia, and Japan for iOS & Android. See the Sideloader API on Github.

Prerequisites For Using The SDK

In order to start using the PayPal Here SDK, you need the following:

  1. A developer-enabled PayPal account (sign up here). This is the account you use to register your app. You will receive an App ID & Secret to use with the SDK.
  2. A PayPal Here business account ([sign up here] (https://www.paypal.com/us/webapps/mobilemerchant/page/mpa/ob/geturl?onbver=2.0&country.x=US&productIntentID=mobile_payment_acceptance&referringpage=ios_sdk_github&hs=login)). This is the account that the end merchant uses, and will be the destination account of funds received. A single app can be associated with/used by one or many merchant accounts – including the developer-enabled account. You will receive an Access Token and Refresh URL for each merchant that grants permission to your app. (See our Onboarding guide for suggestions on how to help your merchants sign up for PayPal business accounts)
  3. A PayPal Here swiper. You can get one shipped to you when you create a business account in step (2), or via retailers like Staples.
  4. Apple development tools: Xcode 5.1, and an Apple developer account.

The Sample App

To make it easier to see and understand how to best use the capabilities of the SDK, we’ve designed a sample/reference application. To make the app functional, there is some minimal UI code that can be ignored – the point is to show how to use the SDK API’s.

With the Sample App, you can view code that:

  • Initializes the SDK
  • Authenticates the merchant
  • Updates the merchant location
  • Creates & adds items to an invoice
  • Takes a payment with the card reader
  • Takes a keyed-in card transaction
  • Add a signature to finalize a payment
  • Send an email/SMS receipt

Get Started

The first thing you need to do is set up your app to start using the SDK.

  • Initialize the SDK (each time the app starts)
  • Authenticate the merchant and pass the merchant’s credentials (Access Token) to the SDK (more on PayPal oAuth)
  • Set the merchant’s location (any time the merchant’s location changes)
  • Start monitoring the card reader for events (for card present transactions)

If you want to start with test transactions (generally a good idea), you can optionally send a selectEnvironmentWithType message to PayPalHereSDK:

	[PayPalHereSDK selectEnvironmentWithType:environment_type];
  • environment_type is ePPHSDKServiceType_Sandbox for the Sandbox environment, or ePPHSDKServiceType_Live for the live environment (default).

With an authenticated merchant, it calls PayPalHereSDK.setActiveMerchant to set the merchant for which transactions will be executed.

	[PayPalHereSDK setActiveMerchant:merchant withMerchantId:merchantId completionHander:handler];
  • merchant is an instance of the PPHMerchantInfo represeting a merchant object
  • merchantId is an id for the merchant. It is defined by agreement between the back-end server and the app (not by the SDK), and must be unique among the merchants that use the back-end server and the app.
  • handler is an id for a completion handler to be called when merchant setup is completed.

Now, monitor the card reader for events like reader connections, removals, and swipes. Invoke the API (SettingsViewController.m).

	[[PayPalHereSDK sharedCardReaderManager] beginMonitoring];

Interacting With The Card Reader

Card reader interaction is established by calling:

    [[PayPalHereSDK sharedCardReaderManager] beginMonitoring];

which will monitor for all card reader types.

Once you've begun monitoring, the SDK will start firing notification center events for relevant card events. However, we recommend you do not monitor the notification center directly, but instead use our class that will translate untyped notification center calls to typed delegate calls. You do this by simply storing an instance of PPHCardReaderWatcher in your class and implementing the PPHCardReaderDelegate protocol:

    self.readerWatcher = [[PPHCardReaderWatcher alloc] initWithDelegate: self];

The events are very simple:

-(void)didStartReaderDetection: (PPHReaderType) readerType; //Indicates a reader (or something else) was inserted into the headphone jack
-(void)didDetectReaderDevice: (PPHCardReaderBasicInformation*) reader; //Indicates that a PayPal reader was detected
-(void)didReceiveCardReaderMetadata: (PPHCardReaderMetadata*) metadata; //Includes additional data about the PayPal reader, like reader type and serial number
-(void)didRemoveReader: (PPHReaderType) readerType; //Indicates the reader was removed

-(void)didDetectCardSwipeAttempt; //Indicates that something (e.g. a card, a piece of paper) was swiped through the reader
-(void)didCompleteCardSwipe:(PPHCardSwipeData*)card; //Indicates a successful read of the card, with data
-(void)didFailToReadCard; //Indicates a failed read (e.g. this wasn't a credit card)

The first four relate to the insertion, removal and detection of the card reader, the other three are in the context of a transaction, which you must "begin" by telling the card reader manager you're ready to receive a swipe. Because some readers (namely audio jack readers) have batteries in them, you MUST be careful about when you activate the reader. In the PayPal Here app, for example, we activate the reader when there is a non-zero value in the "cart" or active order. If you have a view or step which expresses clear intent to take a charge, that's a good time to activate the reader.

Build & Complete a Transaction

In order to process a payment, there needs to be an amount to charge. PayPal creates Invoices to represent each transaction to be paid. Invoices can be extremely simple (a simple amount), or complex with details on item names, taxes, tips, and/or discounts. The basic order of operations:

  • Start a new invoice
  • Add item data to the invoice (optional)
  • Begin a purchase event and collect card data
  • Collect a signature for the transaction

Start a new invoice

The invoice is a PPHInvoice, and doesn't need to have been saved to the PayPal backend to begin watching for card swipes. It will need to be saved before attempting a charge, but you can do this in parallel with receiving swipe data. To create an invoice, just set up a currency, add one or more items, and set tax or other information:

PPHInvoice *invoice = [[PPHInvoice alloc] initWithCurrency:self.currencyField.text];

[invoice addItemWithId: @"Item"
                   name: @"Purchase"
               quantity: [NSDecimalNumber one]
              unitPrice: [PPHAmount amountWithString:self.amountField.text inCurrency:self.currencyField.text].amount
                taxRate: nil
            taxRateName: nil];

Add item data

You should add details about each item on the receipt if possible. To save an invoice, just call save and provide a completion handler. Typically you would show some progress UI while doing this, unless it's being done in the background:

        [invoice save:^(PPHError *error) {
          // If error is non-nil, something bad happened. Else, invoice has been updated with server info
          // such as PayPal invoice id, auto-generated merchant reference number, etc.
        }];

And then, get the invoice ready for payment:

// Begin the purchase and forward to payment method
 PPHTransactionManager *tm = [PayPalHereSDK sharedTransactionManager];
 tm.ignoreHardwareReaders = NO;
 [tm beginPayment];
 tm.currentInvoice = invoice;

(SimpleFSPaymentDelegate.m)

Begin a purchase event

The PPHTransactionManager takes care of most details for you - it's even possible to take a card swipe payment without having to explicitly save the invoice or to use the card reader API to capture card events. Of course, this comes at the cost of less control over the step by step process. If you do want to see all the card swiper events you still can create a card watcher and get all the card events while using the PPHTransactionManager at the same time.

In order to start processing card payments, use the “PPHTransactionManagerDelegate”. This protocol receives events (via the “onPaymentEvent” method) from the SDK. In order to implement the above “onPaymentEvent” method and receive events off it, init an instance of the “PPHTransactionWatcher” class:

[[PPHTransactionWatcher alloc] initWithDelegate:self];

Second, start your payment. Here's an example of taking a payment for a fixed amount ($5):

[[PayPalHereSDK sharedTransactionManager] beginPaymentWithAmount:[PPHAmount amountWithString:amountString inCurrency:@"USD"] andName:@"FixedAmountPayment"];

Then, wait for the user to swipe a card. You do that by capturing the ePPHTransactionType_CardDataReceived event from the PPHTransacitonWatcher:

#pragma mark my PPHTransactionManagerDelegate overrides
- (void)onPaymentEvent:(PPHTransactionManagerEvent *) event {
  if(event.eventType == ePPHTransactionType_CardDataReceived) {
      NSLog(@"The transaction manager has card data!");
      // We're now clear to process the payment
  }
}

Now that you know the card has been captured you can ask the PPHTransactionWatcher to process the payment:

[[PayPalHereSDK sharedTransactionManager] processPaymentWithPaymentType:ePPHPaymentMethodSwipe
                  withTransactionController:nil
                          completionHandler:^(PPHTransactionResponse *response) {
                              if(!record.error) {
                                  self.successfulResponse = response;
                                  NSLog(@"Payment captured successfully!  We now have the money in our account!");

if(response.isSignatureRequiredToFinalize) {
   NSLog(@"This payment requires a signature.  Let's provide one via the finalizePayment method");

}                              
                              }
                          }];

Add a signature

The PPHTransactionManager can inform you if a signature is required for the payment that is being processed (common, as signatures are usually required for transactions). When the processPayment method's completion handler is called you can check the isSignatureRequiredToFinalize member of the PPHTransactionResponse object that is provided to the completion handler.

[[PayPalHereSDK sharedTransactionManager] provideSignature:self.signature.printableImage
 forTransaction:_capturedPaymentResponse.record
 completionHandler:^(PPHError *error) {
 [self showPaymentCompeleteView:_capturedPaymentResponse];
 }];

(SignatureViewController.m)

More Stuff to Look At

There is a lot more available in the PayPal Here SDK. More detail is available in our developer documentation to show other capabilities. These include:

  • Auth/Capture: Rather than a one-time sale, authorize a payment with a card swipe, and complete the transaction at a later time. This is common when adding tips after the transaction is complete (e.g. at a restaurant).
  • Refunds: Use the SDK to refund a transaction
  • Send Receipts: You can use services through the SDK to send email or SMS receipts to customers
  • Key-in: Most applications need to let users key in card numbers directly, in case the card's magstripe data can no longer be read.
  • CashierID: Include your own unique user identifier to track a merchant's employee usage
  • Error Handling: See more detail about the different types of errors that can be returned

App Review Information

When you submit your app, you will need to refer to MFI ID's for the hardware that you can interact with through our app. Be sure to include the following into your app store review notes:

  • This iOS application uses the Bluetooth protocol "com.paypal.here.reader": PPID# 126754-0002
  • This iOS application uses the com.magtek.idynamo protocol for the Magtek iDynamo reader: PPID 103164-0003

ios-here-sdk-dist's People

Contributors

paypaldoma avatar vinodhsundararajan avatar pphkash avatar tonyleachsf avatar paypalsathya avatar djmax avatar burnto avatar ppmtscory avatar pguelpa avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.