diff --git a/package.json b/package.json index 2d0ff4ac5b..87eb6f075e 100644 --- a/package.json +++ b/package.json @@ -88,6 +88,7 @@ "@sumsub/fisherman": "2.1.0", "@sumsub/react-native-mobilesdk-module": "1.45.1", "@tradle/react-native-http": "2.0.1", + "@transak/ui-components-rn": "0.6.0", "@walletconnect/jsonrpc-types": "1.0.4", "@walletconnect/react-native-compat": "2.21.8", "asyncstorage-down": "4.2.0", diff --git a/src/navigation/services/ExternalServicesGroup.tsx b/src/navigation/services/ExternalServicesGroup.tsx index f949ba6ebd..31c851eaff 100644 --- a/src/navigation/services/ExternalServicesGroup.tsx +++ b/src/navigation/services/ExternalServicesGroup.tsx @@ -30,6 +30,12 @@ import MoonpayBuyEmbeddedCheckout, { import MoonpayBuyEmbeddedOnboarding, { MoonpayBuyEmbeddedOnboardingProps, } from './screens/MoonpayBuyEmbeddedOnboarding'; +import TransakBuyHeadlessCheckout, { + TransakBuyHeadlessCheckoutProps, +} from './screens/TransakBuyHeadlessCheckout'; +import TransakBuyHeadlessOnboarding, { + TransakBuyHeadlessOnboardingProps, +} from './screens/TransakBuyHeadlessOnboarding'; interface ExternalServicesProps { ExternalServices: typeof Root; @@ -43,6 +49,8 @@ export type ExternalServicesGroupParamList = { MoonpaySellCheckout: MoonpaySellCheckoutProps; RampSellCheckout: RampSellCheckoutProps; SimplexSellCheckout: SimplexSellCheckoutProps; + TransakBuyHeadlessCheckout: TransakBuyHeadlessCheckoutProps; + TransakBuyHeadlessOnboarding: TransakBuyHeadlessOnboardingProps; }; export enum ExternalServicesScreens { @@ -52,6 +60,8 @@ export enum ExternalServicesScreens { MOONPAY_SELL_CHECKOUT = 'MoonpaySellCheckout', RAMP_SELL_CHECKOUT = 'RampSellCheckout', SIMPLEX_SELL_CHECKOUT = 'SimplexSellCheckout', + TRANSAK_BUY_HEADLESS_CHECKOUT = 'TransakBuyHeadlessCheckout', + TRANSAK_BUY_HEADLESS_ONBOARDING = 'TransakBuyHeadlessOnboarding', } const AccountHeader = ({ @@ -124,6 +134,20 @@ const ExternalServicesGroup = ({ headerTitle: '', }} /> + {t('Confirm Buy')}, + }} + /> + { return __DEV__ ? PASSTHROUGH_URI_DEV : PASSTHROUGH_URI_PROD; }; +// Transak headless + +export const transakHeadlessEnvironment: 'STAGING' | 'PRODUCTION' = + transakEnv === 'production' ? 'PRODUCTION' : 'STAGING'; + +// Opt-in: headless only works once Transak has enabled it for our API key and +// whitelisted the BWS IPs, so it stays off until the config turns it on. +export const isTransakHeadlessPaymentMethodEnabled = ( + method: PaymentMethodKey | undefined, + buyCryptoConfig: BuyCryptoConfig | undefined, + country: string | undefined, +): boolean => { + if (buyCryptoConfig?.transak?.config?.headlessBuyEnabled !== true) { + return false; + } + // UK customers must go through Transak's FCA journey, which only the widget + // implements (headless orders fail with 4016). + if (country === 'GB') { + return false; + } + return method === 'creditCard' || method === 'debitCard'; +}; + +// A session about to expire is treated as expired: Transak cannot refresh an +// expired session, and a purchase must not fail halfway because of it. +export const isTransakHeadlessUserAuthValid = ( + userAuth: TransakHeadlessUserAuthData | undefined, +): userAuth is TransakHeadlessUserAuthData => + !!userAuth?.accessToken && userAuth.expiresAt - Date.now() > 10 * 60 * 1000; + +const TRANSAK_HEADLESS_RESULT_PARAM = 'headlessResult'; + +// After 3DS Transak redirects to these. The in-app WebView intercepts them; if +// one is ever opened in a browser, the passthrough page still sends the +// customer back to the app with the partnerOrderId, as the widget flow does. +export const getTransakHeadlessRedirectUrls = ( + transakExternalId: string, +): {successUrl: string; failureUrl: string} => { + const buildUrl = (result: 'success' | 'failure') => + `${getPassthroughUri()}?${new URLSearchParams({ + partnerOrderId: transakExternalId, + [TRANSAK_HEADLESS_RESULT_PARAM]: result, + }).toString()}`; + return {successUrl: buildUrl('success'), failureUrl: buildUrl('failure')}; +}; + +export const getTransakHeadlessRedirectResult = ( + url: string, +): 'success' | 'failure' | undefined => { + if ( + !url.startsWith(getPassthroughUri()) && + !url.startsWith('bitpay://transak') + ) { + return undefined; + } + try { + const result = new URL(url).searchParams.get(TRANSAK_HEADLESS_RESULT_PARAM); + return result === 'success' || result === 'failure' ? result : undefined; + } catch { + return undefined; + } +}; + export const getTransakCoinFormat = (coin: string): string => { coin = externalServicesCoinMapping(coin); let formattedCoin: string = `${coin.toUpperCase()}`; diff --git a/src/navigation/services/screens/BuyAndSellRoot.tsx b/src/navigation/services/screens/BuyAndSellRoot.tsx index 68c45702cd..b4e9669364 100644 --- a/src/navigation/services/screens/BuyAndSellRoot.tsx +++ b/src/navigation/services/screens/BuyAndSellRoot.tsx @@ -128,10 +128,13 @@ import { SimplexPaymentData, TransakAccessTokenData, TransakGetSignedUrlRequestData, + TransakHeadlessGetQuoteRequestData, + TransakHeadlessUserAuthData, TransakPaymentData, TransakSignedUrlData, } from '../../../store/buy-crypto/buy-crypto.models'; import {cloneDeep} from '../../../utils/object'; +import {prepareTransakHeadlessCheckout} from '../../../store/buy-crypto/effects/transak/transak-headless'; import { banxaEnv, getBanxaChainFormat, @@ -180,6 +183,8 @@ import { getTransakChainFormat, getTransakCoinFormat, getTransakPaymentMethodFormat, + isTransakHeadlessPaymentMethodEnabled, + isTransakHeadlessUserAuthValid, transakEnv, } from '../buy-crypto/utils/transak-utils'; import { @@ -699,6 +704,10 @@ const BuyAndSellRoot = ({ const accessTokenTransak: TransakAccessTokenData | undefined = useAppSelector( ({BUY_CRYPTO}) => BUY_CRYPTO.tokens?.transak?.[transakEnv], ); + const transakHeadlessUserAuth: TransakHeadlessUserAuthData | undefined = + useAppSelector( + ({BUY_CRYPTO}) => BUY_CRYPTO.tokens?.transakHeadlessUser?.[transakEnv], + ); const buyCryptoOpts: BuyCryptoStateOpts = useAppSelector( ({BUY_CRYPTO}: RootState) => BUY_CRYPTO.opts, ); @@ -3399,12 +3408,13 @@ const BuyAndSellRoot = ({ if (offer.errorMsg || offer.outOfLimitMsg) { return; } - continueToTransak(offer, paymentMethod); + continueToTransak(offer, paymentMethod, false); }; const continueToTransak = async ( offer: CryptoOffer, paymentMethod: PaymentMethod, + skipHeadless?: boolean, ) => { if (!selectedWallet) { return; @@ -3424,6 +3434,27 @@ const BuyAndSellRoot = ({ return; } + // Headless keeps the whole card payment in the app. Whenever it cannot run + // (no session and the customer skips, KYC not approved, Transak errors...) + // the purchase continues below with the standard Transak widget. + if ( + !skipHeadless && + isTransakHeadlessPaymentMethodEnabled( + paymentMethod?.method, + buyCryptoConfig, + locationData?.countryShortCode, + ) + ) { + const startedHeadless = await continueToTransakHeadless( + offer, + paymentMethod, + address, + ); + if (startedHeadless) { + return; + } + } + const destinationChain = selectedWallet.chain; const transakExternalId = uuid.v4().toString(); const coin = selectedWallet.currencyAbbreviation.toLowerCase(); @@ -3582,6 +3613,183 @@ const BuyAndSellRoot = ({ navigation.goBack(); }; + // Returns whether the headless flow took over the purchase: either its + // onboarding or its checkout is on screen. If not, the caller goes on with + // the Transak widget. + const continueToTransakHeadless = async ( + offer: CryptoOffer, + paymentMethod: PaymentMethod, + address: string, + ): Promise => { + if (!selectedWallet) { + return false; + } + const wallet = selectedWallet; + const transakExternalId = uuid.v4().toString(); + const quoteRequestData: TransakHeadlessGetQuoteRequestData = { + env: transakEnv, + fiatCurrency: offer.fiatCurrency.toUpperCase(), + cryptoCurrency: getTransakCoinFormat( + wallet.currencyAbbreviation.toLowerCase(), + ), + network: getTransakChainFormat(wallet.chain) ?? 'mainnet', + paymentMethod: 'credit_debit_card', + fiatAmount: offer.fiatAmount, + partnerCustomerId: wallet.id, + partnerOrderId: transakExternalId, + }; + + const startCheckout = async ( + userAuth: TransakHeadlessUserAuthData, + ): Promise<'started' | 'unauthorized' | 'unavailable'> => { + const preparation = await prepareTransakHeadlessCheckout( + wallet, + quoteRequestData, + userAuth.accessToken, + ); + if (preparation.status !== 'ready') { + logger.debug( + `[TransakHeadlessBuy] cannot run headless: ${ + preparation.status === 'unavailable' + ? preparation.reason + : 'session rejected' + }`, + ); + if (preparation.status === 'unauthorized') { + dispatch( + BuyCryptoActions.updateHeadlessUserAuthTransak({ + env: transakEnv, + userAuth: undefined, + }), + ); + } + return preparation.status; + } + + dispatch( + Analytics.track('Requested Crypto Purchase', { + exchange: 'transak', + fiatAmount: offer.fiatAmount, + fiatCurrency: offer.fiatCurrency, + paymentMethod: paymentMethod.method, + coin: wallet.currencyAbbreviation.toLowerCase(), + chain: wallet.chain?.toLowerCase(), + isHeadless: true, + }), + ); + + const checkoutParams = { + wallet, + toAddress: address, + offer, + paymentMethod, + userAuth, + transakExternalId, + quoteRequestData, + preparation, + onFallback: (reason: string) => { + logger.debug( + `[TransakHeadlessBuy] checkout fallback (${reason}), continuing with the Transak widget.`, + ); + fallbackToTransakWidget(offer, paymentMethod); + }, + }; + + // Replace the onboarding (if any) so going back from the checkout + // returns to the offers. + navigation.dispatch(state => { + const routes = state.routes.filter( + r => + r.name !== ExternalServicesScreens.TRANSAK_BUY_HEADLESS_ONBOARDING, + ); + if (routes.length === state.routes.length) { + return CommonActions.navigate({ + name: ExternalServicesScreens.TRANSAK_BUY_HEADLESS_CHECKOUT, + params: checkoutParams, + }); + } + const newRoutes = [ + ...routes, + { + name: ExternalServicesScreens.TRANSAK_BUY_HEADLESS_CHECKOUT, + params: checkoutParams, + }, + ]; + return CommonActions.reset({ + ...state, + routes: newRoutes, + index: newRoutes.length - 1, + }); + }); + setOpeningBrowser(false); + return 'started'; + }; + + if (isTransakHeadlessUserAuthValid(transakHeadlessUserAuth)) { + const result = await startCheckout(transakHeadlessUserAuth); + if (result !== 'unauthorized') { + return result === 'started'; + } + // The stored session is no longer accepted: sign in again below. + } + + navigation.navigate( + ExternalServicesScreens.TRANSAK_BUY_HEADLESS_ONBOARDING, + { + wallet, + country: locationData?.countryShortCode, + initialEmail: user?.email, + onConnect: async (userAuth: TransakHeadlessUserAuthData) => { + dispatch( + BuyCryptoActions.updateHeadlessUserAuthTransak({ + env: transakEnv, + userAuth, + }), + ); + const result = await startCheckout(userAuth); + if (result !== 'started') { + fallbackToTransakWidget(offer, paymentMethod); + } + }, + onSkip: (manualSkip: boolean) => { + logger.debug( + `[TransakHeadlessBuy] ${ + manualSkip ? 'User skipped' : 'Skipped' + } the Transak sign in, continuing with the Transak widget.`, + ); + fallbackToTransakWidget(offer, paymentMethod); + }, + }, + ); + setOpeningBrowser(false); + return true; + }; + + // Leaves the headless screen on top and continues with the Transak widget. + const fallbackToTransakWidget = async ( + offer: CryptoOffer, + paymentMethod: PaymentMethod, + ) => { + hasInitializedRef.current = true; + navigation.goBack(); + // Wait for the back-transition: the transitionEnd listener resets + // buttonState and openingBrowser on every transition. Race against a + // timeout in case transitionEnd never fires. + await Promise.race([ + new Promise(resolve => { + const unsubscribe = navigation.addListener('transitionEnd', () => { + unsubscribe(); + resolve(); + }); + }), + new Promise(resolve => setTimeout(resolve, 2500)), + ]); + setButtonState('loading'); + setOpeningBrowser(true); + await sleep(1000); + continueToTransak(offer, paymentMethod, true); + }; + const goToSellCheckout = ( offer: SellCryptoOffer, paymentMethod: WithdrawalMethod, diff --git a/src/navigation/services/screens/TransakBuyHeadlessCheckout.tsx b/src/navigation/services/screens/TransakBuyHeadlessCheckout.tsx new file mode 100644 index 0000000000..96b69d0b1f --- /dev/null +++ b/src/navigation/services/screens/TransakBuyHeadlessCheckout.tsx @@ -0,0 +1,976 @@ +import React, {useEffect, useRef, useState} from 'react'; +import { + ActivityIndicator, + SafeAreaView, + ScrollView, + StyleSheet, + Text, + View, + ViewProps, +} from 'react-native'; +import Modal from 'react-native-modal'; +import WebView from 'react-native-webview'; +import { + CommonActions, + RouteProp, + useNavigation, + useRoute, +} from '@react-navigation/native'; +import {useTranslation} from 'react-i18next'; +import {useSafeAreaInsets} from 'react-native-safe-area-context'; +import cloneDeep from 'lodash.clonedeep'; +import {TransakCard, TransakCardRef} from '@transak/ui-components-rn'; +import {useTheme, usePaymentSent} from '../../../contexts'; +import {useAppDispatch, useLogger} from '../../../utils/hooks'; +import { + Black, + Caution, + Slate30, + SlateDark, + White, +} from '../../../styles/colors'; +import {BaseText} from '../../../components/styled/Text'; +import {CurrencyImage} from '../../../components/currency-image/CurrencyImage'; +import Checkbox from '../../../components/checkbox/Checkbox'; +import Button, {ButtonState} from '../../../components/button/Button'; +import {TouchableOpacity} from '../../../components/base/TouchableOpacity'; +import {HEIGHT, WIDTH} from '../../../components/styled/Containers'; +import TransakLogo from '../../../components/icons/external-services/transak/transak-logo'; +import { + formatFiatAmount, + getBadgeImg, + getCurrencyAbbreviation, + getErrorString, + sleep, +} from '../../../utils/helper-methods'; +import { + ItemDivisor, + SelectedOptionCol, + SelectedOptionContainer, + SelectedOptionText, +} from '../swap-crypto/styled/SwapCryptoCheckout.styled'; +import { + dismissBottomNotificationModal, + showBottomNotificationModal, +} from '../../../store/app/app.actions'; +import {Analytics} from '../../../store/analytics/analytics.effects'; +import {BuyCryptoActions} from '../../../store/buy-crypto'; +import {Wallet} from '../../../store/wallet/wallet.models'; +import { + TransakHeadlessGetQuoteRequestData, + TransakHeadlessOrderData, + TransakHeadlessQuoteData, + TransakHeadlessSavedCard, + TransakHeadlessUserAuthData, + TransakPaymentData, + TransakStatusKey, +} from '../../../store/buy-crypto/buy-crypto.models'; +import { + isTransakHeadlessUnauthorized, + TransakHeadlessError, + transakHeadlessCreateCardSession, + transakHeadlessCreateOrder, + transakHeadlessGetOrderDetails, + transakHeadlessGetQuote, + TransakHeadlessPreparation, +} from '../../../store/buy-crypto/effects/transak/transak-headless'; +import { + getTransakHeadlessRedirectResult, + getTransakHeadlessRedirectUrls, + transakEnv, + transakHeadlessEnvironment, +} from '../buy-crypto/utils/transak-utils'; +import {PaymentMethod} from '../buy-crypto/constants/BuyCryptoConstants'; +import {CryptoOffer} from '../components/externalServicesOfferSelector'; +import {TransakSettingsProps} from '../../tabs/settings/external-services/screens/TransakSettings'; +import {ExternalServicesSettingsScreens} from '../../tabs/settings/external-services/ExternalServicesGroup'; +import {RootStacks} from '../../../Root'; +import {TabsScreens} from '../../tabs/TabsStack'; +import {APP_DEEPLINK_PREFIX} from '../../../constants/config'; + +// Transak refreshes quotes every minute; anything older is re-fetched before +// it is used to create a card session or a saved-card order. +const QUOTE_MAX_AGE_MS = 30 * 1000; +// Same as the SDK's own iframe timeout on web, which the RN component lacks. +const CARD_FORM_LOAD_TIMEOUT_MS = 30 * 1000; +const CARD_FORM_HEIGHT = 340; +// The order may come back without the 3DS URL yet. +const ORDER_POLL_INTERVAL_MS = 2000; +const ORDER_POLL_ATTEMPTS = 10; + +const FINAL_FAILED_STATUSES: TransakStatusKey[] = [ + 'FAILED', + 'CANCELLED', + 'EXPIRED', + 'REFUNDED', +]; + +const styles = StyleSheet.create({ + root: {flex: 1}, + container: { + flex: 1, + margin: 14, + }, + headerContainer: { + alignItems: 'center', + marginBottom: 24, + }, + iconRow: { + flexDirection: 'row', + alignItems: 'center', + marginBottom: 20, + }, + title: { + fontSize: 39, + fontWeight: '700', + textAlign: 'center', + marginBottom: 10, + }, + subtitle: { + fontSize: 13, + lineHeight: 22, + fontWeight: '400', + textAlign: 'center', + }, + rowText: { + fontSize: 13, + }, + rowDataContainer: { + flexDirection: 'row', + alignItems: 'center', + justifyContent: 'space-between', + paddingVertical: 15, + }, + sectionLabel: { + fontSize: 13, + fontWeight: '500', + marginTop: 8, + marginBottom: 4, + }, + cardOption: { + flexDirection: 'row', + alignItems: 'center', + paddingVertical: 12, + }, + cardOptionText: { + fontSize: 14, + marginLeft: 12, + flex: 1, + }, + cardForm: { + height: CARD_FORM_HEIGHT, + marginTop: 8, + }, + cardFormLoading: { + position: 'absolute', + top: 0, + right: 0, + bottom: 0, + left: 0, + alignItems: 'center', + justifyContent: 'center', + }, + cardError: { + fontSize: 12, + color: Caution, + marginTop: 6, + }, + bottomSection: { + paddingTop: 16, + }, + poweredByContainer: { + flexDirection: 'row', + alignItems: 'center', + justifyContent: 'center', + marginTop: 12, + }, + poweredByText: { + fontSize: 11, + marginRight: 4, + }, + webViewModalContainer: { + flex: 1, + justifyContent: 'center', + }, + webViewModalHeader: { + height: 50, + justifyContent: 'center', + alignItems: 'flex-start', + paddingHorizontal: 15, + borderBottomWidth: 1, + }, + webViewCloseButton: { + padding: 10, + }, + webViewCloseText: { + fontSize: 24, + }, +}); + +const ThemedText = React.forwardRef< + Text, + React.ComponentProps & {secondary?: boolean} +>(({style, secondary, ...rest}, ref) => { + const theme = useTheme(); + const color = secondary + ? theme.dark + ? Slate30 + : SlateDark + : theme.dark + ? White + : Black; + return ; +}); +ThemedText.displayName = 'ThemedText'; + +const RowDataContainer: React.FC = ({style, ...rest}) => ( + +); + +export interface TransakBuyHeadlessCheckoutProps { + wallet: Wallet; + toAddress: string; + offer: CryptoOffer; + paymentMethod: PaymentMethod; + userAuth: TransakHeadlessUserAuthData; + transakExternalId: string; + quoteRequestData: TransakHeadlessGetQuoteRequestData; + preparation: Extract; + // Leaves this screen and continues with the Transak widget. + onFallback: (reason: string) => void; +} + +const isSavedCardExpired = (card: TransakHeadlessSavedCard): boolean => { + if (!card.expiryMonth || !card.expiryYear) { + return false; + } + const now = new Date(); + const year = card.expiryYear < 100 ? 2000 + card.expiryYear : card.expiryYear; + return ( + year < now.getFullYear() || + (year === now.getFullYear() && card.expiryMonth < now.getMonth() + 1) + ); +}; + +const getSavedCardLabel = (card: TransakHeadlessSavedCard): string => + `${card.scheme ? card.scheme.toUpperCase() : 'CARD'} •••• ${card.last4}`; + +const getOrderRedirectUrl = ( + order: TransakHeadlessOrderData | undefined, +): string | undefined => + order?.paymentDetails?.find(detail => !!detail?.redirectUrl)?.redirectUrl; + +const TransakBuyHeadlessCheckout: React.FC = () => { + const { + params: { + wallet, + toAddress, + offer, + paymentMethod, + userAuth, + transakExternalId, + quoteRequestData, + preparation, + onFallback, + }, + } = useRoute>(); + const {t} = useTranslation(); + const logger = useLogger(); + const navigation = useNavigation(); + const dispatch = useAppDispatch(); + const theme = useTheme(); + const insets = useSafeAreaInsets(); + const {showPaymentSent, hidePaymentSent} = usePaymentSent(); + + const coin = cloneDeep(wallet.currencyAbbreviation).toLowerCase(); + const usableSavedCards = preparation.savedCards.filter( + card => !isSavedCardExpired(card), + ); + const {successUrl, failureUrl} = + getTransakHeadlessRedirectUrls(transakExternalId); + + const [quote, setQuote] = useState( + preparation.quote, + ); + const quoteFetchedAtRef = useRef(preparation.quoteFetchedAt); + const [selectedCardId, setSelectedCardId] = useState( + usableSavedCards[0]?.paymentIdentifierId ?? 'new', + ); + const [cardSessionId, setCardSessionId] = useState(); + const [cardFormReady, setCardFormReady] = useState(false); + const [cardValid, setCardValid] = useState(false); + const [cardStateError, setCardStateError] = useState(); + const [buttonState, setButtonState] = useState(); + const [redirectUrl, setRedirectUrl] = useState(); + + const cardRef = useRef(null); + const creatingSessionRef = useRef(false); + const sessionRetriedRef = useRef(false); + const submittingCardRef = useRef(false); + const orderRef = useRef(undefined); + const finalizingRef = useRef(false); + const mountedRef = useRef(true); + + const isNewCard = selectedCardId === 'new'; + + useEffect(() => { + return () => { + mountedRef.current = false; + }; + }, []); + + const forgetUserSession = () => { + dispatch( + BuyCryptoActions.updateHeadlessUserAuthTransak({ + env: transakEnv, + userAuth: undefined, + }), + ); + }; + + const showError = async ({ + err, + reason, + title, + allowFallback, + }: { + err?: unknown; + reason: string; + title?: string; + allowFallback: boolean; + }) => { + const errMsg = err === undefined ? '' : getErrorString(err); + logger.error(`[TransakHeadlessCheckout] ${reason}: ${errMsg}`); + if (isTransakHeadlessUnauthorized(err)) { + forgetUserSession(); + } + setButtonState(undefined); + submittingCardRef.current = false; + + dispatch( + Analytics.track('Failed Buy Crypto', { + exchange: 'transak', + context: 'TransakBuyHeadlessCheckout', + reason: errMsg ? `[${reason}]: ${errMsg}` : reason, + paymentMethod: paymentMethod?.method || '', + amount: Number(offer.fiatAmount) || '', + coin, + chain: wallet.chain?.toLowerCase() || '', + fiatCurrency: offer.fiatCurrency || '', + isHeadless: true, + }), + ); + + await sleep(700); + if (!mountedRef.current) { + return; + } + dispatch( + showBottomNotificationModal({ + type: 'error', + title: title ?? t('Error'), + message: allowFallback + ? t( + 'We could not complete your purchase in the app. You can continue on Transak instead.', + ) + : t('Your card payment was not completed.'), + enableBackdropDismiss: false, + actions: [ + ...(allowFallback + ? [ + { + text: t('Continue on Transak'), + action: () => { + dispatch(dismissBottomNotificationModal()); + onFallback(reason); + }, + primary: true, + }, + ] + : []), + { + text: allowFallback ? t('Cancel') : t('OK'), + action: async () => { + dispatch(dismissBottomNotificationModal()); + await sleep(500); + navigation.goBack(); + }, + primary: !allowFallback, + }, + ], + }), + ); + }; + + const getFreshQuote = async (): Promise => { + if (Date.now() - quoteFetchedAtRef.current < QUOTE_MAX_AGE_MS) { + return quote; + } + const newQuote = await transakHeadlessGetQuote(wallet, quoteRequestData); + if (!newQuote?.quoteId) { + throw new Error('No quoteId returned'); + } + quoteFetchedAtRef.current = Date.now(); + if (mountedRef.current) { + setQuote(newQuote); + } + return newQuote; + }; + + const createCardSession = async () => { + if (creatingSessionRef.current) { + return; + } + creatingSessionRef.current = true; + setCardSessionId(undefined); + setCardFormReady(false); + setCardValid(false); + setCardStateError(undefined); + try { + const freshQuote = await getFreshQuote(); + const session = await transakHeadlessCreateCardSession(wallet, { + env: transakEnv, + userAccessToken: userAuth.accessToken, + quoteId: freshQuote.quoteId, + walletAddress: toAddress, + successUrl, + failureUrl, + config: {colorMode: theme.dark ? 'DARK' : 'LIGHT'}, + }); + if (!session?.sessionId) { + throw new Error('No sessionId returned'); + } + if (mountedRef.current) { + setCardSessionId(session.sessionId); + } + } catch (err) { + showError({err, reason: 'createCardSession', allowFallback: true}); + } finally { + creatingSessionRef.current = false; + } + }; + + // Only when the new card option gets selected: a failed session is not + // retried on its own, the customer is offered the widget instead. + useEffect(() => { + if (isNewCard && !cardSessionId) { + createCardSession(); + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [isNewCard]); + + useEffect(() => { + if (!cardSessionId || cardFormReady) { + return; + } + const timeout = setTimeout(() => { + showError({ + reason: 'card form load timeout', + allowFallback: true, + }); + }, CARD_FORM_LOAD_TIMEOUT_MS); + return () => clearTimeout(timeout); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [cardSessionId, cardFormReady]); + + const recordOrder = (order: TransakHeadlessOrderData) => { + const fiatTotalAmount = order.fiatAmount ?? quote.fiatAmount; + const fee = order.totalFeeInFiat ?? quote.totalFee; + const newData: TransakPaymentData = { + address: toAddress, + chain: wallet.chain, + created_on: Date.now(), + crypto_amount: order.cryptoAmount ?? quote.cryptoAmount, + coin: coin.toUpperCase(), + env: __DEV__ ? 'dev' : 'prod', + fiat_base_amount: fiatTotalAmount - fee, + fiat_total_amount: fiatTotalAmount, + fiat_total_amount_currency: offer.fiatCurrency, + external_id: transakExternalId, + status: order.status ?? 'AWAITING_PAYMENT_FROM_USER', + user_id: wallet.id, + order_id: order.orderId, + payment_method: paymentMethod?.method, + is_headless: true, + }; + dispatch( + BuyCryptoActions.successPaymentRequestTransak({ + transakPaymentData: newData, + }), + ); + }; + + const goToTransakSettings = (status?: string) => { + const transakSettingsParams: TransakSettingsProps = { + incomingPaymentRequest: { + transakExternalId, + walletId: wallet.id, + status, + }, + }; + navigation.dispatch( + CommonActions.reset({ + index: 1, + routes: [ + { + name: RootStacks.TABS, + params: {screen: TabsScreens.HOME}, + }, + { + name: ExternalServicesSettingsScreens.TRANSAK_SETTINGS, + params: transakSettingsParams, + }, + ], + }), + ); + }; + + const finalize = async ( + result: 'success' | 'failure' | 'cancelled' | 'unconfirmed', + ) => { + const order = orderRef.current; + if (finalizingRef.current || !order) { + return; + } + finalizingRef.current = true; + setRedirectUrl(undefined); + logger.debug( + `[TransakHeadlessCheckout] order ${order.orderId} finished: ${result}`, + ); + + let status = order.status; + try { + const details = await transakHeadlessGetOrderDetails(wallet, { + env: transakEnv, + userAccessToken: userAuth.accessToken, + orderId: order.orderId, + }); + status = details?.status ?? status; + } catch (err) { + logger.warn( + `[TransakHeadlessCheckout] could not refresh order ${ + order.orderId + }: ${getErrorString(err)}`, + ); + } + + dispatch( + BuyCryptoActions.updatePaymentRequestTransak({ + transakIncomingData: { + transakExternalId, + status, + order_id: order.orderId, + }, + }), + ); + + if (result === 'unconfirmed') { + goToTransakSettings(status); + return; + } + + // Closing the 3DS page after paying, but before Transak redirected, still + // leaves a paid order behind. + const paid = + !FINAL_FAILED_STATUSES.includes(status) && + (result === 'success' || + (result === 'cancelled' && status !== 'AWAITING_PAYMENT_FROM_USER')); + + if (paid) { + const cryptoAmount = order.cryptoAmount ?? quote.cryptoAmount; + const fiatTotalAmount = order.fiatAmount ?? quote.fiatAmount; + const fee = order.totalFeeInFiat ?? quote.totalFee; + dispatch( + Analytics.track('Purchased Buy Crypto', { + exchange: 'transak', + fiatAmount: fiatTotalAmount || '', + feeAmount: fee || '', + fiatCurrency: offer.fiatCurrency || '', + coin, + chain: wallet.chain?.toLowerCase() || '', + cryptoAmount: cryptoAmount || '', + paymentMethod: paymentMethod?.method || '', + exchangeRate: + (cryptoAmount && (fiatTotalAmount - fee) / cryptoAmount) || '', + isHeadless: true, + }), + ); + showPaymentSent({ + onCloseModal: () => hidePaymentSent(), + title: t('Transaction Submitted'), + }); + await sleep(1200); + goToTransakSettings(status); + return; + } + + showError({ + reason: `order ${result} (${status})`, + title: t('Payment not completed'), + allowFallback: false, + }); + }; + + const handleOrderCreated = async (order: TransakHeadlessOrderData) => { + if (!order?.orderId) { + throw new Error('No orderId returned'); + } + orderRef.current = order; + recordOrder(order); + + let url = getOrderRedirectUrl(order); + let status = order.status; + for ( + let attempt = 0; + !url && + !FINAL_FAILED_STATUSES.includes(status) && + attempt < ORDER_POLL_ATTEMPTS; + attempt++ + ) { + await sleep(ORDER_POLL_INTERVAL_MS); + if (!mountedRef.current) { + return; + } + try { + const details = await transakHeadlessGetOrderDetails(wallet, { + env: transakEnv, + userAccessToken: userAuth.accessToken, + orderId: order.orderId, + }); + orderRef.current = {...order, ...details}; + url = getOrderRedirectUrl(details); + status = details?.status ?? status; + } catch (err) { + logger.warn( + `[TransakHeadlessCheckout] order poll failed: ${getErrorString(err)}`, + ); + } + } + + if (url) { + setRedirectUrl(url); + } else { + finalize( + FINAL_FAILED_STATUSES.includes(status) ? 'failure' : 'unconfirmed', + ); + } + }; + + const payWithSavedCard = async (card: TransakHeadlessSavedCard) => { + setButtonState('loading'); + try { + const freshQuote = await getFreshQuote(); + const order = await transakHeadlessCreateOrder(wallet, { + env: transakEnv, + userAccessToken: userAuth.accessToken, + quoteId: freshQuote.quoteId, + walletAddress: toAddress, + paymentIdentifierId: card.paymentIdentifierId, + successUrl, + failureUrl, + }); + await handleOrderCreated(order); + } catch (err) { + showError({ + err, + reason: 'createOrder (saved card)', + allowFallback: !orderRef.current, + }); + } + }; + + const payWithNewCard = () => { + if (!cardFormReady || !cardValid) { + return; + } + setButtonState('loading'); + submittingCardRef.current = true; + cardRef.current?.submit(); + }; + + const onCardSuccess = async ({requestId}: {requestId: string}) => { + if (!submittingCardRef.current) { + return; + } + submittingCardRef.current = false; + try { + const order = await transakHeadlessCreateOrder(wallet, { + env: transakEnv, + userAccessToken: userAuth.accessToken, + requestId, + }); + await handleOrderCreated(order); + } catch (err) { + showError({ + err, + reason: 'createOrder (new card)', + allowFallback: !orderRef.current, + }); + } + }; + + const onCardError = ({code}: {code: string}) => { + // An expired or invalid session: one new session is worth a try before + // giving up, since the customer has not paid anything yet. + if (code === 'CONFIG_LOAD_FAILED' && !sessionRetriedRef.current) { + sessionRetriedRef.current = true; + logger.warn( + '[TransakHeadlessCheckout] card form config failed, new session', + ); + createCardSession(); + return; + } + showError({ + err: new TransakHeadlessError(code), + reason: 'card form error', + allowFallback: true, + }); + }; + + const onPressBuy = () => { + if (isNewCard) { + payWithNewCard(); + return; + } + const card = usableSavedCards.find( + c => c.paymentIdentifierId === selectedCardId, + ); + if (card) { + payWithSavedCard(card); + } + }; + + const handleRedirectNavigation = (url: string): boolean => { + const result = getTransakHeadlessRedirectResult(url); + if (result) { + finalize(result); + return false; + } + // Nothing on the 3DS page may take the customer out of the app. + return !url.startsWith(APP_DEEPLINK_PREFIX); + }; + + const buyDisabled = + !!buttonState || + (isNewCard ? !cardFormReady || !cardValid : !selectedCardId); + + return ( + + + + + + + + + {formatFiatAmount(Number(quote.fiatAmount), offer.fiatCurrency)} + + + {quote.cryptoAmount} {coin.toUpperCase()} + + + + + {t('Destination')} + + + + + {wallet.walletName ? wallet.walletName : wallet.currencyName} + + + + + + + {t('Fees')} + + {formatFiatAmount(Number(quote.totalFee), offer.fiatCurrency)} + + + + + + {t('Total')} + + + {formatFiatAmount(Number(quote.fiatAmount), offer.fiatCurrency)} + + + + + + {t('Pay with')} + + {usableSavedCards.length > 0 ? ( + <> + {usableSavedCards.map(card => ( + setSelectedCardId(card.paymentIdentifierId)}> + + + setSelectedCardId(card.paymentIdentifierId) + } + /> + + {getSavedCardLabel(card)} + + + + ))} + setSelectedCardId('new')}> + + setSelectedCardId('new')} + /> + + {t('Use a new card')} + + + + + ) : null} + + {isNewCard ? ( + + {cardSessionId ? ( + setCardFormReady(true)} + onChange={({isValid, errorCode}) => { + setCardValid(isValid); + setCardStateError( + errorCode === 'BIN_BLOCKED' + ? t( + 'This card is not supported. Please use a different card.', + ) + : undefined, + ); + }} + onSuccess={onCardSuccess} + onError={onCardError} + /> + ) : null} + {!cardFormReady ? ( + + + + ) : null} + + ) : null} + {isNewCard && cardStateError ? ( + {cardStateError} + ) : null} + + + + + + + {t('Powered by')} + + + + + + + finalize('cancelled')} + style={{margin: 0, padding: 0}}> + + + finalize('cancelled')}> + ✕ + + + {redirectUrl ? ( + + handleRedirectNavigation(event.url) + } + // Android does not always ask before following a redirect. + onNavigationStateChange={event => { + if (getTransakHeadlessRedirectResult(event.url)) { + handleRedirectNavigation(event.url); + } + }} + /> + ) : null} + + + + ); +}; + +export default TransakBuyHeadlessCheckout; diff --git a/src/navigation/services/screens/TransakBuyHeadlessOnboarding.tsx b/src/navigation/services/screens/TransakBuyHeadlessOnboarding.tsx new file mode 100644 index 0000000000..2e8f501e39 --- /dev/null +++ b/src/navigation/services/screens/TransakBuyHeadlessOnboarding.tsx @@ -0,0 +1,482 @@ +import React, {useLayoutEffect, useState} from 'react'; +import { + Keyboard, + SafeAreaView, + ScrollView, + StyleSheet, + Text, + TextProps, + View, + ViewProps, +} from 'react-native'; +import {useNavigation} from '@react-navigation/native'; +import {NativeStackScreenProps} from '@react-navigation/native-stack'; +import {useTranslation} from 'react-i18next'; +import Button, {ButtonState} from '../../../components/button/Button'; +import BoxInput from '../../../components/form/BoxInput'; +import {BaseText} from '../../../components/styled/Text'; +import { + Action, + LinkBlue, + Slate30, + SlateDark, + White, +} from '../../../styles/colors'; +import {useTheme} from '../../../contexts'; +import {useAppDispatch, useLogger} from '../../../utils/hooks'; +import {AppEffects} from '../../../store/app'; +import {Analytics} from '../../../store/analytics/analytics.effects'; +import {getErrorString} from '../../../utils/helper-methods'; +import yup from '../../../lib/yup'; +import TransakLogo from '../../../components/icons/external-services/transak/transak-logo'; +import {Wallet} from '../../../store/wallet/wallet.models'; +import { + TransakHeadlessUserAuthData, + TransakHeadlessVerifyOtpData, +} from '../../../store/buy-crypto/buy-crypto.models'; +import { + TransakHeadlessError, + transakHeadlessSendOtp, + transakHeadlessVerifyOtp, +} from '../../../store/buy-crypto/effects/transak/transak-headless'; +import {transakEnv} from '../buy-crypto/utils/transak-utils'; +import { + ExternalServicesGroupParamList, + ExternalServicesScreens, +} from '../ExternalServicesGroup'; + +const OTP_LENGTH = 6; + +const styles = StyleSheet.create({ + container: { + flex: 1, + margin: 14, + }, + headerContainer: { + marginBottom: 24, + }, + iconRow: { + flexDirection: 'row', + alignItems: 'center', + marginBottom: 24, + }, + title: { + fontSize: 31, + fontWeight: '700', + textAlign: 'left', + lineHeight: 38, + marginBottom: 12, + }, + subtitle: { + fontSize: 16, + fontWeight: '400', + textAlign: 'left', + lineHeight: 24, + }, + inputContainer: { + marginBottom: 20, + }, + secondaryActions: { + flexDirection: 'row', + justifyContent: 'space-between', + marginTop: 16, + }, + secondaryActionText: { + fontSize: 14, + fontWeight: '500', + }, + bottomSection: { + padding: 16, + }, + legalText: { + fontSize: 13, + textAlign: 'center', + marginBottom: 16, + lineHeight: 20, + }, +}); + +const Container: React.FC = ({style, ...rest}) => ( + +); + +const HeaderContainer: React.FC = ({style, ...rest}) => ( + +); + +const IconRow: React.FC = ({style, ...rest}) => ( + +); + +const Title = React.forwardRef>( + ({style, ...rest}, ref) => { + const theme = useTheme(); + return ( + + ); + }, +); +Title.displayName = 'Title'; + +const Subtitle = React.forwardRef>( + ({style, ...rest}, ref) => { + const theme = useTheme(); + return ( + + ); + }, +); +Subtitle.displayName = 'Subtitle'; + +const InputContainer: React.FC = ({style, ...rest}) => ( + +); + +const SecondaryActions: React.FC = ({style, ...rest}) => ( + +); + +const ActionLink = React.forwardRef( + ({style, disabled, onPress, ...rest}, ref) => { + const theme = useTheme(); + return ( + + ); + }, +); +ActionLink.displayName = 'ActionLink'; + +const BottomSection: React.FC = ({style, ...rest}) => ( + +); + +const LegalText = React.forwardRef>( + ({style, ...rest}, ref) => { + const theme = useTheme(); + return ( + + ); + }, +); +LegalText.displayName = 'LegalText'; + +const LegalLink = React.forwardRef(({style, ...rest}, ref) => { + const theme = useTheme(); + return ( + + ); +}); +LegalLink.displayName = 'LegalLink'; + +export interface TransakBuyHeadlessOnboardingProps { + wallet: Wallet; + country?: string; + initialEmail?: string; + // Kept loading until it resolves, while the checkout is prepared. + onConnect: (userAuth: TransakHeadlessUserAuthData) => Promise | void; + // manualSkip is false when the onboarding gave up on its own. + onSkip: (manualSkip: boolean) => void; +} + +const emailSchema = yup.string().email().required().trim(); + +const TransakBuyHeadlessOnboarding = ({ + route, +}: NativeStackScreenProps< + ExternalServicesGroupParamList, + ExternalServicesScreens.TRANSAK_BUY_HEADLESS_ONBOARDING +>) => { + const {t} = useTranslation(); + const navigation = useNavigation(); + const logger = useLogger(); + const dispatch = useAppDispatch(); + + const {wallet, country, initialEmail, onConnect, onSkip} = route.params; + + const [step, setStep] = useState<'email' | 'code'>('email'); + const [email, setEmail] = useState(initialEmail ?? ''); + const [emailError, setEmailError] = useState(); + const [code, setCode] = useState(''); + const [codeError, setCodeError] = useState(); + const [stateToken, setStateToken] = useState(); + const [buttonState, setButtonState] = useState(); + const [resending, setResending] = useState(false); + + const busy = !!buttonState || resending; + + useLayoutEffect(() => { + navigation.setOptions({ + headerTitle: '', + }); + }, [navigation]); + + const sendCode = async (normalizedEmail: string): Promise => { + try { + const data = await transakHeadlessSendOtp(wallet, { + env: transakEnv, + email: normalizedEmail, + }); + if (!data?.stateToken) { + throw new Error('No stateToken returned'); + } + setStateToken(data.stateToken); + dispatch(Analytics.track('Transak Headless Onboarding: code sent')); + return true; + } catch (err) { + logger.error( + `[TransakHeadlessOnboarding] send code failed: ${getErrorString(err)}`, + ); + setEmailError( + t('We could not send the code. Please check your email and try again.'), + ); + return false; + } + }; + + const submitEmail = async () => { + Keyboard.dismiss(); + const normalizedEmail = email.trim().toLowerCase(); + if (!emailSchema.isValidSync(normalizedEmail)) { + setEmailError(t('Please enter a valid email address.')); + return; + } + setEmailError(undefined); + setButtonState('loading'); + const sent = await sendCode(normalizedEmail); + setButtonState(undefined); + if (sent) { + setEmail(normalizedEmail); + setCode(''); + setCodeError(undefined); + setStep('code'); + } + }; + + const resendCode = async () => { + setResending(true); + setCode(''); + setCodeError(undefined); + const sent = await sendCode(email); + setResending(false); + if (!sent) { + setStep('email'); + } + }; + + const submitCode = async () => { + Keyboard.dismiss(); + if (!stateToken || code.length !== OTP_LENGTH) { + setCodeError(t('Enter the 6-digit code.')); + return; + } + setCodeError(undefined); + setButtonState('loading'); + let data: TransakHeadlessVerifyOtpData; + try { + data = await transakHeadlessVerifyOtp(wallet, { + env: transakEnv, + email, + otp: code, + stateToken, + }); + if (!data?.accessToken || !data.ttl) { + throw new Error('No accessToken returned'); + } + dispatch(Analytics.track('Transak Headless Onboarding: connected')); + } catch (err) { + logger.error( + `[TransakHeadlessOnboarding] verify code failed: ${getErrorString( + err, + )}`, + ); + setButtonState(undefined); + const isRejectedCode = + err instanceof TransakHeadlessError && + !!err.statusCode && + err.statusCode >= 400 && + err.statusCode < 500; + setCodeError( + isRejectedCode + ? t('The code is not valid or has expired.') + : t('Something went wrong. Please try again later.'), + ); + return; + } + await onConnect({ + accessToken: data.accessToken, + expiresAt: Date.now() + data.ttl * 1000, + email, + }); + setButtonState(undefined); + }; + + const skip = () => { + dispatch( + Analytics.track('Transak Headless Onboarding: manual skip', {step}), + ); + onSkip(true); + }; + + const openUrl = (url: string) => { + dispatch(AppEffects.openUrlWithInAppBrowser(url)); + }; + + return ( + + + + + + + {step === 'email' ? ( + <> + {t('Pay by card without leaving the app')} + + {t( + 'BitPay partners with Transak so you can buy crypto with your card right here. Verify your email with Transak to continue.', + )} + + + ) : ( + <> + {t('Enter verification code')} + + {t('Transak sent a 6-digit code to {{email}}.', {email})} + + + )} + + + {step === 'email' ? ( + + { + setEmail(text); + setEmailError(undefined); + }} + error={emailError} + keyboardType={'email-address'} + autoCapitalize={'none'} + autoCorrect={false} + textContentType={'emailAddress'} + autoComplete={'email'} + returnKeyType={'done'} + onSubmitEditing={submitEmail} + editable={!busy} + /> + + ) : ( + + { + setCode(text.replace(/\D/g, '').slice(0, OTP_LENGTH)); + setCodeError(undefined); + }} + error={codeError} + keyboardType={'number-pad'} + textContentType={'oneTimeCode'} + autoComplete={'one-time-code'} + maxLength={OTP_LENGTH} + autoFocus={true} + returnKeyType={'done'} + onSubmitEditing={submitCode} + editable={!busy} + /> + + + {resending ? t('Sending...') : t('Resend code')} + + { + setStep('email'); + setCode(''); + setCodeError(undefined); + }}> + {t('Use a different email')} + + + + )} + + + + + {t('By continuing, you agree to')}{' '} + + openUrl( + country === 'US' + ? 'https://transak.com/terms-of-service-us' + : 'https://transak.com/terms-of-service', + ) + }> + {t("Transak's Terms of Service")} + + {'.'} + + + + + + ); +}; + +export default TransakBuyHeadlessOnboarding; diff --git a/src/store/buy-crypto/buy-crypto.actions.ts b/src/store/buy-crypto/buy-crypto.actions.ts index 13723cc6bb..09fada7ead 100644 --- a/src/store/buy-crypto/buy-crypto.actions.ts +++ b/src/store/buy-crypto/buy-crypto.actions.ts @@ -12,6 +12,7 @@ import { TransakIncomingData, WyrePaymentData, TransakAccessTokenPayload, + TransakHeadlessUserAuthPayload, } from './buy-crypto.models'; import {RampIncomingData, RampPaymentData} from './models/ramp.models'; import {BuyCryptoStateOpts} from './buy-crypto.reducer'; @@ -149,6 +150,14 @@ export const updateAccessTokenTransak = ( payload, }); +// userAuth undefined clears the stored session. +export const updateHeadlessUserAuthTransak = ( + payload: TransakHeadlessUserAuthPayload, +): BuyCryptoActionType => ({ + type: BuyCryptoActionTypes.HEADLESS_USER_AUTH_TRANSAK, + payload, +}); + export const removePaymentRequestTransak = (payload: { transakExternalId: string; }): BuyCryptoActionType => ({ diff --git a/src/store/buy-crypto/buy-crypto.models.ts b/src/store/buy-crypto/buy-crypto.models.ts index f0b44dd920..74eb0d78a4 100644 --- a/src/store/buy-crypto/buy-crypto.models.ts +++ b/src/store/buy-crypto/buy-crypto.models.ts @@ -793,6 +793,7 @@ export interface TransakPaymentData { order_id?: string; payment_method?: PaymentMethodKey; transaction_id?: string; + is_headless?: boolean; } export interface TransakIncomingData { @@ -1137,3 +1138,106 @@ export interface TransakOrderDetailsData { walletLink: string; }; } + +// Transak headless (Whitelabel API, proxied by BWS) + +export type TransakEnv = 'sandbox' | 'production'; + +// Transak user session from the email OTP login. Valid for 30 days and only +// renewable with a new OTP once expired. +export interface TransakHeadlessUserAuthData { + accessToken: string; + expiresAt: number; // ms + email: string; +} + +export interface TransakHeadlessUserAuthPayload { + env: TransakEnv; + userAuth: TransakHeadlessUserAuthData | undefined; +} + +export interface TransakHeadlessSendOtpData { + isTncAccepted?: boolean; + stateToken: string; + email: string; + expiresIn?: number; // seconds +} + +export interface TransakHeadlessVerifyOtpData { + accessToken: string; + ttl: number; // seconds + created?: string; +} + +export interface TransakHeadlessGetQuoteRequestData { + env: TransakEnv; + fiatCurrency: string; + cryptoCurrency: string; + network: string; + paymentMethod: TransakPaymentType; + fiatAmount: number; + partnerCustomerId?: string; + partnerOrderId?: string; +} + +export interface TransakHeadlessQuoteData { + quoteId: string; + conversionPrice: number; + fiatCurrency?: string; + cryptoCurrency?: string; + paymentMethod?: string; + fiatAmount: number; + cryptoAmount: number; + isBuyOrSell?: 'BUY' | 'SELL'; + network: string; + feeDecimal?: number; + totalFee: number; + feeBreakdown?: {name: string; value: number; id: string}[]; + nonce?: number; + slippage?: number; +} + +export type TransakHeadlessKycStatus = + | 'NOT_SUBMITTED' + | 'SUBMITTED' + | 'APPROVED' + | 'ADDITIONAL_FORMS_REQUIRED'; + +export interface TransakHeadlessKycRequirementData { + isAllowedToPlaceOrder: boolean; + status: TransakHeadlessKycStatus | string; + kycType?: 'SIMPLE' | 'STANDARD' | 'ENHANCED' | string; +} + +export interface TransakHeadlessSavedCard { + paymentIdentifierId: string; + bin?: string; + last4: string; + scheme?: string; + expiryMonth?: number; + expiryYear?: number; +} + +export interface TransakHeadlessCardSessionData { + sessionId: string; + expiresAt?: string; +} + +export interface TransakHeadlessOrderData { + orderId: string; + status: TransakStatusKey; + fiatCurrency?: string; + cryptoCurrency?: string; + paymentMethod?: string; + network?: string; + fiatAmount?: number; + cryptoAmount?: number; + totalFeeInFiat?: number; + walletAddress?: string; + paymentDetails?: { + redirectUrl?: string; + [key: string]: any; + }[]; + txHash?: string; + transactionLink?: string; +} diff --git a/src/store/buy-crypto/buy-crypto.reducer.spec.ts b/src/store/buy-crypto/buy-crypto.reducer.spec.ts index ed6ea94282..eb5574c07e 100644 --- a/src/store/buy-crypto/buy-crypto.reducer.spec.ts +++ b/src/store/buy-crypto/buy-crypto.reducer.spec.ts @@ -745,6 +745,49 @@ describe('ACCESS_TOKEN_TRANSAK', () => { }); }); +// --------------------------------------------------------------------------- +// HEADLESS_USER_AUTH_TRANSAK +// --------------------------------------------------------------------------- + +describe('HEADLESS_USER_AUTH_TRANSAK', () => { + const userAuth = { + accessToken: 'user-tok', + expiresAt: 9999999, + email: 'user@example.com', + }; + + it('stores the user session for the env', () => { + const state = buyCryptoReducer(freshState(), { + type: BuyCryptoActionTypes.HEADLESS_USER_AUTH_TRANSAK, + payload: {env: 'sandbox', userAuth}, + }); + expect(state.tokens.transakHeadlessUser?.sandbox).toEqual(userAuth); + expect(state.tokens.transakHeadlessUser?.production).toBeUndefined(); + }); + + it('clears the user session when userAuth is undefined', () => { + let state = buyCryptoReducer(freshState(), { + type: BuyCryptoActionTypes.HEADLESS_USER_AUTH_TRANSAK, + payload: {env: 'production', userAuth}, + }); + state = buyCryptoReducer(state, { + type: BuyCryptoActionTypes.HEADLESS_USER_AUTH_TRANSAK, + payload: {env: 'production', userAuth: undefined}, + }); + expect(state.tokens.transakHeadlessUser?.production).toBeUndefined(); + }); + + it('works on a state persisted before headless existed', () => { + const base = {...freshState(), tokens: {transak: {}}}; + const state = buyCryptoReducer(base, { + type: BuyCryptoActionTypes.HEADLESS_USER_AUTH_TRANSAK, + payload: {env: 'sandbox', userAuth}, + }); + expect(state.tokens.transakHeadlessUser?.sandbox).toEqual(userAuth); + expect(state.tokens.transak).toEqual({}); + }); +}); + // --------------------------------------------------------------------------- // WYRE // --------------------------------------------------------------------------- diff --git a/src/store/buy-crypto/buy-crypto.reducer.ts b/src/store/buy-crypto/buy-crypto.reducer.ts index a058c5bec6..f920049bdb 100644 --- a/src/store/buy-crypto/buy-crypto.reducer.ts +++ b/src/store/buy-crypto/buy-crypto.reducer.ts @@ -5,6 +5,7 @@ import { SardinePaymentData, SimplexPaymentData, TransakAccessTokenData, + TransakHeadlessUserAuthData, TransakPaymentData, WyrePaymentData, } from './buy-crypto.models'; @@ -34,6 +35,10 @@ export interface BuyCryptoState { wyre: {[key in string]: WyrePaymentData}; tokens: { transak: {[key in 'sandbox' | 'production']?: TransakAccessTokenData}; + // Missing on states persisted before Transak headless existed. + transakHeadlessUser?: { + [key in 'sandbox' | 'production']?: TransakHeadlessUserAuthData; + }; }; } @@ -51,6 +56,7 @@ const initialState: BuyCryptoState = { wyre: {}, tokens: { transak: {}, + transakHeadlessUser: {}, }, }; @@ -419,6 +425,18 @@ export const buyCryptoReducer = ( }, }; + case BuyCryptoActionTypes.HEADLESS_USER_AUTH_TRANSAK: + return { + ...state, + tokens: { + ...state.tokens, + transakHeadlessUser: { + ...state.tokens.transakHeadlessUser, + [action.payload.env]: action.payload.userAuth, + }, + }, + }; + case BuyCryptoActionTypes.SUCCESS_PAYMENT_REQUEST_WYRE: const {wyrePaymentData} = action.payload; if (wyrePaymentData.orderId) { diff --git a/src/store/buy-crypto/buy-crypto.types.ts b/src/store/buy-crypto/buy-crypto.types.ts index 87b2c4261a..828238549d 100644 --- a/src/store/buy-crypto/buy-crypto.types.ts +++ b/src/store/buy-crypto/buy-crypto.types.ts @@ -9,6 +9,7 @@ import { SimplexIncomingData, TransakPaymentData, TransakIncomingData, + TransakHeadlessUserAuthPayload, WyrePaymentData, } from './buy-crypto.models'; import {BuyCryptoStateOpts} from './buy-crypto.reducer'; @@ -37,6 +38,7 @@ export enum BuyCryptoActionTypes { SUCCESS_PAYMENT_REQUEST_WYRE = 'BUY_CRYPTO/SUCCESS_PAYMENT_REQUEST_WYRE', REMOVE_PAYMENT_REQUEST_WYRE = 'BUY_CRYPTO/REMOVE_PAYMENT_REQUEST_WYRE', ACCESS_TOKEN_TRANSAK = 'BUY_CRYPTO/ACCESS_TOKEN_TRANSAK', + HEADLESS_USER_AUTH_TRANSAK = 'BUY_CRYPTO/HEADLESS_USER_AUTH_TRANSAK', } interface updateBuyCryptoOpts { @@ -181,6 +183,11 @@ interface updateAccessTokenTransak { }; } +interface updateHeadlessUserAuthTransak { + type: typeof BuyCryptoActionTypes.HEADLESS_USER_AUTH_TRANSAK; + payload: TransakHeadlessUserAuthPayload; +} + interface successPaymentRequestWyre { type: typeof BuyCryptoActionTypes.SUCCESS_PAYMENT_REQUEST_WYRE; payload: { @@ -216,5 +223,6 @@ export type BuyCryptoActionType = | updatePaymentRequestTransak | removePaymentRequestTransak | updateAccessTokenTransak + | updateHeadlessUserAuthTransak | successPaymentRequestWyre | removePaymentRequestWyre; diff --git a/src/store/buy-crypto/effects/transak/transak-headless.ts b/src/store/buy-crypto/effects/transak/transak-headless.ts new file mode 100644 index 0000000000..c120168564 --- /dev/null +++ b/src/store/buy-crypto/effects/transak/transak-headless.ts @@ -0,0 +1,211 @@ +import {Wallet} from '../../../wallet/wallet.models'; +import { + TransakEnv, + TransakHeadlessCardSessionData, + TransakHeadlessGetQuoteRequestData, + TransakHeadlessKycRequirementData, + TransakHeadlessOrderData, + TransakHeadlessQuoteData, + TransakHeadlessSavedCard, + TransakHeadlessSendOtpData, + TransakHeadlessVerifyOtpData, +} from '../../buy-crypto.models'; + +// Transak's Whitelabel API answers errors with a body instead of a failed +// request, and BWS passes it through, so it is turned into an error here. +export class TransakHeadlessError extends Error { + statusCode?: number; + errorCode?: number; + + constructor(message: string, statusCode?: number, errorCode?: number) { + super(message); + this.name = 'TransakHeadlessError'; + this.statusCode = statusCode; + this.errorCode = errorCode; + } +} + +// Documented error codes the app reacts to. +export const TRANSAK_HEADLESS_ERROR_CODES = { + INVALID_AUTH_TOKEN: 1002, + USER_NOT_ONBOARDED: 1023, + ACCOUNT_DISABLED: 2030, + KYC_UPGRADE_REQUIRED: 4003, + FCA_CRITERIA_NOT_MET: 4016, + KYC_NOT_APPROVED: 6002, + FEATURE_NOT_ENABLED: 6003, + KYC_NOT_APPROVED_FOR_TRANSACTION: 6012, + LOCATION_DATA_REQUIRED: 6014, +}; + +export const isTransakHeadlessUnauthorized = (err: unknown): boolean => + err instanceof TransakHeadlessError && + (err.statusCode === 401 || + err.errorCode === TRANSAK_HEADLESS_ERROR_CODES.INVALID_AUTH_TOKEN); + +const unwrap = (response: any): T => { + const body = response?.body ?? response; + const error = + body?.error && typeof body.error === 'object' + ? body.error + : typeof body?.statusCode === 'number' && body.statusCode >= 400 + ? body + : undefined; + if (error) { + throw new TransakHeadlessError( + typeof error.message === 'string' ? error.message : 'Unknown error', + error.statusCode, + error.errorCode, + ); + } + return (body?.data ?? body?.response ?? body) as T; +}; + +export const transakHeadlessSendOtp = async ( + wallet: Wallet, + requestData: {env: TransakEnv; email: string}, +): Promise => + unwrap(await wallet.transakHeadlessSendOtp(requestData)); + +export const transakHeadlessVerifyOtp = async ( + wallet: Wallet, + requestData: { + env: TransakEnv; + email: string; + otp: string; + stateToken: string; + }, +): Promise => + unwrap(await wallet.transakHeadlessVerifyOtp(requestData)); + +export const transakHeadlessGetQuote = async ( + wallet: Wallet, + requestData: TransakHeadlessGetQuoteRequestData, +): Promise => + unwrap(await wallet.transakHeadlessGetQuote(requestData)); + +export const transakHeadlessGetKycRequirement = async ( + wallet: Wallet, + requestData: {env: TransakEnv; userAccessToken: string; quoteId: string}, +): Promise => + unwrap(await wallet.transakHeadlessGetKycRequirement(requestData)); + +export const transakHeadlessGetSavedCards = async ( + wallet: Wallet, + requestData: {env: TransakEnv; userAccessToken: string}, +): Promise => { + const data = unwrap<{ + paymentInstruments?: { + credit_debit_card?: {cards?: TransakHeadlessSavedCard[]}; + }; + }>(await wallet.transakHeadlessGetSavedCards(requestData)); + return data?.paymentInstruments?.credit_debit_card?.cards ?? []; +}; + +export const transakHeadlessCreateCardSession = async ( + wallet: Wallet, + requestData: { + env: TransakEnv; + userAccessToken: string; + quoteId: string; + walletAddress: string; + successUrl: string; + failureUrl: string; + config?: { + colorMode?: 'DARK' | 'LIGHT'; + colors?: {[key: string]: string}; + }; + }, +): Promise => + unwrap(await wallet.transakHeadlessCreateCardSession(requestData)); + +export const transakHeadlessCreateOrder = async ( + wallet: Wallet, + requestData: + | {env: TransakEnv; userAccessToken: string; requestId: string} + | { + env: TransakEnv; + userAccessToken: string; + quoteId: string; + walletAddress: string; + paymentIdentifierId: string; + successUrl: string; + failureUrl: string; + }, +): Promise => + unwrap(await wallet.transakHeadlessCreateOrder(requestData)); + +export const transakHeadlessGetOrderDetails = async ( + wallet: Wallet, + requestData: {env: TransakEnv; userAccessToken: string; orderId: string}, +): Promise => + unwrap(await wallet.transakHeadlessGetOrderDetails(requestData)); + +export type TransakHeadlessPreparation = + | { + status: 'ready'; + quote: TransakHeadlessQuoteData; + quoteFetchedAt: number; + savedCards: TransakHeadlessSavedCard[]; + } + // The stored session was rejected: it has to be discarded. + | {status: 'unauthorized'} + // Headless cannot run this purchase (KYC, limits, feature...): the widget + // has to be used instead. + | {status: 'unavailable'; reason: string}; + +// Everything needed to decide headless vs widget before showing any screen, +// so falling back never interrupts a checkout the customer already started. +export const prepareTransakHeadlessCheckout = async ( + wallet: Wallet, + quoteRequestData: TransakHeadlessGetQuoteRequestData, + userAccessToken: string, +): Promise => { + const env = quoteRequestData.env; + try { + const quote = await transakHeadlessGetQuote(wallet, quoteRequestData); + if (!quote?.quoteId) { + return {status: 'unavailable', reason: 'quote: no quoteId'}; + } + const quoteFetchedAt = Date.now(); + + const kyc = await transakHeadlessGetKycRequirement(wallet, { + env, + userAccessToken, + quoteId: quote.quoteId, + }); + if (!kyc?.isAllowedToPlaceOrder) { + return { + status: 'unavailable', + reason: `kyc: ${kyc?.status ?? 'unknown'} (${kyc?.kycType ?? '-'})`, + }; + } + + let savedCards: TransakHeadlessSavedCard[] = []; + try { + savedCards = await transakHeadlessGetSavedCards(wallet, { + env, + userAccessToken, + }); + } catch (err) { + // Not being able to list saved cards still allows paying with a new one. + if (isTransakHeadlessUnauthorized(err)) { + throw err; + } + } + + return {status: 'ready', quote, quoteFetchedAt, savedCards}; + } catch (err) { + if (isTransakHeadlessUnauthorized(err)) { + return {status: 'unauthorized'}; + } + const code = + err instanceof TransakHeadlessError + ? `${err.statusCode ?? '-'}/${err.errorCode ?? '-'}` + : 'request'; + return { + status: 'unavailable', + reason: `${code}: ${err instanceof Error ? err.message : String(err)}`, + }; + } +}; diff --git a/yarn.lock b/yarn.lock index ac243f479f..b5e1e11329 100644 --- a/yarn.lock +++ b/yarn.lock @@ -5303,6 +5303,18 @@ Base64 "~0.2.0" inherits "~2.0.1" +"@transak/ui-components-core@0.6.0": + version "0.6.0" + resolved "https://registry.yarnpkg.com/@transak/ui-components-core/-/ui-components-core-0.6.0.tgz#f4c992a3cba1c1c7b85356471aadfc8ed298451e" + integrity sha512-SHIf5PcAtivh5xiKiRAB++WRazwGG/lRgKG16geEKUNZEX+PG5N39bX/vG4HL+ntQldFyLhGLRC6unFRB6cScw== + +"@transak/ui-components-rn@0.6.0": + version "0.6.0" + resolved "https://registry.yarnpkg.com/@transak/ui-components-rn/-/ui-components-rn-0.6.0.tgz#f4db7229b95c614f8c155fc8396bb8e22778ae53" + integrity sha512-8R1KsEDbgZcQBQ8DNj7LbdHNihVGT+I9MprtW9lf1ORaA6B62WivzP3Gh45MilHFiYrAO4EcPB/cNYvbujOqAQ== + dependencies: + "@transak/ui-components-core" "0.6.0" + "@trysound/sax@0.2.0": version "0.2.0" resolved "https://registry.yarnpkg.com/@trysound/sax/-/sax-0.2.0.tgz#cccaab758af56761eb7bf37af6f03f326dd798ad"