How to close the razorpay webview after callback_url success response in react-native? - react-native

I am intergrating react-native-razorpay for payment in my react-native application. I could get the payment done and by providing the callback_url in the payment options to the RazorpayCheckOut i could even call my backend server and update the payment action but when the callback_url to server is providing the app with the success message there is no way that i could read the message and close the razorpay webview that is opened in my react-native app.
Is there any way that i can close the ebview of razorpay and move back to app on receiving the sucess message of callback_url?

Based on the sample code listed here https://github.com/razorpay/react-native-razorpay
RazorPay returns data.razorpay_payment_id as a response.
You could use that payment_id to get the status of your payment from the back-end
I used the ruby gem in my backend API to get the payment status
Razorpay::Payment.fetch("payment_id")
https://razorpay.com/docs/server-integration/ruby/
<TouchableHighlight onPress={() => {
var options = {
description: 'Credits towards consultation',
image: 'https://i.imgur.com/3g7nmJC.png',
currency: 'INR',
key: 'rzp_test_1DP5mmOlF5G5ag',
amount: '5000',
name: 'foo',
prefill: {
email: 'void#razorpay.com',
contact: '9191919191',
name: 'Razorpay Software'
},
theme: {color: '#F37254'}
}
RazorpayCheckout.open(options).then((data) => {
// handle success
alert(`Success: ${data.razorpay_payment_id}`);
}).catch((error) => {
// handle failure
alert(`Error: ${error.code} | ${error.description}`);
});
}}>

Related

ApplePay using stripe-react-native show Payment Not Completed while return payment method result

I'm having trouble integrating ApplePay using stripe-react-native lib to my app. I followed the guide in stripe doc and manage to open the payment sheet. But when proceed to payment the UI loading for a bit then show 'Payment Not Completed!' then close the sheet. However the payment function still return the success result (payment method info).
Fail payment on UI
My implementation code:
App.js
return (
<Provider store={store}>
<StripeProvider publishableKey="pk_test_51L6AWmGROtrteUVR8vR4WLpcNT1KFiHJjWYjGYiYB0Fwh0HdRDkbj9fy4Hlp88z1S76TufwTL755QUnWswWUUhOT00UijEYwS3"
merchantIdentifier="merchant.com.adamo.dropr"
>
<PersistGate persistor={persistor}>
<StackNavigation />
<FlashMessage position="top" floating={true} hideStatusBar={false} />
<GlobalUI ref={GlobalService.globalUIRef} />
</PersistGate>
</StripeProvider>
</Provider>
);
open payment sheet file:
const pay = async () => {
// ...
const { paymentMethod, error } = await presentApplePay({
cartItems: [
{
label: "Example item name",
amount: "100.00",
isPending: false,
paymentType: "Immediate",
},
],
country: "GB",
currency: "GBP",
shippingMethods: [
{
amount: "20.00",
identifier: "DPS",
label: "Courier",
detail: "Delivery",
isPending: true,
},
],
requiredShippingAddressFields: ["emailAddress", "phoneNumber"],
requiredBillingContactFields: ["phoneNumber", "name"],
});
console.log(paymentMethod);
if (error) {
console.log(error);
} else {
console.log("success");
}
// ...
};
{isApplePaySupported && (
<ApplePayButton
onPress={pay}
type="plain"
buttonStyle="black"
borderRadius={8}
style={{
marginTop: Spacing.height5,
width: Spacing.width157,
height: Spacing.height52,
}}
/>
)}
And I already had the apple pay certificate added to the Stripe dashboard.
Stripe dashboard
Please tell me if I missing something in the configuration or did something wrong with the implementation.
there are two parts in the Apple Pay flow.
The first part is to call presentApplePay() to present the Apple PaymentSheet to your customer, so that they can choose the payment method for this payment. You've implemented the first part correctly.
The second part is to call confirmApplePayPayment() to submit the payment to Stripe, and this is missing in your flow. You should first send a request to your backend to create a PaymentIntent, and pass the PaymentIntent's client_secret back to your iOS app, so that you can call confirmApplePayPayment() with the returned client_secret.
You can refer to this doc and learn how to submit payment to Stripe. This guide also provides example code that you can directly use in your project.

Implementation React native google pay

