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

ERROR First initialize the Stripe Terminal SDK before performing any action #659

Open
abhijitCN opened this issue Apr 5, 2024 · 9 comments

Comments

@abhijitCN
Copy link

abhijitCN commented Apr 5, 2024

### In my Root(index.js) I initialized and API call for token and in App.js useEffect call the const { initialize } = useStripeTerminal() as per the documentation but still I get ERROR First initialize the Stripe Terminal SDK before performing any action PLEASE HELP.

  1. In my indej.js

import {
StripeTerminalProvider
} from '@stripe/stripe-terminal-react-native';
import { AppRegistry } from 'react-native';
import { name as appName } from './app.json';
import App from './src/App';

const ReduxAppWrapper = () => {
const fetchTokenProvider = async () => {
try {
const response = await fetch(
FetchTokenApi/stripe/tokens,
{
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
},
);
const {secret} = await response.json();
console.log('fetch Token Provider secret KEY >> ', secret);
return secret;
} catch (error) {
console.log('fetch Token Provider eror >> ', error);
}
};

return (



);
};
AppRegistry.registerComponent(appName, () => ReduxAppWrapper);

  1. In my App.js

function App() {
const { initialize } = useStripeTerminal();

useEffect(() => {
console.log('USE EFFECT >>initialized stripe-terminal in ROOT > ');
initialize({
logLevel: 'verbose',
});
}, [initialize]);

return (
<>


</>
);
}
export default App;

** @kevinlam92 @mihaildu @TheRusskiy @SudoPlz & ANYONE face this issue**

@nazli-stripe
Copy link
Collaborator

@abhijitCN are you still running into this issue? initialize method returns a Promise and you'll need to wait for its completion before calling other methods.

@MoinJanjua
Copy link

Hi ; I also have the same issue I am trying to implement card reader sdk ReactNative

"First initialize the Stripe Terminal SDK before performing any action"

SDK version "@stripe/stripe-terminal-react-native": "^0.0.1-beta.19",

@GabrielDuarteJr
Copy link

GabrielDuarteJr commented Jul 15, 2024

I have the same issue, I initialize the SDK and after I call the discoverReaders and I have the error, this is my code:

const { error, reader } = await initialize();
...
const { error: discoverReadersError } = await discoverReaders({ discoveryMethod: 'bluetoothScan', simulated: true, });

when the promise of initialize is finished the SDK shouldn't it be ready?

@abhijitCN
Copy link
Author

I have the same issue, I initialize the SDK and after I call the discoverReaders and I have the error, this is my code:

const { error, reader } = await initialize(); ... const { error: discoverReadersError } = await discoverReaders({ discoveryMethod: 'bluetoothScan', simulated: true, });

when the promise of initialize is finished the SDK shouldn't it be ready?

@GabrielDuarteJr hello, have you got any solution for it!!

@w4nd3r1ingY4k
Copy link

hi, I'm also having this issue!

My root is wrapped in a stripe terminal provider (splash screen) then the home page initialises and the payment page scans for readers, but I am getting that error when my useEffect to scan for readers kicks in. Any coms / help would be appreciated, thanks

@abhijitCN
Copy link
Author

I have the same issue, I initialize the SDK and after I call the discoverReaders and I have the error, this is my code:

const { error, reader } = await initialize(); ... const { error: discoverReadersError } = await discoverReaders({ discoveryMethod: 'bluetoothScan', simulated: true, });

when the promise of initialize is finished the SDK shouldn't it be ready?

@GabrielDuarteJr is this asynchronous functionality works perfectly and is the error resolved?

@MoinJanjua
Copy link

Hi Guyz i was also facing the same issue and i tried differently and its work fine
here is the resolve code structure
after doing by this way it is working

