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

Add rebootReader method #629

Merged
merged 2 commits into from
Mar 4, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,13 @@ class StripeTerminalReactNativeModule(reactContext: ReactApplicationContext) :
terminal.disconnectReader(NoOpCallback(promise))
}

@ReactMethod
@Suppress("unused")
fun rebootReader(promise: Promise) {
paymentIntents.clear()
terminal.rebootReader(NoOpCallback(promise))
}

@ReactMethod
@Suppress("unused")
fun cancelReaderReconnection(promise: Promise) {
Expand Down
6 changes: 4 additions & 2 deletions dev-app/src/components/ListItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ type Props = {
onPress?(): void;
color?: string;
testID?: string;
visible?: boolean;
};

export default function ListItem({
Expand All @@ -26,8 +27,9 @@ export default function ListItem({
onPress,
testID,
disabled,
visible = true,
}: Props) {
return (
return visible ? (
<TouchableOpacity
testID={testID}
activeOpacity={onPress ? 0.5 : 1}
Expand All @@ -50,7 +52,7 @@ export default function ListItem({
</View>
{rightElement && rightElement}
</TouchableOpacity>
);
) : null;
}

const styles = StyleSheet.create({
Expand Down
98 changes: 58 additions & 40 deletions dev-app/src/screens/HomeScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,48 +31,53 @@ export default function HomeScreen() {
const [online, setOnline] = useState<boolean>(true);
const [discoveryMethod, setDiscoveryMethod] =
useState<Reader.DiscoveryMethod>('bluetoothScan');
const { disconnectReader, connectedReader } = useStripeTerminal({
onDidChangeOfflineStatus(status: OfflineStatus) {
console.log(status);
setOnline(status.sdk.networkStatus === 'online' ? true : false);
},
onDidForwardingFailure(error) {
console.log('onDidForwardingFailure ' + error?.message);
let toast = Toast.show(error?.message ? error.message : 'unknown error', {
duration: Toast.durations.LONG,
position: Toast.positions.BOTTOM,
shadow: true,
animation: true,
hideOnPress: true,
delay: 0,
});
const { disconnectReader, connectedReader, rebootReader } = useStripeTerminal(
{
onDidChangeOfflineStatus(status: OfflineStatus) {
console.log(status);
setOnline(status.sdk.networkStatus === 'online' ? true : false);
},
onDidForwardingFailure(error) {
console.log('onDidForwardingFailure ' + error?.message);
let toast = Toast.show(
error?.message ? error.message : 'unknown error',
{
duration: Toast.durations.LONG,
position: Toast.positions.BOTTOM,
shadow: true,
animation: true,
hideOnPress: true,
delay: 0,
}
);

setTimeout(function () {
Toast.hide(toast);
}, 3000);
},
onDidForwardPaymentIntent(paymentIntent, error) {
let toastMsg =
'Payment Intent ' +
paymentIntent.id +
' forwarded. ErrorCode' +
error?.code +
'. ErrorMsg = ' +
error?.message;
let toast = Toast.show(toastMsg, {
duration: Toast.durations.LONG,
position: Toast.positions.BOTTOM,
shadow: true,
animation: true,
hideOnPress: true,
delay: 0,
});
setTimeout(function () {
Toast.hide(toast);
}, 3000);
},
onDidForwardPaymentIntent(paymentIntent, error) {
let toastMsg =
'Payment Intent ' +
paymentIntent.id +
' forwarded. ErrorCode' +
error?.code +
'. ErrorMsg = ' +
error?.message;
let toast = Toast.show(toastMsg, {
duration: Toast.durations.LONG,
position: Toast.positions.BOTTOM,
shadow: true,
animation: true,
hideOnPress: true,
delay: 0,
});

setTimeout(function () {
Toast.hide(toast);
}, 3000);
},
});
setTimeout(function () {
Toast.hide(toast);
}, 3000);
},
}
);
const batteryPercentage =
(connectedReader?.batteryLevel ? connectedReader?.batteryLevel : 0) * 100;
const batteryStatus = batteryPercentage
Expand Down Expand Up @@ -106,6 +111,19 @@ export default function HomeScreen() {
await disconnectReader();
}}
/>
<ListItem
title="Reboot Reader"
testID="reboot-reader-button"
color={colors.blue}
onPress={async () => {
await rebootReader();
}}
visible={
discoveryMethod === 'bluetoothScan' ||
discoveryMethod === 'bluetoothProximity' ||
discoveryMethod === 'usb'
}
/>
</List>

<List title="COMMON WORKFLOWS">
Expand Down
5 changes: 5 additions & 0 deletions ios/StripeTerminalReactNative.m
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,11 @@ @interface RCT_EXTERN_MODULE(StripeTerminalReactNative, RCTEventEmitter)
rejecter: (RCTPromiseRejectBlock)reject
)

RCT_EXTERN_METHOD(
rebootReader:(RCTPromiseResolveBlock)resolve
rejecter: (RCTPromiseRejectBlock)reject
)

RCT_EXTERN_METHOD(
createPaymentIntent:(NSDictionary *)params
resolver: (RCTPromiseResolveBlock)resolve
Expand Down
12 changes: 12 additions & 0 deletions ios/StripeTerminalReactNative.swift
Original file line number Diff line number Diff line change
Expand Up @@ -347,6 +347,18 @@ class StripeTerminalReactNative: RCTEventEmitter, DiscoveryDelegate, BluetoothRe
}
}

@objc(rebootReader:rejecter:)
func rebootReader(resolver resolve: @escaping RCTPromiseResolveBlock, rejecter reject: @escaping RCTPromiseRejectBlock) {
Terminal.shared.rebootReader() { error in
if let error = error as NSError? {
resolve(Errors.createError(nsError: error))
} else {
self.paymentIntents = [:]
resolve([:])
}
}
}

func terminal(_ terminal: Terminal, didReportUnexpectedReaderDisconnect reader: Reader) {
let error = Errors.createError(code: ErrorCode.unexpectedSdkError, message: "Reader has been disconnected unexpectedly")
sendEvent(withName: ReactNativeConstants.REPORT_UNEXPECTED_READER_DISCONNECT.rawValue, body: error)
Expand Down
3 changes: 3 additions & 0 deletions src/StripeTerminalSdk.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import type {
CancelDiscoveringResultType,
ConnectBluetoothReaderParams,
DisconnectReaderResultType,
RebootReaderResultType,
Reader,
ConnectInternetReaderParams,
ConnectUsbReaderParams,
Expand Down Expand Up @@ -72,6 +73,8 @@ export interface StripeTerminalSdkType {
): Promise<ConnectReaderResultType>;
// Disconnect reader
disconnectReader(): Promise<DisconnectReaderResultType>;
// Reboot reader
rebootReader(): Promise<RebootReaderResultType>;
// Create a payment intent
createPaymentIntent(
params: CreatePaymentIntentParams
Expand Down
1 change: 1 addition & 0 deletions src/__tests__/__snapshots__/functions.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ Object {
"getOfflineStatus": [Function],
"initialize": [Function],
"installAvailableUpdate": [Function],
"rebootReader": [Function],
"retrievePaymentIntent": [Function],
"retrieveSetupIntent": [Function],
"setConnectionToken": [Function],
Expand Down
2 changes: 2 additions & 0 deletions src/__tests__/functions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ describe('functions.test.ts', () => {
setConnectionToken: jest.fn(),
simulateReaderUpdate: jest.fn(),
disconnectReader: jest.fn(),
rebootReader: jest.fn(),
clearCachedCredentials: jest.fn(),

discoverReaders: jest.fn().mockImplementation(() => ({})),
Expand Down Expand Up @@ -389,6 +390,7 @@ describe('functions.test.ts', () => {
disconnectReader: jest
.fn()
.mockImplementation(() => ({ error: '_error' })),
rebootReader: jest.fn().mockImplementation(() => ({ error: '_error' })),
connectInternetReader: jest
.fn()
.mockImplementation(() => ({ error: '_error' })),
Expand Down
17 changes: 17 additions & 0 deletions src/functions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import type {
ConnectBluetoothReaderParams,
CancelDiscoveringResultType,
DisconnectReaderResultType,
RebootReaderResultType,
ConnectInternetReaderParams,
ConnectUsbReaderParams,
CreatePaymentIntentParams,
Expand Down Expand Up @@ -255,6 +256,22 @@ export async function disconnectReader(): Promise<DisconnectReaderResultType> {
}, 'disconnectReader')();
}

export async function rebootReader(): Promise<RebootReaderResultType> {
return Logger.traceSdkMethod(async () => {
try {
const { error } = await StripeTerminalSdk.rebootReader();

return {
error: error,
};
} catch (error) {
return {
error: error as any,
};
}
}, 'rebootReader')();
}

export async function createPaymentIntent(
params: CreatePaymentIntentParams
): Promise<PaymentIntentResultType> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ Object {
"installAvailableUpdate": [Function],
"isInitialized": false,
"loading": false,
"rebootReader": [Function],
"retrievePaymentIntent": [Function],
"retrieveSetupIntent": [Function],
"setReaderDisplay": [Function],
Expand Down
8 changes: 7 additions & 1 deletion src/hooks/__tests__/useStripeTerminal.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,9 @@ function spyAllFunctions({ returnWith = null }: { returnWith?: any } = {}) {
.spyOn(functions, 'disconnectReader')
.mockImplementation(disconnectReader);
//

const rebootReader = jest.fn(() => returnWith);
jest.spyOn(functions, 'rebootReader').mockImplementation(rebootReader);
//
const installAvailableUpdate = jest.fn(() => returnWith);
jest
.spyOn(functions, 'installAvailableUpdate')
Expand Down Expand Up @@ -173,6 +175,7 @@ function spyAllFunctions({ returnWith = null }: { returnWith?: any } = {}) {
cancelDiscovering,
connectBluetoothReader,
disconnectReader,
rebootReader,
connectInternetReader,
connectUsbReader,
createPaymentIntent,
Expand Down Expand Up @@ -320,6 +323,7 @@ describe('useStripeTerminal.test.tsx', () => {
result.current.createPaymentIntent({} as any);
result.current.createSetupIntent({} as any);
result.current.disconnectReader();
result.current.rebootReader();
result.current.retrievePaymentIntent('');
result.current.getLocations({} as any);
result.current.confirmPaymentIntent({} as any);
Expand Down Expand Up @@ -371,6 +375,7 @@ describe('useStripeTerminal.test.tsx', () => {
await result.current.createPaymentIntent({} as any);
await result.current.createSetupIntent({} as any);
await result.current.disconnectReader();
await result.current.rebootReader();
await result.current.retrievePaymentIntent('');
await result.current.getLocations({} as any);
await result.current.confirmPaymentIntent({} as any);
Expand Down Expand Up @@ -467,6 +472,7 @@ describe('useStripeTerminal.test.tsx', () => {
await expect(result.current.disconnectReader()).resolves.toEqual(
'_value'
);
await expect(result.current.rebootReader()).resolves.toEqual('_value');
await expect(
result.current.retrievePaymentIntent({} as any)
).resolves.toEqual('_value');
Expand Down
21 changes: 21 additions & 0 deletions src/hooks/useStripeTerminal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import {
cancelDiscovering,
connectBluetoothReader,
disconnectReader,
rebootReader,
connectInternetReader,
connectUsbReader,
createPaymentIntent,
Expand Down Expand Up @@ -474,6 +475,25 @@ export function useStripeTerminal(props?: Props) {
return response;
}, [setLoading, setConnectedReader, setDiscoveredReaders, _isInitialized]);

const _rebootReader = useCallback(async () => {
if (!_isInitialized()) {
console.error(NOT_INITIALIZED_ERROR_MESSAGE);
return;
}
setLoading(true);

const response = await rebootReader();

if (!response.error) {
setConnectedReader(null);
setDiscoveredReaders([]);
}
Copy link
Collaborator

Choose a reason for hiding this comment

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

I don't think we want to clear the connected reader. If the user enabled auto-reconnect the SDK will start attempting to reconnect when the rebooted reader disconnects. That reconnect may fail but that's OK. We should rely on the existing disconnect callbacks to clear the connected reader

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

yes, I removed the codes and gave a test, it works well then. thanks!


setLoading(false);

return response;
}, [setLoading, setConnectedReader, setDiscoveredReaders, _isInitialized]);

const _createPaymentIntent = useCallback(
async (params: CreatePaymentIntentParams) => {
if (!_isInitialized()) {
Expand Down Expand Up @@ -850,6 +870,7 @@ export function useStripeTerminal(props?: Props) {
cancelDiscovering: _cancelDiscovering,
connectBluetoothReader: _connectBluetoothReader,
disconnectReader: _disconnectReader,
rebootReader: _rebootReader,
connectInternetReader: _connectInternetReader,
connectUsbReader: _connectUsbReader,
createPaymentIntent: _createPaymentIntent,
Expand Down
4 changes: 4 additions & 0 deletions src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,10 @@ export type DisconnectReaderResultType = {
error: StripeError;
};

export type RebootReaderResultType = {
error: StripeError;
};

export type UpdateSoftwareResultType = {
update?: Reader.SoftwareUpdate;
error?: StripeError;
Expand Down