React Native library that implements PayPal Checkout flow using purely native code (swift).

Overview

react-native-paypal-swift

React Native library that implements PayPal Checkout flow using purely native code (swift).

React Native library

Installation

npm install react-native-paypal-swift or `yarn add react-native-paypal-swift`
  1. [iOS] Add pod 'Braintree', '~> 4' and pod 'Braintree/DataCollector' to your Podfile.

  2. [iOS] Run pod install

  3. [iOS] Register a URL scheme in Xcode (must always start with your Bundle Identifier and end in .payments - e.g. your.app.id.payments). See details here.

  4. [iOS] Edit your AppDelegate as follows:

    Objective C ~> AppDelegate.m

    #import "BraintreeCore.h"
    #import "BraintreePayPal.h"
    #import "BTDataCollector.h"
    
    static NSString *URLScheme;
    
    @implementation AppDelegate
    
    - (BOOL)application:(UIApplication *)application
      didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
      NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
      NSString *urlscheme = [NSString stringWithFormat:@"%@.payments", bundleIdentifier];
      URLScheme = urlscheme;
      [BTAppSwitch setReturnURLScheme:urlscheme];
    }
    
    // if you support only iOS 9+, add the following method
    - (BOOL)application:(UIApplication *)application
        openURL:(NSURL *)url
        sourceApplication:(NSString *)sourceApplication
        annotation:(id)annotation
    {
        if ([url.scheme localizedCaseInsensitiveCompare:URLScheme] == NSOrderedSame) {
            return [BTAppSwitch handleOpenURL:url sourceApplication:sourceApplication];
        }
        return NO;
    }
    
    // otherwise, if you support iOS 8, add the following method
      - (BOOL)application:(UIApplication *)application
          openURL:(NSURL *)url
          options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
      {
          if ([url.scheme localizedCaseInsensitiveCompare:URLScheme] == NSOrderedSame) {
              return [BTAppSwitch handleOpenURL:url options:options];
          }
          return NO;
      }

    Swift ~> AppDelegate.swift

       func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
           BTAppSwitch.setReturnURLScheme("com.your-company.your-app.payments")
           return true
       }
    
      // if you're using UISceneDelegate (introduced in iOS 13), call BTAppSwitch's handleOpenURLContext method from within the scene:openURLContexts scene delegate method.
       func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
           URLContexts.forEach { context in
               if context.url.scheme?.localizedCaseInsensitiveCompare("com.your-company.your-app.payments") == .orderedSame {
                   BTAppSwitch.handleOpenURLContext(context)
               }
           }
       }
    
     // otherwise, if you aren't using UISceneDelegate, call BTAppSwitch's handleOpenURL method from within the application:openURL:options app delegate method.
      func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
          if url.scheme?.localizedCaseInsensitiveCompare("com.your-company.your-app.payments") == .orderedSame {
              return BTAppSwitch.handleOpen(url, options: options)
          }
          return false
      }

Usage

First you need to get a valid token from your server. Refer to this.

Then you can execute the following code, for example reacting to a button press.

    import {Paypal} from "react-native-paypal-swift";

    // ...
    const CLIENT_TOKEN = useMemo<string>(() => 'sandbox_v29bk2j6_xxxxxxxxx', []);
    // For one time payments
   const requestOneTimePayment = useCallback(() => {
       Paypal.requestOneTimePayment(CLIENT_TOKEN,
         {
           amount: '10',
         },
       ).then(resOneTimePayment => {
            //   nonce,
            //   payerId,
            //   email ,
            //   firstName,
            //   lastName ,
            //   phone,
            //   billingAddress,
            //   shippingAddress
         console.log({ resOneTimePayment });
       }).catch(err => {
         console.log(err);
       });
     }, []);

     const requestBillingAgreement = useCallback(() => {
       Paypal.requestBillingAgreement(CLIENT_TOKEN,
         {
           billingAgreementDescription: 'Your agreement description',
           currencyCode: 'GBP',
           localeCode: 'en_GB',
         },
       ).then(resBillingAgreement => {
            //   nonce,
            //   payerId,
            //   email ,
            //   firstName,
            //   lastName ,
            //   phone,
            //   billingAddress,
            //   shippingAddress
         console.log({ resBillingAgreement });
       }).catch(err => {
         console.log(err);
       });
     }, []);

    const requestDeviceData = useCallback(() => {
        Paypal.requestDeviceData(CLIENT_TOKEN).then(resDeviceData => {
          alert(`Your correlation id: ${resDeviceData?.deviceData?.correlation_id}`);
          console.log({ resDeviceData });
        }).catch(err => {
          console.log(err);
        });
      }, []);
// ...

Creating/Finding client token

