Skip to content

Instantly share code, notes, and snippets.

@mootrichard
Last active September 21, 2018 15:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mootrichard/6d34a09f965d203a7eb4813b73d9bcbd to your computer and use it in GitHub Desktop.
Save mootrichard/6d34a09f965d203a7eb4813b73d9bcbd to your computer and use it in GitHub Desktop.
A modified CheckoutScreen for a custom Keypad
/*
Copyright 2018 Square Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {
View, Text, Alert, Platform,
ActionSheetIOS, // eslint-disable-line react-native/split-platform-components
} from 'react-native';
import { withGlobalize } from 'react-native-globalize';
import {
startCheckoutAsync,
startReaderSettingsAsync,
getAuthorizedLocationAsync,
CheckoutErrorCanceled,
CheckoutErrorSdkNotAuthorized,
ReaderSettingsErrorSdkNotAuthorized,
UsageError,
} from 'react-native-square-reader-sdk';
import CustomButton from '../components/CustomButton';
import SquareLogo from '../components/SquareLogo';
import { defaultStyles } from '../styles/common';
import KeyPadButton from 'react-native-square-reader-sdk/reader-sdk-react-native-quickstart/app/components/KeypadButton';
class CheckoutScreen extends Component {
constructor(props) {
super(props);
this.state = {
currentValue: [0, 0],
};
}
async componentWillMount() {
try {
const authorizedLocation = await getAuthorizedLocationAsync();
this.setState({ locationName: authorizedLocation.name });
} catch (ex) {
if (__DEV__) {
Alert.alert(ex.debugCode, ex.debugMessage);
} else {
Alert.alert(ex.code, ex.message);
}
}
}
async onCheckout() {
const { navigate } = this.props.navigation;
// A checkout parameter is required for this checkout method
const checkoutParams = {
amountMoney: {
amount: parseInt(this.state.currentValue.slice(2).join(''), 10),
currencyCode: 'USD', // optional, use authorized location's currency code by default
},
// Optional for all following configuration
skipReceipt: false,
alwaysRequireSignature: true,
allowSplitTender: false,
note: 'Hello 💳 💰 World!',
tipSettings: {
showCustomTipField: true,
showSeparateTipScreen: false,
tipPercentages: [15, 20, 30],
},
additionalPaymentTypes: ['cash', 'manual_card_entry', 'other'],
};
try {
const checkoutResult = await startCheckoutAsync(checkoutParams);
// Consume checkout result from here
const currencyFormatter = this.props.globalize.getCurrencyFormatter(
checkoutResult.totalMoney.currencyCode,
{ minimumFractionDigits: 0, maximumFractionDigits: 2 },
);
const formattedCurrency = currencyFormatter(checkoutResult.totalMoney.amount / 100);
Alert.alert(`${formattedCurrency} Successfully Charged`, 'See the debugger console for transaction details. You can refund transactions from your Square Dashboard.');
console.log(JSON.stringify(checkoutResult));
} catch (ex) {
let errorMessage = ex.message;
switch (ex.code) {
case CheckoutErrorCanceled:
// Handle canceled transaction here
console.log('transaction canceled.');
break;
case CheckoutErrorSdkNotAuthorized:
// Handle sdk not authorized
navigate('Deauthorizing');
break;
default:
if (__DEV__) {
errorMessage += `\n\nDebug Message: ${ex.debugMessage}`;
console.log(`${ex.code}:${ex.debugCode}:${ex.debugMessage}`);
}
Alert.alert('Error', errorMessage);
break;
}
}
}
onSettings() {
const { navigate } = this.props.navigation;
if (Platform.OS !== 'ios') {
navigate('Setting', { locationName: this.state.locationName });
} else {
ActionSheetIOS.showActionSheetWithOptions({
options: ['Reader Settings', 'Deauthorize', 'Cancel'],
destructiveButtonIndex: 1,
cancelButtonIndex: 2,
title: `Location: ${this.state.locationName}`,
},
async (buttonIndex) => {
if (buttonIndex === 0) {
// Handle reader settings
try {
await startReaderSettingsAsync();
} catch (ex) {
let errorMessage = ex.message;
switch (ex.code) {
case ReaderSettingsErrorSdkNotAuthorized:
// Handle reader settings not authorized
navigate('Deauthorizing');
break;
case UsageError:
default:
if (__DEV__) {
errorMessage += `\n\nDebug Message: ${ex.debugMessage}`;
console.log(`${ex.code}:${ex.debugCode}:${ex.debugMessage}`);
}
Alert.alert('Error', errorMessage);
break;
}
}
} else if (buttonIndex === 1) {
// Handle Deauthorize
navigate('Deauthorizing');
}
});
}
}
addValue(value) {
this.setState((prevState) => {
return {
currentValue: [...prevState.currentValue, value],
};
});
}
displayValue() {
if (this.state.currentValue.length === 2) {
return '0.00';
}
if (this.state.currentValue.length > 2 && this.state.currentValue.length < 4) {
return `0.${this.state.currentValue[1]}${this.state.currentValue[2]}`;
}
if (this.state.currentValue.length === 4) {
return `${this.state.currentValue[1]}.${this.state.currentValue[2]}${this.state.currentValue[3]}`;
}
if (this.state.currentValue.length > 3){
return `${ this.state.currentValue.slice(2,-2).join('')}`+
`.${ this.state.currentValue[this.state.currentValue.length-2 ] }` +
`${ this.state.currentValue[this.state.currentValue.length-1 ] }`;
}
return this.state.currentValue.join('');
}
clearValue() {
this.setState({
currentValue: [0, 0]
})
}
render() {
return (
<View style={defaultStyles.pageContainer}>
<View style={defaultStyles.logoContainer}>
<SquareLogo />
</View>
<Text style={defaultStyles.title}>
Charge $
{
`${this.displayValue()}`
}
</Text>
<View style={{flex: 4, flexDirection:'column', alignContent: 'stretch'}}>
<View style={{flexDirection: 'row',}}>
<KeyPadButton
title="7"
onPress={() => this.addValue(7)}
primary
/>
<KeyPadButton
title="8"
onPress={() => this.addValue(8)}
primary
/>
<KeyPadButton
title="9"
onPress={() => this.addValue(9)}
primary
/>
</View>
<View style={{flexDirection: 'row',}}>
<KeyPadButton
title="4"
onPress={() => this.addValue(4)}
primary
/>
<KeyPadButton
title="5"
onPress={() => this.addValue(5)}
primary
/>
<KeyPadButton
title="6"
onPress={() => this.addValue(5)}
primary
/>
</View>
<View style={{flexDirection: 'row',}}>
<KeyPadButton
title="1"
onPress={() => this.addValue(1)}
primary
/>
<KeyPadButton
title="2"
onPress={() => this.addValue(2)}
primary
/>
<KeyPadButton
title="3"
onPress={() => this.addValue(3)}
primary
/>
</View>
<View style={{flexDirection: 'row',}}>
<KeyPadButton
title="0"
onPress={() => this.addValue(0)}
primary
/>
<KeyPadButton
title="Clear"
onPress={() => this.clearValue()}
primary
/>
</View>
</View>
<View style={defaultStyles.buttonContainer}>
<CustomButton
title="Charge"
onPress={() => this.onCheckout()}
primary
/>
</View>
</View>
);
}
}
CheckoutScreen.propTypes = {
globalize: PropTypes.object.isRequired,
navigation: PropTypes.object.isRequired,
};
export default withGlobalize(CheckoutScreen);
/*
Copyright 2018 Square Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import React from 'react';
import PropTypes from 'prop-types';
import { StyleSheet, TouchableOpacity, Text } from 'react-native';
const KeyPadButton = props => (
<TouchableOpacity
style={props.disabled
? [styles.button, props.primary
? styles.primaryButton : styles.secondaryButton, styles.disabledButton]
: [styles.button, props.primary
? styles.primaryButton : styles.secondaryButton]}
onPress={props.onPress}
disabled={props.disabled}
>
<Text style={props.disabled
? [styles.buttonText, styles.disabledButtonText]
: styles.buttonText}
>
{props.title}
</Text>
</TouchableOpacity>
);
KeyPadButton.defaultProps = {
disabled: false,
primary: false,
};
KeyPadButton.propTypes = {
title: PropTypes.string.isRequired,
onPress: PropTypes.func.isRequired,
disabled: PropTypes.bool,
primary: PropTypes.bool,
};
const styles = StyleSheet.create({
button: {
flex: 1,
alignItems: 'center',
height: 84,
justifyContent: 'center',
alignSelf: 'stretch',
},
primaryButton: {
backgroundColor: '#3972B2',
},
secondaryButton: {
borderColor: 'white',
borderWidth: 1,
},
disabledButton: {
borderColor: 'rgba(255, 255, 255, 0.6)',
},
buttonText: {
color: 'white',
fontSize: 20,
fontWeight: '600',
},
disabledButtonText: {
color: 'rgba(255, 255, 255, 0.6)',
},
});
export default KeyPadButton;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment