Skip to content

Commit

Permalink
feat: webembed pay
Browse files Browse the repository at this point in the history
  • Loading branch information
sidmorizon committed Jan 14, 2025
1 parent f2a6d57 commit c1a1298
Show file tree
Hide file tree
Showing 25 changed files with 606 additions and 170 deletions.
31 changes: 18 additions & 13 deletions apps/web-embed/index.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,29 @@
import { LazyLoadPage } from '@onekeyhq/kit/src/components/LazyLoadPage';
import { ConfigProvider } from '@onekeyhq/components';
import React from 'react';
import '@onekeyhq/shared/src/polyfills';
import React, { lazy, Suspense } from 'react';
import { createRoot } from 'react-dom/client';
import { HashRouter, Route, Routes } from 'react-router-dom';

const PageWebEmbedApi = LazyLoadPage(() => import('./pages/PageWebEmbedApi'));
const PagePrivyLogin = LazyLoadPage(() => import('./pages/PagePrivyLogin'));
import AppProvider from './pages/AppProvider';

const PageIndex = lazy(() => import('./pages/PageIndex'));
const PageWebEmbedApi = lazy(() => import('./pages/PageWebEmbedApi'));
const PagePrivyLogin = lazy(() => import('./pages/PagePrivyLogin'));

const container = document.getElementById('root');
const root = createRoot(container);

root.render(
<React.StrictMode>
<ConfigProvider theme="light" locale="en-us" onLocaleChange={() => {}}>
<HashRouter>
<Routes>
<Route path="/" element={<PageWebEmbedApi />} />
<Route path="/prime/login" element={<PagePrivyLogin />} />
</Routes>
</HashRouter>
</ConfigProvider>
<AppProvider>
<Suspense fallback={<div />}>
<HashRouter>
<Routes>
<Route path="/" element={<PageIndex />} />
<Route path="/webembed-api" element={<PageWebEmbedApi />} />
<Route path="/prime/login" element={<PagePrivyLogin />} />
</Routes>
</HashRouter>
</Suspense>
</AppProvider>
</React.StrictMode>,
);
14 changes: 14 additions & 0 deletions apps/web-embed/pages/AppProvider.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { ConfigProvider } from '@onekeyhq/components';

export default function AppProvider({
children,
}: {
children: React.ReactNode;
}) {
// TODO Toast support
return (
<ConfigProvider theme="light" locale="en-US">
{children}
</ConfigProvider>
);
}
3 changes: 3 additions & 0 deletions apps/web-embed/pages/PageIndex.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default function PageIndex() {
return <div>PageIndex</div>;
}
67 changes: 65 additions & 2 deletions apps/web-embed/pages/PagePrivyLogin.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,68 @@
import { Button } from '@onekeyhq/components';
/* eslint-disable unicorn/prefer-global-this */
import { useState } from 'react';

import { Button, SizableText, Stack, Toast } from '@onekeyhq/components';
import { PrimeSubscriptionPlans } from '@onekeyhq/kit/src/views/Prime/pages/PrimeDashboard/PrimeSubscriptionPlans';
import purchasesSdk from '@onekeyhq/kit/src/views/Prime/purchasesSdk/purchasesSdk';
import errorToastUtils from '@onekeyhq/shared/src/errors/utils/errorToastUtils';

import type { Package } from '@revenuecat/purchases-js';