Note that the client token should be served via a backend service but can be hardcoded:

  1. Go to https://www.braintreegateway.com or https://sandbox.braintreegateway.com/ and login or create an account
  2. Click the gear at the top and select to API
  3. You can find your token under Tokenization Keys. You will need to create one if none exists

Backend implementation

For an overview of the braintree payment flow see https://developers.braintreepayments.com/start/overview

This library covers the client setup here: https://developers.braintreepayments.com/start/hello-client

It does NOT however cover the server portion here: https://developers.braintreepayments.com/start/hello-server

You will need the server portion in order to complete your transactions. See a simple example of this server in /exampleServer. The example app is pointed to this on default

Contributing

See the contributing guide to learn how to contribute to the repository and the development workflow.

License

MIT

You might also like...
react native esptouch

react-native-esptouch One should know that This is a Unofficial project. The official demo is below: EsptouchForAndroid EsptouchForIOS Getting started

React Native Template for Taro

React Native Template for Taro requirement taro: @tarojs/[email protected]^3.2.0 framework: 'react' quick start install react native library install peerDependenci

A suite of IoT tools to use with React Native.

react-native-iot-tools WIP. A suite of IoT tools for React Native applications. Package iOS Android @react-native-iot-tools/bluetooth ✅ ❌ @react-nativ

Encryption/Decryption for React Native

@dhairyasharma/react-native-encryption Encryption/decryption for React Native. Benchmark File Details File Link http://bit.do/benchmarkfile File Size

Encryption/Decryption for React Native

@dhairyasharma/react-native-encryption Encryption/decryption for React Native. Benchmark File Details File Link http://bit.do/benchmarkfile File Size

iOS's Stocks App clone written in React Native for demo purpose (available both iOS and Android).
iOS's Stocks App clone written in React Native for demo purpose (available both iOS and Android).

FinanceReactNative iOS's Stocks App clone written in React Native for demo purpose (available both iOS and Android). Data is pulled from Yahoo Finance

React Native Photo Editor (RNPE)
React Native Photo Editor (RNPE)

React Native Photo Editor (RNPE) 🌄 Image editor using native modules for iOS an

Discover Movies and TV shows -  React Native
Discover Movies and TV shows - React Native

movieapp Discover Movies and TV shows Download APK file Download from Google Drive - v2.2.1 What's included Name Description React Native Build Native

All my React Native examples

ReactNativeExamples All my React Native examples and experiements can be found here. This repo is divided into two sub folders, Instructions git clone

Releases(1.0.3)
Owner
Tibb
Life is like a camera lens :camera:. Focus only on what’s important and you can capture it perfectly :clap::clap::clap:
Tibb
A sample app that implements MVVM architecture using Swift, ViewModel, Alamofire

MVVM Architecture Android: Template This repository contains a sample app that implements MVVM architecture using Swift, ViewModel, Alamofire, and etc

null 0 Oct 19, 2021
React Native utility library around image and video files for getting metadata like MIME type, timestamp, duration, and dimensions. Works on iOS and Android using Java and Obj-C, instead of Node 🚀.

Qeepsake React Native File Utils Extracts information from image and video files including MIME type, duration (video), dimensions, and timestamp. The

Qeepsake 10 Aug 20, 2022
The source code to How to build a news app with react native 📰

Royal News · The source code to How to build a news app with react native article on NimreyCode, medium, and dev.to. Requirements: Android Studio or X

Mohammed Salman 96 Aug 16, 2022
A testing MQTT react native library

react-native-awesome-testing abc Installation npm install react-native-awesome-testing Usage import { multiply } from "react-native-awesome-testing";

null 0 Nov 26, 2021
Blazing⚡️Fast BTC and ETH Wallet Generator library for React Native, Android and iOS

Blazing ⚡️ Fast BTC and ETH Wallet Generator library for React Native, Android and iOS.

Coingrig 3 Feb 21, 2022
A react native interface for integrating payments using Braintree

A react native interface for integrating payments using Braintree

eKreative 15 Sep 7, 2022
A property finder application written using React Native

React Native PropertyFinder App This repository accompanies the tutorial I published on Ray Wenderlich's website, which describes the process of build

Colin Eberhardt 276 Aug 14, 2022
React Native 实现无侵入自定义下拉刷新组件

react-native-ly-refresh-control 下拉刷新 iOS 基于MJRefresh 通过RCTCustomRefreshContolProtocol实现RefreshControl组件封装 JS端可以无侵入自定义下拉刷新只需要替换对应的refreshControl Androi

少言 12 Jul 2, 2022
iOS 15 share play API in react-native

react-native-shareplay iOS 15 share play API in react-native Installation yarn add react-native-shareplay And go to Xcode Capabilities and enable "Gro

Popshop Live 26 Aug 2, 2022
React Native package for interacting with HomeKit devices

React Native package for interacting with HomeKit devices

Ibrahim Berat Kaya 4 Dec 24, 2021