`export default function CartReaders({ navigation }) {
const [readers, setReaders] = useState([]);
const [connectedReader, setConnectedReader] = useState(null);
const [simulated, setSimulated] = useState(true);
const [online, setOnline] = useState(false);
const [discoveryMethod, setDiscoveryMethod] = useState('bluetoothScan');

const fetchConnectionToken = async () => {
try {
const response = await fetch('your Connection Token API with backend url', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': your bearer token,
},
});
const data = await response.json();
if (data.error) throw new Error(data.error.message);
return data.secret;
} catch (error) {
Alert.alert('Error fetching connection token:', error.message);
throw new Error('Failed to fetch connection token');
}
};

const { initialize, disconnectReader, terminal } = useStripeTerminal({
fetchConnectionToken,
onDidChangeOfflineStatus(status) {
setOnline(status.sdk.networkStatus === 'online');
},
});

const handleDisconnect = async () => {
try {
await disconnectReader();
AsyncStorage.saveValueToStorage("ReaderConnected",'false')
Alert.alert(
'Disconnected',
'The reader has been successfully disconnected.',
[
{
text: 'OK',
onPress: () => navigation.goBack(), // Navigate back when OK is pressed
},
]
);
} catch (error) {
Alert.alert(
'Error',
'Failed to disconnect the reader. Please try again.',
[
{
text: 'OK',
onPress: () => navigation.goBack(), // Navigate back on error as well
},
]
);
}
};

useEffect(() => {
const initializeTerminal = async () => {
const { error, reader } = await initialize();
if (error) {
Alert.alert('Initialization Error:', error.message);
return;
}
setConnectedReader(reader);
};
initializeTerminal();

const handleDiscoveredReaders = (updatedReaders) => setReaders(updatedReaders);
terminal?.on('didUpdateDiscoveredReaders', handleDiscoveredReaders);
return () => terminal?.off('didUpdateDiscoveredReaders', handleDiscoveredReaders);

}, [initialize, terminal]);

useEffect(() => {

}, [connectedReader]);

const renderConnectedContent = connectedReader ? (
<>
{connectedReader.deviceType}
<View style={{ backgroundColor: 'white', borderBottomWidth: 1, borderColor: Colours.BACKGROUND_LIGHT_GRAY }}>

  <Text style={styles.label}>
   Status
  </Text>
  <Text style={styles.value}>
    Connected{simulated && <Text>, simulated</Text>}
  </Text>
</View>

<View style={{ backgroundColor: 'white', borderBottomWidth: 2, borderColor: Colours.BACKGROUND_LIGHT_GRAY }}>
<Text style={styles.label}>Battery Level:</Text>
<Text style={styles.value}>{connectedReader.batteryLevel ? (connectedReader.batteryLevel * 100).toFixed(0) + '%' : 'N/A'}</Text>
</View>

<View style={{ backgroundColor: 'white', borderBottomWidth: 2, borderColor: Colours.BACKGROUND_LIGHT_GRAY }}>
<Text style={styles.label}>Device Software Version:</Text>
<Text style={styles.value}>{connectedReader.deviceSoftwareVersion || 'N/A'}</Text>
</View>

<View style={{ backgroundColor: 'white', borderBottomWidth: 2, borderColor: Colours.BACKGROUND_LIGHT_GRAY }}>
<Text style={styles.label}>Device Type:</Text>
<Text style={styles.value}>{connectedReader.deviceType || 'N/A'}</Text>
</View>

<View style={{ backgroundColor: 'white', borderBottomWidth: 2, borderColor: Colours.BACKGROUND_LIGHT_GRAY }}>
<Text style={styles.label}>Location Display Name:</Text>
<Text style={styles.value}>{connectedReader.location?.displayName || 'N/A'}</Text>
</View>
<TouchableOpacity style={{ backgroundColor: 'gray', borderBottomWidth: 1, borderColor: Colours.BACKGROUND_LIGHT_GRAY }} onPress={() => navigation.navigate('CollectCardPaymentScreen', {
          simulated,
          discoveryMethod,
        })}>
          <Text style={styles.listItem}>Collect Payment</Text>
        </TouchableOpacity>

<TouchableOpacity onPress={handleDisconnect} style={styles.button}>
  <Text style={styles.buttonText}>Disconnect Reader</Text>
</TouchableOpacity>
</>

) : (
No reader connected
);

return (
<>

<TouchableOpacity onPress={() => { navigation.goBack(); }}>


Terminal
<View style={[styles.indicator, { backgroundColor: online ? 'green' : 'red' }]} />





{connectedReader ? (
<>

        {renderConnectedContent}
      </>
    ) : (
      <>
        <Text style={styles.ItemsTitle}>Readers</Text>
        <TouchableOpacity style={{ backgroundColor: 'white', borderBottomWidth: 1, borderColor: Colours.BACKGROUND_LIGHT_GRAY }} onPress={() => navigation.navigate('DiscoverReadersScreen', { simulated, discoveryMethod })}>
          <Text style={styles.listItem}>Discover Readers</Text>
        </TouchableOpacity>

        <TouchableOpacity style={{ backgroundColor: 'white', borderBottomWidth: 1, borderColor: Colours.BACKGROUND_LIGHT_GRAY }} onPress={() => navigation.navigate('RegisterInternetReader')}>
          <Text style={styles.listItem}>Register Internet Reader</Text>
        </TouchableOpacity>

        <Text style={styles.MethodTitle}>Discovery Method</Text>
        <TouchableOpacity style={{ backgroundColor: 'white', borderBottomWidth: 1, borderColor: Colours.BACKGROUND_LIGHT_GRAY }}
          onPress={() => navigation.navigate('DiscoveryMethodScreen', {
            onChange: async (value) => {
              setDiscoveryMethod(value);
              setSimulated(simulated);
            },
          })}
        >
          <Text style={styles.listItem}>{mapFromDiscoveryMethod(discoveryMethod)}</Text>
        </TouchableOpacity>
        <View style={styles.switchContainer}>
          <Text style={styles.listItem}>Simulated</Text>
          <Switch style={{ marginRight: 16, alignSelf: 'center' }} value={simulated} onValueChange={(value) => setSimulated(value)} />
        </View>
        <Text style={styles.infoText}>
          The SDK comes with the ability to simulate behavior without using physical hardware. This makes it easy to
          quickly test your integration end-to-end, from connecting a reader to taking payments.
        </Text>
      </>
    )}
  </ScrollView>
</>

);
}`

@abhijitCN
Copy link
Author

@MoinJanjua thank you so much, it's helpful for me thanks.

@nazli-stripe
Copy link
Collaborator

@abhijitCN are you still running into this issue?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants