Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Promise based API #3

Merged
merged 3 commits into from
Oct 25, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 21 additions & 24 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

React Native wrapper around our Android and iOS mobile SDKs

To know more about Razorpay payment flow and steps involved, please read up here:
<https://docs.razorpay.com/docs>

## Installation

Run the following on terminal from your project directory:
Expand Down Expand Up @@ -83,25 +86,13 @@ link iOS SDK as explained in the previous section:

### Steps

1. Import Razorpay module to your component:
```js
import { Razorpay } from 'react-native-razorpay';
const { RazorpayCheckout, RazorpayEventEmitter } = Razorpay;
```
2. Instantiate an event emitter with `RazorpayEventEmitter`:
```js
const razorpayEvents = new NativeEventEmitter(RazorpayEventEmitter);
```
3. Add payment event listeners to your component, preferably in `componentWillMount`:
1. Import RazorpayCheckout module to your component:
```js
razorpayEvents.addListener('onPaymentError', (data) => {
alert("Error: " + data.code + " | " + data.description)
});
razorpayEvents.addListener('onPaymentSuccess', (data) => {
alert("Success: " + data.payment_id)
});
import RazorpayCheckout from 'react-native-razorpay';
```
4. Call RazorpayCheckout's `open` method with `options`, preferably on a user action:
2. Call `RazorpayCheckout.open` method with the payment `options`. The method
returns a **JS Promise** where `then` part corresponds to a successful payment
and the `catch` part corresponds to payment failure.
```js
<TouchableHighlight onPress={() => {
var options = {
Expand All @@ -111,17 +102,22 @@ razorpayEvents.addListener('onPaymentSuccess', (data) => {
key: 'rzp_test_1DP5mmOlF5G5ag',
amount: '5000',
name: 'foo',
prefill: {email: '[email protected]', contact: '8879524924', name: 'Pranav Gupta'},
prefill: {
email: '[email protected]',
contact: '8955806560',
name: 'Akshay Bhalotia'
},
theme: {color: '#F37254'}
}
RazorpayCheckout.open(options)
RazorpayCheckout.open(options).then(data =>
{ alert("Success: " + data.payment_id) }
).catch(data =>
{ alert("Error: " + data.code + " | " + data.description) }
);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

change it to below style

RazorpayCheckout.open(options).then((data) => {
    // handle success
    alert(`Success: ${data.payment_id}`)
}).catch((error) => {
    // handle error
    alert(`Error: ${error.code} | ${error.description}`)    
})

}}>
```
5. Stop listening for payment events, preferably in `componentWillMount`:
```js
razorpayEvents.remove();
```

A descriptive [list of valid options for checkout][options] is available (under
Manual Checkout column).

## Contributing

Expand All @@ -143,3 +139,4 @@ or [contact us][contact] to help you with integrations.
[integrations]: https://razorpay.com/integrations "List of our integrations"
[ios-docs]: https://docs.razorpay.com/v1/page/ios-integration "Documentation for the iOS Integration"
[LICENSE]: /LICENSE "MIT License"
[options]: https://docs.razorpay.com/docs/checkout-form#checkout-fields "Checkout Options"
28 changes: 25 additions & 3 deletions RazorpayCheckout.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,29 @@

import { NativeModules, NativeEventEmitter } from 'react-native';

export const Razorpay = {
RazorpayCheckout: NativeModules.RazorpayCheckout,
RazorpayEventEmitter: NativeModules.RazorpayEventEmitter
const razorpayEvents = new NativeEventEmitter(NativeModules.RazorpayEventEmitter);

const removeSubscriptions = () => {
razorpayEvents.removeAllListeners('Razorpay::PAYMENT_SUCCESS');
razorpayEvents.removeAllListeners('Razorpay::PAYMENT_ERROR');
};

class RazorpayCheckout {
static open(options, successCallback, errorCallback) {
return new Promise(function(resolve, reject) {
razorpayEvents.addListener('Razorpay::PAYMENT_SUCCESS', (data) => {
let resolveFn = successCallback || resolve;
resolveFn(data);
removeSubscriptions();
});
razorpayEvents.addListener('Razorpay::PAYMENT_ERROR', (data) => {
let rejectFn = errorCallback || reject;
rejectFn(data);
removeSubscriptions();
});
NativeModules.RazorpayCheckout.open(options);
});
}
}

export default RazorpayCheckout;
10 changes: 5 additions & 5 deletions android/src/main/java/com/razorpay/rn/RazorpayModule.java
Original file line number Diff line number Diff line change
Expand Up @@ -115,15 +115,15 @@ public void onActivityResult(int requestCode, int resultCode, Intent data){
if (data != null) {
Bundle extras = data.getExtras();
if (extras != null) {
result = extras.getString("RESULT");
}
result = extras.getString("RESULT");
}
}
if (resultCode == 1) {
try {
JSONObject resultJson = new JSONObject(result);
WritableMap successParams = Arguments.createMap();
successParams.putString(MAP_KEY_PAYMENT_ID, resultJson.getString(MAP_KEY_RZP_PAYMENT_ID));
sendEvent("onPaymentSuccess", successParams);
sendEvent("Razorpay::PAYMENT_SUCCESS", successParams);
} catch(Exception e){}
}
else {
Expand All @@ -133,8 +133,8 @@ public void onActivityResult(int requestCode, int resultCode, Intent data){
WritableMap errorParams = Arguments.createMap();
errorParams.putInt(MAP_KEY_ERROR_CODE, resultCode);
errorParams.putString(MAP_KEY_ERROR_DESC, result);
sendEvent("onPaymentError", errorParams);
}
sendEvent("Razorpay::PAYMENT_ERROR", errorParams);
}
}

private void sendEvent(String eventName, @Nullable WritableMap params) {
Expand Down
47 changes: 21 additions & 26 deletions example/index.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
/**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/

import React, { Component } from 'react';
import {
Expand All @@ -15,47 +15,42 @@ import {
NativeEventEmitter
} from 'react-native';

import { Razorpay } from 'react-native-razorpay';
const { RazorpayCheckout, RazorpayEventEmitter } = Razorpay;

const razorpayEvents = new NativeEventEmitter(RazorpayEventEmitter);
import RazorpayCheckout from 'react-native-razorpay';

class example extends Component {
componentWillMount() {
razorpayEvents.addListener('onPaymentError', (data) => {
alert("Error: " + data.code + " | " + data.description)
});
razorpayEvents.addListener('onPaymentSuccess', (data) => {
alert("Success: " + data.payment_id)
});
}

render() {
return (
<View style={styles.container}>
<TouchableHighlight onPress={() => {
<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: '[email protected]', contact: '8879524924', name: 'Pranav Gupta'},
prefill: {
email: '[email protected]',
contact: '8955806560',
name: 'Akshay Bhalotia'
},
theme: {color: '#F37254'}
}
RazorpayCheckout.open(options)
}}>
RazorpayCheckout.open(options).then((data) => {
// handle success
alert(`Success: ${data.payment_id}`);
}).catch((error) => {
// handle failure
alert(`Error: ${error.code} | ${error.description}`);
});
}}>
<Text style = {styles.text}>Pay</Text>
</TouchableHighlight>
</View>
</TouchableHighlight>
</View>
);
}

componentWillUnmount () {
razorpayEvents.remove();
}

}

const styles = StyleSheet.create({
Expand Down
2 changes: 1 addition & 1 deletion example/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,6 @@
"dependencies": {
"react": ">=15.0.0",
"react-native": ">=0.30.0",
"react-native-razorpay": ">=1.0.0"
"react-native-razorpay": "./../"
}
}
8 changes: 5 additions & 3 deletions ios/RazorpayEventEmitter.m
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ @implementation RazorpayEventEmitter
RCT_EXPORT_MODULE();

- (NSArray<NSString *> *)supportedEvents {
return @[ @"onPaymentSuccess", @"onPaymentError" ];
return @[ @"Razorpay::PAYMENT_SUCCESS", @"Razorpay::PAYMENT_ERROR" ];
}

- (void)startObserving {
Expand All @@ -38,11 +38,13 @@ - (void)stopObserving {
}

- (void)paymentSuccess:(NSNotification *)notification {
[self sendEventWithName:@"onPaymentSuccess" body:notification.userInfo];
[self sendEventWithName:@"Razorpay::PAYMENT_SUCCESS"
body:notification.userInfo];
}

- (void)paymentError:(NSNotification *)notification {
[self sendEventWithName:@"onPaymentError" body:notification.userInfo];
[self sendEventWithName:@"Razorpay::PAYMENT_ERROR"
body:notification.userInfo];
}

+ (void)onPaymentSuccess:(NSString *)payment_id {
Expand Down