I am implementing it .
react-native-google-pay
It is installed and showing a login popup as expected but i am not able to get how can i test it. As there is no way to test it.
this is my code
const requestData = {
cardPaymentMethod: {
tokenizationSpecification: {
type: 'PAYMENT_GATEWAY',
gateway: 'stripe',
gatewayMerchantId: '',
stripe: {
publishableKey: '',
version: '2018-11-08',
}
},
allowedCardNetworks,
allowedCardAuthMethods,
},
transaction: {
totalPrice: amount_to_add,
totalPriceStatus: 'FINAL',
currencyCode: 'USD',
},
merchantName: 'Merchant',
};
In this what is the value of gatewayMerchantId,type.
And Let me know if someone have dummy cards or a way to test it. As it is showing error, as well as no trasaction response of 200 or rejection.
I haven't done a Google Pay integration with Stripe, but react-native-google-pay looks like a thin wrapper around the Google Pay API. I'd suggest looking at Google Pay's documentation to supplement the holes in the library's documentation.
In this case, I'd suggest changing the values in the tokenizationSpecification to match Google Pay's docs:
const requestData = {
cardPaymentMethod: {
tokenizationSpecification: {
type: 'PAYMENT_GATEWAY',
parameters: {
gateway: "stripe"
"stripe:version": "2018-10-31"
"stripe:publishableKey": "YOUR_PUBLIC_STRIPE_KEY"
}
},
allowedCardNetworks,
allowedCardAuthMethods,
},
transaction: {
totalPrice: amount_to_add,
totalPriceStatus: 'FINAL',
currencyCode: 'USD',
},
merchantName: 'Merchant',
};
When I integrated to Google Pay, I used my real credit card number (I was unable to get anything fake into Google Pay) and enabled test mode. The library seems to support that test mode like this:
// Set the environment before the payment request
GooglePay.setEnvironment(GooglePay.ENVIRONMENT_TEST);

What is razorpay orders api and how to integrate it with react native?

I am trying to implement a payment module in my react native app and trying to use Razorpay. As per documentation, there are two main things, the checkout, and the orders API. What is the difference between the two? What is exactly orders API and how is it to be used in react native? They have given many options in the docs to integrate the orders API like java, ruby, etc but nothing for react native. So any help would be appreciated. Thank you.
The Razorpay has integrated the checkout function for react-native, which means it will lead to the calling of payment API, what this does is accepts payment from any user directly transferring the money without any details. With orders API, Razorpay enables you to create Orders that can be linked to payments. That means So that whatever payment arrives in your wallet is described with what has the payment related to. For example, suppose you have to show a product you wish to sell.
So first, you will have to create an order by calling orders API on your server-side, i.e. Node.JS or something else with request parameters like the amount, self-generated receipt number, and optional notes on who the user is. then after receiving the order_id, you will pass onto the mobile application and start the checkout functionality provided by react-native-razorpay.
Here is the example on how I used the react-native-razorpay.
On server-side - node.js:
const Razorpay = require("razorpay");
//...
let rzp = new Razorpay({
key_id: "", // your `KEY_ID`
key_secret: "" // your `KEY_SECRET`
});
//Inside Create Order Function
rzp.orders
.create({
amount: price * 100,
currency: "INR",
receipt: "", // Add receipt string
payment_capture: 1, // auto capture payment config
notes: { username, planId: id }
// custom notes, you can use this in received response as key-value pair
})
.then(data => { // created order response
let sendToApplicationResponse = { // Creating the response send to mobile app
username,
orderId: data.id,
receipt: data.receipt
};
return sendToApplicationResponse;
})
On react-native application-side:
import RazorpayCheckout from 'react-native-razorpay';
//.....
onPress={async () => {
//Call my server to create an Order
// passing userId and price and plan selected as request parameters
// and waiting for the response
const response = await .....
// You can add parameters given in payment API
var options = {
currency: 'INR',
key: '', // add your razorpay key here
amount: price * 100,
order_id: response.data.orderId, // using the orderId which
prefill: { // add prefill details if you want
contact: "",
name: "",
},
payment_capture: 1,
};
// Call the razorpay checkout
RazorpayCheckout.open(options)
.then(data => {
console.log('RazorpayCheckout', data);
Alert.alert('Payment Successful!');
})
.catch(error => {
Alert.alert('Something went wrong!');
// Alert.alert(`Error: ${error.code} | ${error.description}`);
});
}}

React native paypal wrapper crash on pressing back button

paypal(price,bookingId){
PayPal.initialize(PayPal.SANDBOX, "ARFiHtTEV2P17X4Hdei6M4vqoLx_UVGAvELcTpNprLC4hNklLmNq7cl_z5OqhRGoBzzVRmS9sG-RfhXx");
PayPal.pay({
price: price.toString(),
currency: 'USD',
description: 'Payment for fuel delivery app',
})
.then(confirm => {
var pid = confirm.response.id
this.paypalpaymentapi(price,bookingId,pid)
})
.catch(error => Alert.alert(error))
}
Above code is for paypal payment in react native.Now the problem in above code is that when PayPal.initialize is called and after that when I press back button from initialized paypal then my app crashes and it gives me error that
class castexception can't cast from readablenativemap to String.
How can I resolve this issue ?

Payment token becomes undefined after the Apple Pay process

I am developing an Apple Pay with react-native. I configured everything and I used react-native-payment component. Here is my code:
onPressApplePay=()=>{
console.log("1- start Apple Pay");
if (!DataManager.getInstance().isConnected()) {
this.myAlert(I18n.t("NoInternetConnectionState"));
return;
}
const DETAILS = {
id: 'basic-example',
displayItems: [
{
label: 'items',
amount: { currency: 'EUR', value: '2' },
},
],
total: {
label: 'MyApp',
amount: { currency: 'EUR', value: '2' },
},
};
const METHOD_DATA = [{
supportedMethods: ['apple-pay'],
data: {
merchantIdentifier: 'merchant.com.myapp',
supportedNetworks: [ 'mastercard', 'visa'],
countryCode: 'IT',
currencyCode: 'EUR'
}
}];
const paymentRequest = new PaymentRequest(METHOD_DATA, DETAILS);
console.log("2- paymentRequest.show", paymentRequest);
paymentRequest.show()
.then((paymentResponse) => {
const { paymentToken } = paymentResponse.details; // On Android, you need to invoke the `getPaymentToken` method to receive the `paymentToken`.
paymentRequest.canMakePayments()
.then(canMakePayments => {
console.log("canMakePayments", canMakePayments);
console.log("paymentToken", paymentToken);
// Show fallback payment method
});
})
.catch((err) => {
console.log("4- err", err);
console.log("5- paymentRequest", err);
//alert("The apple pay cancel");
// The API threw an error or the user closed the UI
});
The problem is that as I try to execute the Apple Pay, it says that the 'Payment is not completed' and the token becomes undefined. Can you please ket me know where the problem might be hiden.
I should mention that I tried this code on a real device using both real card and sandBox and in all cases it was failed. Thanks in advance.
This component is also working with stripe and Braintree. The problem was that I needed to add a gateway and a public key which in my case it provided from stripe.
const METHOD_DATA = [{
supportedMethods: ['apple-pay'],
data: {
merchantIdentifier: 'merchant.yyyy.xxxx',
supportedNetworks: [ 'mastercard'],
countryCode: 'IT',
currencyCode: 'EUR',
paymentMethodTokenizationParameters: {
parameters: {
gateway: 'stripe',
'stripe:publishableKey': 'pk_test_XXXXXXX',
'stripe:version': '5.0.0' // Only required on Android
}
}
}
}];
Then I installed the following add on:
yarn add react-native-payments-addon-stripe
yarn add react-native-payments-cli
yarn react-native-payments-cli -- link stripe
(You also need the Carthage update there to make them work)
Then I made an account in stripe.com and use the publish key of that and finally it works!!
Also I have added paymentResponse.complete('success'); to show the successful payment at the end. Without that it sucks in a loop of waiting and finally shows 'Payment is not complete'.
Now I have a successful message with a nice token!
I should mention that in the case that you don't use stripe or Braintree, you will not see any token and it will be always undefined. It is natural, so don't worry. You just need to pass paymentResponse.details as a JSON to your bank provider and it will work. Because in that case the transactionid will be important which you have it.
After that, you go through these steps of installing from this link . You also need to do these steps regarded to certificates for Apple Pay:
1- First on your App ID in your apple developer account you should enable the Apple Pay with the merchant ID.
2- Then you need to ask from your bank for a certificate on you merchant which is a file that looks like this:
XXXXX.certSigningRequest.txt
3- Then select your app ID and go to Apple Pay section which was enabled in step one and upload the certificate there.
Done! Your Apple Pay will work.
The mention saved me! I didn't realize that it was normal the token would be nil if you aren't using Stripe/Braintree!