Giter Site home page Giter Site logo

stripe / stripe-react-native Goto Github PK

View Code? Open in Web Editor NEW
1.2K 49.0 255.0 5.16 MB

React Native library for Stripe.

Home Page: https://stripe.dev/stripe-react-native

License: MIT License

C 0.01% Kotlin 26.52% JavaScript 0.68% Shell 0.59% Java 1.49% Swift 27.11% Ruby 0.22% Objective-C 1.39% TypeScript 40.68% Makefile 0.14% C++ 0.66% Objective-C++ 0.48%
react-native stripe payments

stripe-react-native's Introduction

Stripe React Native SDK

npm version License

The Stripe React Native SDK allows you to build delightful payment experiences in your native Android and iOS apps using React Native. We provide powerful and customizable UI screens and elements that can be used out-of-the-box to collect your users' payment details.

Getting started

Get started with our πŸ“š integration guides and example project, or πŸ“˜ browse the SDK reference.

Updating to a newer version of the SDK? See our changelog.

Features

Simplified Security: We make it simple for you to collect sensitive data such as credit card numbers and remain PCI compliant. This means the sensitive data is sent directly to Stripe instead of passing through your server. For more information, see our Integration Security Guide.

Apple Pay: We provide a seamless integration with Apple Pay.

Payment methods: Accepting more payment methods helps your business expand its global reach and improve checkout conversion.

SCA-Ready: The SDK automatically performs native 3D Secure authentication if needed to comply with Strong Customer Authentication regulation in Europe.

Native UI: We provide native screens and elements to securely collect payment details on Android and iOS.

PaymentSheet: Learn how to integrate PaymentSheet, our new pre-built payments UI for mobile apps. PaymentSheet lets you accept cards, Apple Pay, Google Pay, and much more out of the box and also supports saving & reusing payment methods. PaymentSheet currently accepts the following payment methods: Card, Apple Pay, Google Pay, SEPA Debit, Bancontact, iDEAL, EPS, P24, Afterpay/Clearpay, Klarna, Giropay, Sofort, and ACH.

Recommended usage

If you're selling digital products or services within your app, (e.g. subscriptions, in-game currencies, game levels, access to premium content, or unlocking a full version), you must use the app store's in-app purchase APIs. See Apple's and Google's guidelines for more information. For all other scenarios you can use this SDK to process payments via Stripe.

Installation

yarn add @stripe/stripe-react-native
or
npm install @stripe/stripe-react-native

Expo

Find Expo's full documentation here.

Each Expo SDK version requires a specific stripe-react-native version. See the CHANGELOG for a mapping of versions. To install the correct version for your Expo SDK version run:

expo install @stripe/stripe-react-native

Next, add:

{
  "expo": {
    ...
    "plugins": [
      [
        "@stripe/stripe-react-native",
        {
          "merchantIdentifier": string | string [],
          "enableGooglePay": boolean
        }
      ]
    ],
  }
}

to your app.json file, where merchantIdentifier is the Apple merchant ID obtained here. Otherwise, Apple Pay will not work as expected. If you have multiple merchantIdentifiers, you can set them in an array.

Requirements

Android

  • Android 5.0 (API level 21) and above
    • Your compileSdkVersion must be 34. See this issue for potential workarounds.
  • Android gradle plugin 4.x and above

Components

In order to use CardForm component, you need to install and configure Material Components theme in your app.

  1. Add below dependency to your app/build.gradle file with specified version
implementation 'com.google.android.material:material:<version>'
  1. Set appropriate style in your styles.xml file
<style name="Theme.MyApp" parent="Theme.MaterialComponents.DayNight">
    <!-- ... -->
</style>

iOS

The Stripe React Native SDK requires Xcode 14.1 or later and is compatible with apps targeting iOS 13 or above. For iOS 12 support, please use @stripe/[email protected].

The SDK uses TypeScript features available in Babel version 7.9.0 and above. Alternatively use the plugin-transform-typescript plugin in your project.

You'll need to run pod install in your ios directory to install the native dependencies.

Usage example

For a complete example, visit our docs.

// App.ts
import { StripeProvider } from '@stripe/stripe-react-native';

