Problem with using Stripe in React Native
I added stripe to my React Native application using following command.
Added Stripe to the project as shown below.
And now I’m getting following error.
Our React Native code does not actually run on Node.JS.
I know while building React Native
we use NPM
we have a node server running in the background
so it feels like
we are in Node.JS land
we can use
everything Node.JS has to offer.
But that’s not true.
React Native code can’t depend on Node.JS
Node.JS is not shipped with ios.
we can’t use any of Node.JS packages including
we can’t use
stripe npm module.
Now you can remove
require('stripe') line that was added
in the last step.
stripe.js is a nice wrapper around stripe api. stripe api is very well documented and is easy to use. Since we can’t use stripe.js we will use stripe api.
We will use fetch to create a credit card token using api.
Here, the header has 3 keys. Lets go through them one-by-one:
'Accept': 'application/json': Designates the content to be in JSON format.
'Content-Type': 'application/x-www-form-urlencoded': This tells the endpoint that the payload will be one giant query string where name and value pairs will be separated by the ampersand.
'Authorization': 'Bearer ' + '<YOUR-STRIPE-API-KEY>': This key is to authorize our actions on Stripe. Here
Beareris just a prefix which we need to attach to the api-key because Stripe uses OAuth 2.0 . You can read more on the Bearer token usage here .
Payload needs to contain credit card details.
the payload should be one query string.
An example of this would be:
Let’s prepare a proper payload.
Now we can attach
the body part of the fetch request
we are good to go.
Here’s the whole code snippet.
This is an example of registering a credit card with stripe and getting the token. Similar implementations can be done for other API endpoints.