trustly-react-native-webview
Version:
Trustly ReactNative WebView needed when integrating Trustly Checkout in a ReactNative application.
61 lines (54 loc) • 1.65 kB
JavaScript
import React from 'react';
import { Linking } from 'react-native';
import { WebView } from 'react-native-webview';
import {
NativeEventTypes,
trustlyApplicationName,
trustlyCustomBridge,
} from './common';
const onMessage = ({ data, onSuccess, onError }) => {
try {
const { type, url, eventType } = JSON.parse(data);
const isCheckoutEvent = eventType === 'checkout-event';
if (isCheckoutEvent) {
if (type === NativeEventTypes.REDIRECT) {
try {
Linking.openURL(url);
} catch (e) {
console.log(`There was an error opening URL: ${url}. Error: ${e}`);
onError?.();
}
}
if (type === NativeEventTypes.ABORT || type === NativeEventTypes.ERROR) {
onError?.();
}
if (type === NativeEventTypes.SUCCESS) {
onSuccess?.();
}
}
} catch (e) {
const error = typeof e === 'object' ? JSON.stringify(e) : e;
console.error(
`Something unexpected happen when trying to map Trustly Checkout events. Error: ${error}`,
);
}
};
export const TrustlyWebView = ({ uri, onSuccess, onError }) => {
return (
<WebView
source={{ uri }}
injectedJavaScriptForMainFrameOnly={false}
injectedJavaScript={trustlyCustomBridge}
applicationNameForUserAgent={trustlyApplicationName}
onMessage={({ nativeEvent }) => {
try {
onMessage({ data: nativeEvent.data, onSuccess, onError });
} catch (e) {
console.error(
`Format of nativeEvent.data does not match Trustly API. Data sent: ${nativeEvent.data}`,
);
}
}}
/>
);
};