export default function PagePrivyLogin() {
return <Button>PagePrivyLogin</Button>;
const [packages, setPackages] = useState<Package[]>([]);
const [selectedPackageId, setSelectedPackageId] = useState<string | null>(
null,
);
// @ts-ignore
const settings = window.WEB_EMBED_ONEKEY_APP_SETTINGS as {
themeVariant: string;
localeVariant: string;
primeUserId: string;
primeUserEmail: string;
};
return (
<Stack p="$4">
<PrimeSubscriptionPlans
packages={packages}
onPackageSelected={setSelectedPackageId}
/>
<Button
onPress={async () => {
await purchasesSdk.login({ userId: settings.primeUserId });
const packages0 = await purchasesSdk.getPaywallPackages();
setPackages(packages0);
}}
>
ShowPackages
</Button>
<Button
onPress={async () => {
await errorToastUtils.withErrorAutoToast(async () => {
if (!selectedPackageId) {
throw new Error('No package selected');
}
await purchasesSdk.purchasePackage({
userId: settings.primeUserId,
email: settings.primeUserEmail,
packageId: selectedPackageId,
});
});
}}
>
PurchasePackage
</Button>
<Button
onPress={async () => {
// TODO call app Toast by $onekey.$private
Toast.success({
title: 'success',
message: 'success',
});
}}
>
ShowToast
</Button>
<SizableText>{JSON.stringify(settings)}</SizableText>
</Stack>
);
}
16 changes: 12 additions & 4 deletions apps/web-embed/pages/PageWebEmbedApi.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useLayoutEffect } from 'react';
import { memo, useEffect } from 'react';

import { setBgSensitiveTextEncodeKey } from '@onekeyhq/core/src/secret';
import type { IBackgroundApiWebembedCallMessage } from '@onekeyhq/kit-bg/src/apis/IBackgroundApi';
Expand Down Expand Up @@ -42,11 +42,19 @@ const init = (times = 0) => {
});
};

export default () => {
useLayoutEffect(() => {
let isInitExecuted = false;
const PageWebEmbedApi = memo(() => {
useEffect(() => {
if (isInitExecuted) {
return;
}
isInitExecuted = true;
init();
printMessageToBody('web-embed init...');
printMessageToBody(`${globalThis.location.href}`);
}, []);
return null;
};
});
PageWebEmbedApi.displayName = 'PageWebEmbedApi';

export default PageWebEmbedApi;
1 change: 1 addition & 0 deletions development/webpack/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ const { developmentConsts } = require('../babelTools');
const { EXT_CHANNEL, TARGET_BROWSER } = require('./constant');

exports.createResolveExtensions = function ({ platform, configName }) {
console.log('createResolveExtensions>>>>>>', platform, configName);
return uniq([
// .chrome-ext.ts, .firefox-ext.ts
...(EXT_CHANNEL && TARGET_BROWSER
Expand Down
33 changes: 31 additions & 2 deletions packages/kit/src/components/WebViewWebEmbed/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import backgroundApiProxy from '@onekeyhq/kit/src//background/instance/backgroun
import platformEnv from '@onekeyhq/shared/src/platformEnv';
import webEmbedConfig from '@onekeyhq/shared/src/storage/webEmbedConfig';

import { useLocaleVariant } from '../../hooks/useLocaleVariant';
import { useThemeVariant } from '../../hooks/useThemeVariant';
import WebView from '../WebView';

import type { JsBridgeBase } from '@onekeyfe/cross-inpage-provider-core';
Expand All @@ -16,9 +18,15 @@ const initTop = '15%';
export function WebViewWebEmbed({
isSingleton,
customReceiveHandler,
hashRoutePath,
primeUserId,
primeUserEmail,
}: {
isSingleton?: boolean;
customReceiveHandler?: IJsBridgeReceiveHandler;
hashRoutePath?: string;
primeUserId?: string;
primeUserEmail?: string;
}) {
const webviewRef = useRef<IWebViewWrapperRef | null>(null);
const onWebViewRef = useCallback(($ref: IWebViewWrapperRef | null) => {
Expand All @@ -27,6 +35,8 @@ export function WebViewWebEmbed({
const [top, setTop] = useState(initTop);
const [minimized, setMinimized] = useState(false);
const config = useMemo(() => webEmbedConfig.getWebEmbedConfig(), []);
const themeVariant = useThemeVariant();
const localeVariant = useLocaleVariant();
useEffect(() => {
if (!platformEnv.isNative) {
return;
Expand Down Expand Up @@ -76,9 +86,28 @@ export function WebViewWebEmbed({
nativeWebviewSource={nativeWebviewSource}
onWebViewRef={onWebViewRef}
customReceiveHandler={customReceiveHandler}
nativeInjectedJavaScriptBeforeContentLoaded={`
window.location.hash = "${hashRoutePath || ''}";
window.WEB_EMBED_ONEKEY_APP_SETTINGS = {
themeVariant: "${themeVariant}",
localeVariant: "${localeVariant}",
primeUserId: "${primeUserId || ''}",
primeUserEmail: "${primeUserEmail || ''}",
};
`}
/>
),
[customReceiveHandler, nativeWebviewSource, onWebViewRef, remoteUrl],
[
customReceiveHandler,
hashRoutePath,
localeVariant,
nativeWebviewSource,
onWebViewRef,
primeUserEmail,
primeUserId,
remoteUrl,
themeVariant,
],
);

const webviewUrlOrUri = useMemo(() => {
Expand Down Expand Up @@ -143,7 +172,7 @@ export function WebViewWebEmbed({
}

function WebViewWebEmbedSingletonView() {
return <WebViewWebEmbed isSingleton />;
return <WebViewWebEmbed isSingleton hashRoutePath="/webembed-api" />;
}

export const WebViewWebEmbedSingleton = memo(WebViewWebEmbedSingletonView);
Original file line number Diff line number Diff line change
@@ -1,18 +1,31 @@
import { useCallback, useState } from 'react';

import { Button, Input, Page } from '@onekeyhq/components';
import { openUrlInApp } from '@onekeyhq/shared/src/utils/openUrlUtils';
import openUrlUtils from '@onekeyhq/shared/src/utils/openUrlUtils';

export default function WebviewGallery() {
const [url, setUrl] = useState('https://www.baidu.com');
const [hashRoutePath, setHashRoutePath] = useState('/prime/login');
const openWebView = useCallback(() => {
openUrlInApp(url);
openUrlUtils.openUrlInApp(url);
}, [url]);
const openWebViewEmbed = useCallback(() => {
openUrlUtils.openUrlByWebviewPro({
url: '',
title: 'WebView',
isWebEmbed: true,
hashRoutePath,
primeUserId: 'hello-world-1234567890',
});
}, [hashRoutePath]);
return (
<Page>
<Page.Body justifyContent="center" gap="$5" px="$10">
<Input flex={1} value={url} onChangeText={setUrl} />
<Button onPress={openWebView}>Go</Button>

<Input flex={1} value={hashRoutePath} onChangeText={setHashRoutePath} />
<Button onPress={openWebViewEmbed}>GoWebEmbed</Button>
</Page.Body>
</Page>
);
Expand Down
17 changes: 11 additions & 6 deletions packages/kit/src/views/Prime/hooks/usePrimePayment.native.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,17 +31,23 @@ export function usePrimePayment(): IUsePrimePayment {
if (!user?.privyUserId) {
throw new Error('User not logged in');
}
try {
await Purchases.logOut();
} catch (e) {
console.error(e);
}
// Do not logout which will create anonymous user
// try {
// await Purchases.logOut();
// } catch (e) {
// console.error(e);
// }
if (user?.privyUserId) {
try {
await Purchases.logIn(user.privyUserId);
} catch (e) {
console.error(e);
}
try {
await Purchases.logIn(user.privyUserId);
} catch (e) {
console.error(e);
}
}
const appUserId = await Purchases.getAppUserID();
if (appUserId !== user?.privyUserId) {
Expand Down Expand Up @@ -78,7 +84,6 @@ export function usePrimePayment(): IUsePrimePayment {
}
if (platformEnv.isNativeAndroid) {
apiKey = process.env.REVENUECAT_API_KEY_GOOGLE || '';
// apiKey = 'strp_AEqUtFOZYaIjPSuQGBVHVrqyiUs';
}
if (!apiKey) {
throw new Error('No REVENUECAT api key found');
Expand Down
Loading

0 comments on commit c1a1298

Please sign in to comment.