[Easy Steps] Stripe Payments with react native and nodeJS
Today I am going to share how we can stripe payment easily with react native mobile apps and nodeJS. Stripe is the best way to receive international payment so most clients prefer this payment gateway. By the way, there are a lot of plugins and libraries available for stripe payment with react native, but I am telling you an easy technique. In this tutorial we will discuss stripe API with the help of fetch. Create the payment token from the front end and receive payment from the back end with the help of nodeJS. So let’s begin:
- Setup Front end code with fetch function in react native and stripe API
- Setup Back end nodeJS code for process stripe token
- Full code example
1. Setup Front end code with fetch function in react native and stripe API
In this sample code we call the stripe API with the help of a fetch function in react native. It is an inbuilt function, so we don’t want to require or include you for this.
We need an object of card details and to pass into this function like this code. We need a secret token to send in the header’s authorization parameters. You can get this secret test from this url : stripe keys.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
async function testStripe() { let genCard = { 'card[number]': "4242424242424242", 'card[exp_month]': "11", 'card[exp_year]': "25", 'card[cvc]': "111" } let results = await fetch("https://api.stripe.com/v1/tokens", { method: "post", headers: { Accept: "application/json", "Content-Type": "application/x-www-form-urlencoded", Authorization: "Bearer " + "sk_test_XXXXXXXXXXXXXXXX", }, body: Object.keys(genCard) .map(key => key + '=' + genCard[key]) .join('&'), }).then(response => response.json()) console.log(results) return results['id']; } |
After run this code you can get response in this json form.
Response in terminal console.
1 2 3 |
{"card": {"address_city": null, "address_country": null, "address_line1": null, "address_line1_check": null, "address_line2": null, "address_state": null, "address_zip": null, "address_zip_check": null, "brand": "Visa", "country": "US", "cvc_check": "unchecked", "dynamic_last4": null, "exp_month": 11, "exp_year": 2025, "fingerprint": "RzGDlunRGus3lXqA", "funding": "credit", "id": "card_1KRF7VCgQKBY5pNoDLphPYvl", "last4": "4242", "metadata": {}, "name": null, "object": "card", "tokenization_method": null}, "client_ip": "203.115.84.63", "created": 1644409081, "id": "tok_1KRF7VCgQKBY5pNoxuUpSIws", "livemode": false, "object": "token", "type": "card", "used": false} |
2. Setup Back end nodeJS code for process stripe token
1 2 3 4 5 6 7 8 |
const stripe = require('stripe')('sk_test_xxxxx'); const charge = await stripe.charges.create({ amount: 2000, currency: 'usd', source: 'tok_created_from_api', description: 'My Product payment', }); |
In above code this is nodeJS code. in this code you needs to add stripe library. For installation you can add it with this following command in nodeJS project:
1 |
npm install stripe --save |
Now you need to require stripe library in your js file and call stripe charges function like that. You can get this token with help of REST API. and call into this function. After call this function our payment processed successfully.
3. Sample code for card is valid or invalid and get token with stripe api.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 |
import React from 'react'; import { Text, View, Image, ImageBackground, Button, Alert, TouchableOpacity, TextInput } from 'react-native'; import stripe from 'react-native-stripe-payments'; const stripePyament = (props) => { const [cardName, onChangeText] = React.useState(""); const [cardNumber, onChangeText1] = React.useState(""); const [cardDate, onChangeText2] = React.useState(""); const [cardCVV, onChangeText3] = React.useState(""); const [error, setError] = React.useState({cardName:false,cardNumber:false,cardDate:false,cardCVV:false}); function handleBackButtonClick() { props.history.goBack(null); return true; } const handleClick = async () => { let i = 0; if(cardName === ""){ setError(prev => ({...prev,cardName:true})); i++; } else setError(prev => ({...prev,cardName:false})); if(cardNumber === ""){ setError(prev => ({...prev,cardNumber:true})); i++; }else if(cardNumber.toString().length !== 19){ setError(prev => ({...prev,cardNumber:true})); i++; } else setError(prev => ({...prev,cardNumber:false})); if(cardDate === ""){ setError(prev => ({...prev,cardDate:true})); i++; } else setError(prev => ({...prev,cardDate:false})); if(cardCVV === ""){ setError(prev => ({...prev,cardCVV:true})); i++; } else setError(prev => ({...prev,cardCVV:false})); if(i === 0){ await submitForm(); }else { return; } } async function testStripe() { let lnum = cardDate.split('/') let genCard = { 'card[number]': cardNumber, 'card[exp_month]': parseInt(lnum[0]), 'card[exp_year]': parseInt(lnum[1]), 'card[cvc]': cardCVV } let results = await fetch("https://api.stripe.com/v1/tokens", { method: "post", headers: { Accept: "application/json", "Content-Type": "application/x-www-form-urlencoded", Authorization: "Bearer " + "sk_test_XXXXXXXXXXXXXXXX", }, body: Object.keys(genCard) .map(key => key + '=' + genCard[key]) .join('&'), }).then(response => response.json()) console.log(results) return results['id']; } const submitForm = async () => { let cardnum = cardDate.split('/') console.log(cardnum) const isCardValid = stripe.isCardValid({ number: cardNumber, expMonth: parseInt(cardnum[0]), expYear: parseInt(cardnum[1]), cvc: cardCVV, }); console.log(isCardValid) //return; if(isCardValid){ testStripe() }else{ setLoading(false); alert('Not valid card. Please add valid card details.') } } const handleChangeCard = (value) => { //if(value.length>16) return var v = value.replace(/\s+/g, '').replace(/[^0-9]/gi, '') var matches = v.match(/\d{4,16}/g); var match = matches && matches[0] || '' var parts = [] for (let i=0, len=match.length; i<len; i+=4) { parts.push(match.substring(i, i+4)) } if (parts.length) { value = parts.join(' ') } /*else { return value }*/ onChangeText1(value); } const handleChangeCVV = (text) => { if(text.length>3) return onChangeText3(text); } const handleChangeDate = (text) => { if(text.length>5) return if(text.length == 2 && cardDate.length == 1){ text += '/' }else if(text.length == 2 && cardDate.length == 3){ text = text.substring(0 , text.length-1) } onChangeText2(text); } return ( <View style={styles.mainBoxOuter}> <View style={styles.mainHeaderOuter}> <Text style={styles.headerTitle}>Add Card</Text> </View> <View style={styles.mainBody}> <View style={styles.centerBoxNo}> <View style={styles.centerBox}> <Text style={[styles.mainTitle, styles.blackText]}>Add Payment Card</Text> <Text style={[styles.subTitle, styles.greyText]}>Please fill the detail below if you want to add card</Text> </View> <View style={styles.formOuter}> <View style={styles.formGroupDiv}> <View style={styles.formGroupNew}> <Text style={styles.formLabelNew}>Cardholder Name</Text> <TextInput style={[styles.formControlNew, { borderColor: error.cardName ? 'red' : '#b2b2b2'}]} value={cardName} onChangeText={onChangeText} placeholder="" placeholderTextColor = "#fbfbfb" /> </View> </View> <View style={styles.formGroupDiv}> <View style={styles.formGroupNew}> <Text style={styles.formLabelNew}>Card Number</Text> <TextInput style={[styles.formControlNew, { borderColor: error.cardNumber ? 'red' : '#b2b2b2'}]} value={cardNumber} onChangeText={handleChangeCard} placeholder="" placeholderTextColor = "#fbfbfb" keyboardType='numeric' /> </View> </View> <View style={styles.formGroupDiv}> <View style={styles.formGroupNew}> <Text style={styles.formLabelNew}>Expiry Date</Text> <TextInput style={[styles.formControlNew, { borderColor: error.cardDate ? 'red' : '#b2b2b2'}]} value={cardDate} onChangeText={handleChangeDate} placeholder="" placeholderTextColor = "#fbfbfb" keyboardType='numeric' /> </View> <View style={styles.formGroupNew}> <Text style={styles.formLabelNew}>CVV</Text> <TextInput style={[styles.formControlNew, { borderColor: error.cardCVV ? 'red' : '#b2b2b2'}]} value={cardCVV} onChangeText={handleChangeCVV} placeholder="" placeholderTextColor = "#fbfbfb" keyboardType='numeric' /> </View> </View> <View style={styles.formBtn}> <TouchableOpacity style={styles.btnGradientDiv} onPress={handleClick}> <Text style={styles.TextStyle}>Add Card</Text> </TouchableOpacity> </View> </View> </View> </View> ); } export default stripePayment |
Result: tok_XXXXXXXXX
This token will use in nodejs stripe create charges function after that your payment will processed successfully.