function App() {
  return (
    <StripeProvider
      publishableKey={publishableKey}
      merchantIdentifier="merchant.identifier" // required for Apple Pay
      urlScheme="your-url-scheme" // required for 3D Secure and bank redirects
    >
      <PaymentScreen />
    </StripeProvider>
  );
}

// PaymentScreen.ts
import { useStripe } from '@stripe/stripe-react-native';

export default function PaymentScreen() {
  const { initPaymentSheet, presentPaymentSheet } = useStripe();

  const setup = async () => {
    const { error } = await initPaymentSheet({
      merchantDisplayName: 'Example, Inc.',
      paymentIntentClientSecret: paymentIntent, // retrieve this from your server
    });
    if (error) {
      // handle error
    }
  };

  useEffect(() => {
    setup();
  }, []);

  const checkout = async () => {
    const { error } = await presentPaymentSheet();

    if (error) {
      // handle error
    } else {
      // success
    }
  };

  return (
    <View>
      <Button title="Checkout" onPress={checkout} />
    </View>
  );
}

Stripe initialization

To initialize Stripe in your React Native app, use the StripeProvider component in the root component of your application, or use the initStripe method.

StripeProvider can accept urlScheme, publishableKey, stripeAccountId, threeDSecureParams and merchantIdentifier as props. Only publishableKey is required.

import { StripeProvider } from '@stripe/stripe-react-native';

function App() {
  const [publishableKey, setPublishableKey] = useState('');

  const fetchPublishableKey = async () => {
    const key = await fetchKey(); // fetch key from your server here
    setPublishableKey(key);
  };

  useEffect(() => {
    fetchPublishableKey();
  }, []);

  return (
    <StripeProvider
      publishableKey={publishableKey}
      merchantIdentifier="merchant.identifier" // required for Apple Pay
      urlScheme="your-url-scheme" // required for 3D Secure and bank redirects
    >
      // Your app code here
    </StripeProvider>
  );
}

or

import { initStripe } from '@stripe/stripe-react-native';

function App() {
  // ...

  useEffect(() => {
    initStripe({
      publishableKey: publishableKey,
      merchantIdentifier: 'merchant.identifier',
      urlScheme: 'your-url-scheme',
    });
  }, []);
}

You can find more details about the StripeProvider component in the API reference.

Additional steps for webhook forwarding

Certain payment methods require a webhook listener to notify you of changes in the status. When developing locally, you can use the Stripe CLI to forward webhook events to your local dev server.

  • Install the stripe-cli
  • Run stripe listen --forward-to localhost:4242/webhook
  • The CLI will print a webhook secret (such as, whsec_***) to the console. Set STRIPE_WEBHOOK_SECRET to this value in your example/.env file.

Testing

This library includes a built in mock file for Jest. In order to use it, add the following code to the Jest setup file:

import mock from '@stripe/stripe-react-native/jest/mock.js';

jest.mock('@stripe/stripe-react-native', () => mock);

To have a more control over the mocks, you can extend and override particular methods e.g.:

const presentNativePayMock = jest.fn();

jest.mock('@stripe/stripe-react-native', () => ({
  ...mock,
  presentNativePay: presentNativePayMock,
}));

Contributing

See the contributor guidelines to learn how to contribute to the repository or to learn how to run the example app.

Troubleshooting

Android web browser windows close on backgrounding the app

This is known limitation of using singleTask as your launchMode on Android. See here for a workaround.

Undefined symbols for architecture x86_64 on iOS

While building your iOS project, you may see a Undefined symbols for architecture x86_64 error. This is caused by react-native init template configuration that is not fully compatible with Swift 5.1.

Undefined symbols for architecture x86_64:
  "(extension in Foundation):__C.NSScanner.scanUpToString(Swift.String) -> Swift.String?", referenced from:
      static Stripe.STPPhoneNumberValidator.formattedRedactedPhoneNumber(for: Swift.String, forCountryCode: Swift.String?) -> Swift.String in libStripe.a(STPPhoneNumberValidator.o)
  "__swift_FORCE_LOAD_$_swiftUniformTypeIdentifiers", referenced from:
      __swift_FORCE_LOAD_$_swiftUniformTypeIdentifiers_$_Stripe in libStripe.a(PKPaymentAuthorizationViewController+Stripe_Blocks.o)

Follow these steps to resolve this:

  • Open your project via Xcode, go to project -> build settings, find library search paths and remove all swift related entries such as: $(TOOLCHAIN_DIR)/usr/lib/swift/$(PLATFORM_NAME) and $(TOOLCHAIN_DIR)/usr/lib/swift-5.0/$(PLATFORM_NAME).
  • Create a new Swift file to the project (File > New > File > Swift), give it any name (e.g. Fix.swift), check the appropriate Targets and create a bridging header when prompted by Xcode.

TypeError: null is not an object (evaluating '_NativeStripeSdk.default.initialise') on Android

You might see error this whilst initializing the StripeProvider component with Expo. This is caused by using an older version of Expo before stripe-react-native was officially supported. Updating Expo Go from the stores (or locally on simulators installed with expo install:client:[ios|android]) should fix the problem.

If you're still having troubles, please open an issue or jump in our developer chat.

Apple Pay Is Not Available in "My App Name"

This can occur if you attempt to process an Apple Pay payment on a physical device (even in test mode) without having created and uploaded your Apple Pay Certificate to the Stripe Dashboard. Learn how to do that here.

stripe-react-native's People

Contributors

acomley-stripe avatar ajaykumar97 avatar arekkubaczkowski avatar brendanm-stripe avatar charliecruzan-stripe avatar cruzach avatar davidme-stripe avatar dependabot[bot] avatar huextrat avatar ianjabour-stripe avatar jaimepark-stripe avatar jamesblasco avatar jlh-stripe avatar joyluu-stripe avatar lbinscheck avatar michelleb-stripe avatar miduncan avatar migue1s avatar myckhel avatar nilpuig avatar p-sebastian avatar pavelglebov avatar perqin avatar porter-stripe avatar ranjandsingh avatar seanzhang-stripe avatar souhe avatar thorsten-stripe avatar vivekvardhanadepu avatar walkerdb avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

stripe-react-native's Issues

[Breaking change] Consistent error/exception handling pattern

We'd like to align the exception/error handling pattern of this SDK to the pattern followed by the fetch API and https://github.com/stripe/stripe-js.

The pattern is as following:

  • Methods never throws exceptions unless they are fatal.
  • sync methods returns either {objectName?: objectType; error?: StripeError};
  • async method returns Promise<{objectName?: objectType; error?: StripeError}>;

Pseudo code example:

try {
  let result = await stripe.confirmPayment('{argument}')
  if(result.error) {
    // Handle error
  } else {
    // Handle logic
  }
} catch(err) {
  // Something fatal happened
}

Prior art:

Missing step in example app instructions

Describe the bug
Example app will fail to run due to missing dependencies.

To Reproduce
Following the instructions on a fresh clone of the repo, when you get to the final yarn ios/yarn android step you are given the following error:

error: Error: Unable to resolve module `@babel/runtime/helpers/interopRequireDefault` from `../src/hooks/useStripe.tsx`: @babel/runtime/helpers/interopRequireDefault could not be found within the project.

The problem is that the example app gets its copy of stripe-react-native from the parent directory rather than NPM, presumably because the package isn't on NPM yet. You need to run yarn or npm install in the root directory to ensure that stripe-react-native has the required dependencies.

Proposed solution
Either add "Run yarn or npm install in the root directory" as a step in the instructions or add a check in the yarn ios/yarn android build commands that checks to see if node_modules exists in the parent directory and automatically installs dependencies if needed.

`pod install` issues

Describe the bug
When running yarn bootstrap, pod install errors.

To Reproduce
Steps to reproduce the behavior:

  1. Run yarn bootstrap

Desktop (please complete the following information):

  • OS: MacOS Catalina 10.15.7

Additional context

stripe-react-native-master yarn bootstrap
yarn run v1.22.10
$ yarn example && yarn && yarn pods
$ yarn --cwd example
[1/4] πŸ”  Resolving packages...
[2/4] 🚚  Fetching packages...
[3/4] πŸ”—  Linking dependencies...
[4/4] πŸ”¨  Building fresh packages...
[1/4] πŸ”  Resolving packages...
success Already up-to-date.
$ bob build
β„Ή Building target commonjs
β„Ή Cleaning up previous build at lib/commonjs
β„Ή Compiling 11 files in src with babel
βœ“ Wrote files to lib/commonjs
β„Ή Building target module
β„Ή Cleaning up previous build at lib/module
β„Ή Compiling 11 files in src with babel
βœ“ Wrote files to lib/module
β„Ή Building target typescript
β„Ή Cleaning up previous build at lib/typescript
β„Ή Generating type definitions with tsc
βœ“ Wrote definition files to lib/typescript
$ cd example && pod-install --quiet
1.10.0
> pod install
Auto-linking React Native modules for target `StripeSdkExample`: RNCMaskedView, RNGestureHandler, RNReanimated, RNScreens, and react-native-safe-area-context
Analyzing dependencies
Fetching podspec for `DoubleConversion` from `../node_modules/react-native/third-party-podspecs/DoubleConversion.podspec`
Fetching podspec for `Folly` from `../node_modules/react-native/third-party-podspecs/Folly.podspec`
Fetching podspec for `glog` from `../node_modules/react-native/third-party-podspecs/glog.podspec`
Downloading dependencies
Installing CocoaAsyncSocket (7.6.4)
Installing CocoaLibEvent (1.0.0)
Installing DoubleConversion (1.1.6)
Installing FBLazyVector (0.62.2)
Installing FBReactNativeSpec (0.62.2)
Installing Flipper (0.33.1)
Installing Flipper-DoubleConversion (1.1.7)
Installing Flipper-Folly (2.3.0)
Installing Flipper-Glog (0.3.6)
[!] /bin/bash -c
set -e
#!/bin/bash
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.

set -e

PLATFORM_NAME="${PLATFORM_NAME:-iphoneos}"
CURRENT_ARCH="${CURRENT_ARCH}"

if [ -z "$CURRENT_ARCH" ] || [ "$CURRENT_ARCH" == "undefined_arch" ]; then
    # Xcode 10 beta sets CURRENT_ARCH to "undefined_arch", this leads to incorrect linker arg.
    # it's better to rely on platform name as fallback because architecture differs between simulator and device

    if [[ "$PLATFORM_NAME" == *"simulator"* ]]; then
        CURRENT_ARCH="x86_64"
    else
        CURRENT_ARCH="armv7"
    fi
fi

export CC="$(xcrun -find -sdk $PLATFORM_NAME cc) -arch $CURRENT_ARCH -isysroot $(xcrun -sdk $PLATFORM_NAME --show-sdk-path)"
export CXX="$CC"

# Remove automake symlink if it exists
if [ -h "test-driver" ]; then
    rm test-driver
fi

./configure --host arm-apple-darwin

# Fix build for tvOS
cat << EOF >> src/config.h
/* Add in so we have Apple Target Conditionals */
#ifdef __APPLE__
#include <TargetConditionals.h>
#include <Availability.h>
#endif
/* Special configuration for AppleTVOS */
#if TARGET_OS_TV
#undef HAVE_SYSCALL_H
#undef HAVE_SYS_SYSCALL_H
#undef OS_MACOSX
#endif
/* Special configuration for ucontext */
#undef HAVE_UCONTEXT_H
#undef PC_FROM_UCONTEXT
#if defined(__x86_64__)
#define PC_FROM_UCONTEXT uc_mcontext->__ss.__rip
#elif defined(__i386__)
#define PC_FROM_UCONTEXT uc_mcontext->__ss.__eip
#endif
EOF

# Prepare exported header include
EXPORTED_INCLUDE_DIR="exported/glog"
mkdir -p exported/glog
cp -f src/glog/log_severity.h "$EXPORTED_INCLUDE_DIR/"
cp -f src/glog/logging.h "$EXPORTED_INCLUDE_DIR/"
cp -f src/glog/raw_logging.h "$EXPORTED_INCLUDE_DIR/"
cp -f src/glog/stl_logging.h "$EXPORTED_INCLUDE_DIR/"
cp -f src/glog/vlog_is_on.h "$EXPORTED_INCLUDE_DIR/"

