React Native

To use our SDK with React Native, you only need to check the nativeEvent field from the WebViewMessageEvent, which contains data about the specific event. See the example below::

import { useEffect, useRef, useState } from 'react'
import { SafeAreaProvider, SafeAreaView } from 'react-native-safe-area-context'
import { WebView, WebViewMessageEvent } from 'react-native-webview'

const sdkMobileServer = 'https://sdk-mobile.cert.zerohash.com/'
const zeroHashAppsURL = 'https://web-sdk.cert.zerohash.com'

const App = () => {
  const webViewRef = useRef<WebView>(null)
  const [token, setToken] = useState<string>('<JWT_TOKEN_HERE>')

  useEffect(() => {
    fetchJwt()
  }, [])

  // Fetch JWT token from server
  const fetchJwt = async () => {
    const jwtPayload = {
      participant_code: '{PARTICIPANT_CODE}',
      permissions: [
        'crypto-buy',
        'crypto-sell',
        'crypto-withdrawals',
        'fiat-deposits',
        'fiat-withdrawals',
      ],
    }
    try {
      const response = await fetch(`<API_URL_TO_FETCH_TOKEN>`, {
        method: 'POST',
        body: JSON.stringify(jwtPayload),
      })
      const parsedResponse = await response.json()
      setToken(parsedResponse.message.token)
    } catch (e) {
      console.error('could not fetch jwt')
    }
  }

  // Open modal using injected JS script in webview
  const openModal = () => {
    webViewRef.current?.injectJavaScript(
      `window.postMessage({ "type": "OPEN_MODAL", "payload": { "appIdentifier": "crypto-buy"}});true;`,
    )
  }

  const handleMessage = (event: WebViewMessageEvent) => {
    try {
      // Parse message from webview event data checking nativeEvent field
      const parsedMessage = JSON.parse(event.nativeEvent.data)
      console.log('Received message:', parsedMessage)
      if (parsedMessage.type === 'SDK_MOBILE_READY') {
        console.log('SDK is ready, opening modal...')
        openModal()
      }
      // Handle webview events
      // Your code here...
    } catch (e) {
      alert(
        `could not parse message: ${JSON.stringify(event.nativeEvent.data)}`,
      )
    }
  }

  return (
    <SafeAreaProvider>
      <SafeAreaView>
        <WebView
          ref={webViewRef}
          onMessage={handleMessage}
          source={{
            uri: `${sdkMobileServer}?achDepositsJWT=${token}&cryptoBuyJWT=${token}&cryptoSellJWT=${token}&cryptoWithdrawalsJWT=${token}&fiatWithdrawalsJWT=${token}&userOnboardingJWT=${token}&zeroHashAppsURL=${zeroHashAppsURL}`,
          }}
        />
      </SafeAreaView>
    </SafeAreaProvider>
  )
}

export default App