I’ve gotten so much good feedback from the Square team (and others) on this forum, I figured I’d contribute something for the next guy.
One of the problems that I ran into while integrating in-app payments into my React Native app was the the examples all take the old school Object Oriented approach, and I (and most of the RN community) prefer a functional approach.
Since I am still new to RN, this took a bit of reading and experimentation (I’ve never learned the OO appraoches). The sample code below is close to what I landed on.
Simple to integrate: On the component that you will start credit card processing, merge in the code below.
This code is lifted verbatim (except for some logging) from Square docs and reordered slightly:
Getting Started with the React Native Plugin for In-App Payments SDK
...
import { SQIPCore, SQIPCardEntry } from 'react-native-square-in-app-payments';
...
const ReviewOrderScreen = ({ route, navigation }) => {
// ...
const onStartCardEntry = async () => {
console.log('onStartCardEntry')
await SQIPCore.setSquareApplicationId('sandbox-sq0idb-nyLT7WXGrzL-kk88hjhQRA');
if (Platform.OS === 'ios') {
await SQIPCardEntry.setIOSCardEntryTheme({
saveButtonFont: {
size: 25,
},
saveButtonTitle: 'Pay 💳 ',
keyboardAppearance: 'Light',
saveButtonTextColor: {
r: 255,
g: 0,
b: 125,
a: 0.5,
},
});
}
await SQIPCardEntry.startCardEntryFlow(
{ collectPostalCode: false },
onCardNonceRequestSuccess,
onCardEntryCancel,
);
}
const onCardNonceRequestSuccess = async (cardDetails) => {
console.log('onCardNonceRequestSuccess')
try {
// take payment with the card details
// await chargeCard(cardDetails);
// payment finished successfully
// you must call this method to close card entry
await SQIPCardEntry.completeCardEntry(
this.onCardEntryComplete(),
);
} catch (ex) {
// payment failed to complete due to error
// notify card entry to show processing error
await SQIPCardEntry.showCardNonceProcessingError(ex.message);
}
}
const onCardEntryComplete = () => {
console.log('onCardEntryComplete')
}
const onCardEntryCancel = () => {
console.log('onCardEntryCancel')
}
// ...
return (
// ...
< ... onPress={() => { onStartCardEntry() } ... />
// ...
)
}
Submitted in the hopes that someone will find it helpful.