checking for a BSD-compatible install... /usr/local/bin/ginstall -c
checking whether build environment is sane... yes
checking for arm-apple-darwin-strip... no
checking for strip... strip
checking for a thread-safe mkdir -p... /usr/local/bin/gmkdir -p
checking for gawk... no
checking for mawk... no
checking for nawk... no
checking for awk... awk
checking whether make sets $(MAKE)... yes
checking whether make supports nested variables... yes
checking for arm-apple-darwin-gcc... /Library/Developer/CommandLineTools/usr/bin/cc -arch armv7 -isysroot
checking whether the C compiler works... no
xcrun: error: SDK "iphoneos" cannot be located
xcrun: error: SDK "iphoneos" cannot be located
xcrun: error: SDK "iphoneos" cannot be located
xcrun: error: unable to lookup item 'Path' in SDK 'iphoneos'
/Users/thorsten/Library/Caches/CocoaPods/Pods/Release/Flipper-Glog/0.3.6-1dfd6/missing: Unknown `--is-lightweight' option
Try `/Users/thorsten/Library/Caches/CocoaPods/Pods/Release/Flipper-Glog/0.3.6-1dfd6/missing --help' for more information
configure: WARNING: 'missing' script is too old or missing
configure: error: in `/Users/thorsten/Library/Caches/CocoaPods/Pods/Release/Flipper-Glog/0.3.6-1dfd6':
configure: error: C compiler cannot create executables
See `config.log' for more details


Aborting run
An unexpected error was encountered. Please report it as a bug:
Error
    at CocoaPodsPackageManager._installAsync (/Users/thorsten/Documents/Projects/stripe-react-native-master/node_modules/pod-install/build/index.js:2:85721)
    at processTicksAndRejections (node:internal/process/task_queues:93:5)
    at async CocoaPodsPackageManager.installAsync (/Users/thorsten/Documents/Projects/stripe-react-native-master/node_modules/pod-install/build/index.js:2:85121)
    at async runAsync (/Users/thorsten/Documents/Projects/stripe-react-native-master/node_modules/pod-install/build/index.js:2:12925)
    at async /Users/thorsten/Documents/Projects/stripe-react-native-master/node_modules/pod-install/build/index.js:2:13011

error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Create an API reference page

We'll need a standalone API reference page for the React Native library. We'd like the API reference to be autogenerated using a tool like https://typedoc.org/. Delivery should include a script that generates html (so that we can host it on stripe.dev, similar to http://stripe.dev/stripe-ios )

We'll link to this content from our integration guides. As an example, let's look at the 3DS integration guide you put together. This content should be split between the integration guide and the API reference.

This content should go in the integration guide:

image

image

This content should go in the API reference (and should be autogenerated)

image

createPaymentMethod should require a type

Describe the bug
createPaymentMethod should require a type in its arguments to stay in sync with Stripe.js.

The disconnect is likely due to the fact that Android and iOS don't require a type, probably because they automatically infer it.

However react-stripe-js does via Stripe.js

Expected behavior
Require a type on PaymentMethod creation:

const paymentMethod = await createPaymentMethod({
  type: 'card',
  card,
});

createPaymentMethod's argument type should mimic what we do in Stripe.js.

Install library as local repository issues

Describe the bug
I've followed the instructions here: https://github.com/stripe/stripe-react-native/blob/master/CONTRIBUTING.md#install-library-as-local-repository but am running into some issues, would appreciate any pointers you have @arekkubaczkowski

To Reproduce
Steps to reproduce the behavior:

  1. Spin up new project npx react-native init MyTestApp
  2. Follow instructions at https://github.com/stripe/stripe-react-native/blob/master/CONTRIBUTING.md#install-library-as-local-repository
  3. Get error when running yarn install:
MyTestApp git:(master) yalc add react-native-stripe-sdk
Package [email protected]+b5ef738e added ==> /Users/thorsten/Documents/Projects/oss/react-native/MyTestApp/node_modules/react-native-stripe-sdk.
➜  MyTestApp git:(master) βœ— yarn
yarn install v1.22.10
[1/4] πŸ”  Resolving packages...
[2/4] 🚚  Fetching packages...
[3/4] πŸ”—  Linking dependencies...
warning "@react-native-community/eslint-config > @typescript-eslint/eslint-plugin > [email protected]" has unmet peer dependency "typescript@>=2.8.0 || >= 3.2.0-dev || >= 3.3.0-dev || >= 3.4.0-dev || >= 3.5.0-dev || >= 3.6.0-dev || >= 3.6.0-beta || >= 3.7.0-dev || >= 3.7.0-beta".
[4/4] πŸ”¨  Building fresh packages...
error /Users/thorsten/Documents/Projects/oss/react-native/MyTestApp/node_modules/react-native-stripe-sdk: Command failed.
Exit code: 1
Command: yarn example
Arguments:
Directory: /Users/thorsten/Documents/Projects/oss/react-native/MyTestApp/node_modules/react-native-stripe-sdk
Output:
yarn run v1.22.10
$ yarn --cwd example
info No lockfile found.
[1/4] Resolving packages...
[2/4] Fetching packages...
[3/4] Linking dependencies...
[4/4] Building fresh packages...
success Saved lockfile.
$ yarn example
$ yarn --cwd example
[1/4] Resolving packages...
success Already up-to-date.
$ yarn example
$ yarn --cwd example
[1/4] Resolving packages...
success Already up-to-date.
....
➜  MyTestApp git:(master) βœ—

Consistent parameter names

I noticed that we're not consistent with parameter names,

e.g. livemode vs isLiveMode

And things like customerId or paymentMethodId is something we don't do outside of the mobile world, e.g. normally it would just be customer and paymentMethod.

I would prefer if we were consistent with parameter names by not adding the Id suffix and using livemode instead of isLiveMode across the board, but I'm not sure if that complicates things in terms of mapping from mobile.

Would appreciate you thoughts on this @auchenberg-stripe @bg-stripe @arekkubaczkowski

Expo support

Is your feature request related to a problem? Please describe.
Expo is one of the most popular frameworks for developing React native applications. I'd expect we'll get a lot of requests about this.

Describe the solution you'd like
Is it possible to suppor expo without needing to eject? If so, how much work would that be?

Describe alternatives you've considered
If this isn't easily possible, can we add a "usage with Expo" guide?

Additional context
Currently, when I try to use CardField within an expo project I get β€œInvariant Violation: requireNativeComponent: "CardField" was not found in the UIManager.” which is related to the webview usage I beleive.

Hide fields from `CardDetails`

Developers should not be able to easily inspect properties on the CardDetails object returned from CardField. We should hide all the properties:

export type CardDetails = {
};

Currently, developers can look at cardDetails.number easily. Instead they should just be using the CardDetails object directly.

Ideally, developers should not be able to inspect these properties from CardDetails at all. If that is too difficult, we should do our best to hide them. (cc @thorsten-stripe )

Response of `handleNextPaymentAction` differs between iOS and Android

Describe the bug
The NoWebhookPayment example is working fine on iOS but on Android after the 3D Secure keeps spinning endlessly.

This is due to handleNextPaymentAction having different return values on iOS vs Android.

const response = await handleNextPaymentAction(clientSecret);
// Response on Android
{
   "amount":1400,
   "created":1610534695,
   "currency":"usd",
   "description":null,
   "id":"pi_1I96qRG7gfqYEkPOElpsrC0F",
   "receiptEmail":null,
   "status":"RequiresConfirmation"
}
// Response on iOS
{
   "currency":"usd",
   "description":"...",
   "id":"pm_1I96wnG7gfqYEkPOFrjhO6SK",
   "receiptEmail":"",
   "status":"RequiresConfirmation",
   "stripeId":"pi_1I96woG7gfqYEkPO3r9MhHII"
}

Also, stripeId is not a good name for the PaymentIntent ID. As per https://stripe.com/docs/js/payment_intents/handle_card_action it would be better to return

{ error: Error; paymentIntent: Stripe.PaymentIntent }

To Reproduce
Steps to reproduce the behavior:

  1. Run yarn example start
  2. Run yarn example android
  3. Click "Card payment without webhook"
  4. Click "Pay"
  5. Click "Complete Authentication"
  6. See endless spinning of button

Expected behavior
Same response shape across platforms.

Add card provisioning bindings

Stripe Issuing lets users provision cards from apps to their Apple Pay / Google Pay wallets.

We'd like to add React Native bindings for the functionality in this integration guide:
https://stripe.com/docs/issuing/cards/digital-wallets

The iOS & Android integrations are slightly different, so it's possible the end result will need to start with shared content on setting up your EphemeralKeyProvider, and then split into two sections documenting how to set this up for Apple Pay vs. Google Pay.

We'll want to verify that this works end-to-end in a sample app before we release it. We can give your Stripe account access to push provisioning (email bg [at] stripe.com and we can coordinate).

TypeScript build error

@arekkubaczkowski I'm getting this error on master when running yarn bootstrap. I think there might have gone something wrong in #50 that I didn't catch in the review, sorry! Can you have a look?

stripe-react-native-master git:(master) βœ— yarn bootstrap
yarn run v1.22.10
$ yarn example && yarn && yarn pods
$ yarn --cwd example
[1/4] πŸ”  Resolving packages...
success Already up-to-date.
[1/4] πŸ”  Resolving packages...
success Already up-to-date.
$ bob build
β„Ή Building target commonjs
β„Ή Cleaning up previous build at lib/commonjs
β„Ή Compiling 11 files in src with babel
βœ“ Wrote files to lib/commonjs
β„Ή Building target module
β„Ή Cleaning up previous build at lib/module
β„Ή Compiling 11 files in src with babel
βœ“ Wrote files to lib/module
β„Ή Building target typescript
β„Ή Cleaning up previous build at lib/typescript
β„Ή Generating type definitions with tsc
src/hooks/useStripe.tsx:5:17 - error TS4058: Return type of exported function has or is using name 'CreatePaymentMethodCardData' from external module "/Users/thorsten/Documents/Projects/stripe-react-native-master/src/types" but cannot be named.

5 export function useStripe() {
                  ~~~~~~~~~


Found 1 error.

βœ– Failed to build definition files.
bob build

build files for publishing

Options:
  --help     Show help                                                 [boolean]
  --version  Show version number                                       [boolean]

Error: Failed to build definition files.
    at build (/Users/thorsten/Documents/Projects/stripe-react-native-master/node_modules/@react-native-community/bob/lib/targets/typescript.js:112:11)
    at processTicksAndRejections (node:internal/process/task_queues:93:5)
    at async Object.handler (/Users/thorsten/Documents/Projects/stripe-react-native-master/node_modules/@react-native-community/bob/lib/cli.js:350:9)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Getting started & Installation fails

Describe the bug
Filing this feedback on behalf of @richardg-stripe - feel free to add additional context.

Difficulty installing the project and not having a working build process. Richard (extensive RN experience) was asked to use the library without reading the steps. The feedback is shared below πŸ‘‡

Notes from Richard's dogfooding session:

I created a new react native project following the instructions here: https://reactnative.dev/docs/environment-setup

Project won't install and doesn't have a build.

  • Project has both .circleci and Github actions couldn't find Circle build, github actions is failing.

  • added: "react-native-stripe-sdk": "stripe/stripe-react-native" to package.json. Ran: yarn install this generated errors relating to example directory.

  • git clone https://github.com/stripe/stripe-react-native && cd stripe-react-native && yarn install fails with the same error. cd examples && yarn install fixes it.

  • Examples obviously should be built when building the package.

(cd ios && pod install) fails

Auto-linking React Native module for target `StripeReactNativeTesting`: react-native-stripe-sdk
Analyzing dependencies
[!] CocoaPods could not find compatible versions for pod "react-native-stripe-sdk":
  In Podfile:
    react-native-stripe-sdk (from `../node_modules/react-native-stripe-sdk`)

Specs satisfying the `react-native-stripe-sdk (from `../node_modules/react-native-stripe-sdk`)` dependency were found, but they required a higher minimum deployment target.

I had modify ./ios/Podfile platform :ios, '1{0,1}.0' to make this work.

iOS Project still won't build

Error:

/Build/Products/Debug-iphonesimulator/StripeReactNativeTesting.app/StripeReactNativeTesting
ld: warning: Could not find or use auto-linked library 'swiftCoreMIDI'
ld: warning: Could not find or use auto-linked library 'swiftUniformTypeIdentifiers'
ld: warning: Could not find or use auto-linked library 'swiftCoreML'
Undefined symbols for architecture x86_64:
  "(extension in Foundation):__C.NSScanner.scanUpToString(Swift.String) -> Swift.String?", referenced from:
      static Stripe.STPPhoneNumberValidator.formattedRedactedPhoneNumber(for: Swift.String, forCountryCode: Swift.String?) -> Swift.String in libStripe.a(STPPhoneNumberValidator.o)
  "__swift_FORCE_LOAD_$_swiftUniformTypeIdentifiers", referenced from:
      __swift_FORCE_LOAD_$_swiftUniformTypeIdentifiers_$_Stripe in libStripe.a(PKPaymentAuthorizationViewController+Stripe_Blocks.o)

I got stuck here

Usage example

  • To cater for the greatest number of developers it should be a javascript example not a typescript one. typescript developers understand javascript, but the reverse isn't true.

  • The usage example is pseudo code - it doesn't actually work.

Don't fetch publishable key from server?

I'm not super-familar with ios / android SDK - but is fetching publishable key from your server a best-practice we recommend?

https://github.com/stripe/stripe-react-native/blob/master/example/src/App.tsx#L21-L29

It complicates their examples considerably and makes integration more difficult.

Android builds but adding import {StripeProvider} from 'react-native-stripe-sdk'; breaks the project

RN isn't giving me an error anymore, I just get a white screen as soon as I add that line.

But at one point it said:

 Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.

This error is located at:
    in StripeProvider (at example.js:36)
    in _default (at App.js:36)
    in RCTView (at View.js:34)
    in View (at SafeAreaView.js:41)
    in ForwardRef(SafeAreaView) (at App.js:31)
    in App (at renderApplication.js:45)
    in RCTView (at View.js:34)
    in View (at AppContainer.js:106)
    in RCTView (at View.js:34)
    in View (at AppContainer.js:132)
    in AppContainer (at renderApplication.js:39)

But this might be a red herring.

Android minSDKVersion

Had to update: android/build.gradle

minSdkVersion = {16,21}

createPaymentMethod should return a PaymentMethod instead of an ID

Is your feature request related to a problem? Please describe.
When creating a PaymentMethod via createPaymentMethod:

try {
  const paymentMethod = await createPaymentMethod(card);
  console.log('pm: ', paymentMethod);
 } catch (error) {
   console.log('error', error);
}

The result on success is:
pm: {"stripeId": "pm_1IBafVAasA93llSpCBoFpbZ1"}

The expected result for the equivalent method in Stripe.js is a PaymentMethod object which you can use to for instance check the card's issuer and country before making a payment. Since there's no getPaymentMethod method available in stripe-react-native you can only get that information by passing the ID to the server to retrieve the PaymentMethod there, which seems like an unnecessary extra step.

Describe the solution you'd like
Return the full PaymentMethod object instead of an object only containing the ID when calling createPaymentMethod.

Describe alternatives you've considered
Adding a getPaymentMethod method is possible, but we shouldn't do that as it would deviate from the API in Stripe.js getPaymentMethod would actually be a security risk, since you could then grab potentially sensitive info like the expiry date and last 4 digits of a card with just a publishable key.

Additional context
See also #46

final name of the library

Is your feature request related to a problem? Please describe.
As we named library differently a bit than you, we have mismatching names in several places so we should unify them.

Describe the solution you'd like
Adjust every place naming to stripe-react-native

Describe alternatives you've considered
We can stay with react-native-stripe-sdk, is up to you.

@thorsten-stripe let me know if you either agree with me or not.

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.