Next.js で自動通貨スイッチャーを構築する
前提条件
始める前に、Next.js と React について基本的に理解していることを確認してください。
1. バックエンド API ルートの作成
Geolocation API と対話する Next.js API ルートを作成します。
新しいファイルを次の場所に作成します: src/app/api/geolocation/route.ts
import { NextResponse } from "next/server"; import axios from "axios"; type IPGeolocation = { ip: string; version?: string; city?: string; region?: string; region_code?: string; country_code?: string; country_code_iso3?: string; country_fifa_code?: string; country_fips_code?: string; country_name?: string; country_capital?: string; country_tld?: string; country_emoji?: string; continent_code?: string; in_eu: boolean; land_locked: boolean; postal?: string; latitude?: number; longitude?: number; timezone?: string; utc_offset?: string; country_calling_code?: string; currency?: string; currency_name?: string; languages?: string; country_area?: number; asn?: string; // Append ?fields=asn to the URL isp?: string; // Append ?fields=isp to the URL } type IPGeolocationError = { code: string; error: string; } export async function GET() { // Retrieve IP address using the getClientIp function // For testing purposes, we'll use a fixed IP address // const clientIp = getClientIp(req.headers); const clientIp = "84.17.50.173"; if (!clientIp) { return NextResponse.json( { error: "Unable to determine IP address" }, { status: 400 } ); } const key = process.env.IPFLARE_API_KEY; if (!key) { return NextResponse.json( { error: "IPFlare API key is not set" }, { status: 500 } ); } try { const response = await axios.get<IPGeolocation | IPGeolocationError>( `https://api.ipflare.io/${clientIp}`, { headers: { "X-API-Key": key, }, } ); if ("error" in response.data) { return NextResponse.json({ error: response.data.error }, { status: 400 }); } return NextResponse.json(response.data); } catch { return NextResponse.json( { error: "Internal Server Error" }, { status: 500 } ); } }
2. API キーの取得
IP Flare と呼ばれる無料地理位置情報サービスを使用します。 API キー ページにアクセスします: API キー ページに移動します。
アクセス: www.ipflare.io
API キー ページから API キーを取得し、クイック コピーを使用してそれを環境変数として .env ファイルに保存できます。これをリクエストの認証に使用します。
3. フロントエンドコンポーネントの作成
プロバイダーと通貨セレクターを含むこのオールインワン コンポーネントを作成しました。私は shadcn/ui と、オンラインで見つけたいくつかのフラグ SVG を使用しています。
アプリケーションを
これで、通貨にアクセスしたいアプリケーション内のどこでも、フック const {currency } = useCurrency(); を使用できます。
これを Stripe と統合するには、チェックアウトを作成するときに通貨を送信し、Stripe 製品に複数通貨の価格設定が追加されていることを確認するだけです。
"use client"; import { useRouter } from "next/navigation"; import { createContext, type FC, type ReactNode, useContext, useEffect, useMemo, useState, } from "react"; import axios from "axios"; // 1) Import axios import { Flag } from "~/components/flag"; import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue, } from "~/components/ui/select"; import { cn } from "~/lib/utils"; import { type Currency } from "~/server/schemas/currency"; // -- [1] Create a local type for the data returned by /api/geolocation. type GeolocationData = { country_code?: string; continent_code?: string; currency?: string; }; type CurrencyContext = { currency: Currency; setCurrency: (currency: Currency) => void; }; const CurrencyContext = createContext<CurrencyContext | null>(null); export function useCurrency() { const context = useContext(CurrencyContext); if (!context) { throw new Error("useCurrency must be used within a CurrencyProvider."); } return context; } export const CurrencyProvider: FC<{ children: ReactNode }> = ({ children }) => { const router = useRouter(); // -- [2] Local state for geolocation data const [location, setLocation] = useState<GeolocationData | null>(null); const [isLoading, setIsLoading] = useState<boolean>(true); // -- [3] Fetch location once when the component mounts useEffect(() => { const fetchLocation = async () => { setIsLoading(true); try { const response = await axios.get("/api/geolocation"); setLocation(response.data); } catch (error) { console.error(error); } finally { setIsLoading(false); } }; void fetchLocation(); }, []); // -- [4] Extract currency from location if present (fallback to "usd") const geoCurrency = location?.currency; const getInitialCurrency = (): Currency => { if (typeof window !== "undefined") { const cookie = document.cookie .split("; ") .find((row) => row.startsWith("currency=")); if (cookie) { const value = cookie.split("=")[1]; if (value === "usd" || value === "eur" || value === "gbp") { return value; } } } return "usd"; }; const [currency, setCurrencyState] = useState<Currency>(getInitialCurrency); useEffect(() => { if (!isLoading && geoCurrency !== undefined) { const validatedCurrency = validateCurrency(geoCurrency, location); if (validatedCurrency) { setCurrency(validatedCurrency); } } // eslint-disable-next-line react-hooks/exhaustive-deps }, [isLoading, location, geoCurrency]); // -- [5] Update currency & store cookie; no more tRPC invalidation const setCurrency = (newCurrency: Currency) => { setCurrencyState(newCurrency); if (typeof window !== "undefined") { document.cookie = `currency=${newCurrency}; path=/; max-age=${ 60 * 60 * 24 * 365 }`; // Expires in 1 year } // Removed tRPC invalidate since we are no longer using tRPC router.refresh(); }; const contextValue = useMemo<CurrencyContext>( () => ({ currency, setCurrency, }), [currency], ); return ( <CurrencyContext.Provider value={contextValue}> {children} </CurrencyContext.Provider> ); }; export const CurrencySelect = ({ className }: { className?: string }) => { const { currency, setCurrency } = useCurrency(); return ( <Select value={currency} onValueChange={setCurrency}> <SelectTrigger className={cn("w-[250px]", className)}> <SelectValue placeholder="Select a currency" /> </SelectTrigger> <SelectContent> <SelectGroup className="text-sm"> <SelectItem value="usd"> <div className="flex items-center gap-3"> <Flag code="US" className="h-4 w-4 rounded" /> <span>$ USD</span> </div> </SelectItem> <SelectItem value="eur"> <div className="flex items-center gap-3"> <Flag code="EU" className="h-4 w-4 rounded" /> <span>€ EUR</span> </div> </SelectItem> <SelectItem value="gbp"> <div className="flex items-center gap-3"> <Flag code="GB" className="h-4 w-4 rounded" /> <span>£ GBP</span> </div> </SelectItem> </SelectGroup> </SelectContent> </Select> ); }; // -- [6] Use our new GeolocationData type in place of RouterOutputs const validateCurrency = ( currency: string, location?: GeolocationData | null, ): Currency | null => { if (currency === "usd" || currency === "eur" || currency === "gbp") { return currency; } if (!location) { return null; } if (location.country_code === "GB") { return "gbp"; } // Check if they are in the EU if (location.continent_code === "EU") { return "eur"; } // North America if (location.continent_code === "NA") { return "usd"; } return null; };
以上がNext.js で自動通貨スイッチャーを構築するの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

メモ帳++7.3.1
使いやすく無料のコードエディター

SublimeText3 中国語版
中国語版、とても使いやすい

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

ドリームウィーバー CS6
ビジュアル Web 開発ツール

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

ホットトピック











JavaScriptは現代のWeb開発の基礎であり、その主な機能には、イベント駆動型のプログラミング、動的コンテンツ生成、非同期プログラミングが含まれます。 1)イベント駆動型プログラミングにより、Webページはユーザー操作に応じて動的に変更できます。 2)動的コンテンツ生成により、条件に応じてページコンテンツを調整できます。 3)非同期プログラミングにより、ユーザーインターフェイスがブロックされないようにします。 JavaScriptは、Webインタラクション、シングルページアプリケーション、サーバー側の開発で広く使用されており、ユーザーエクスペリエンスとクロスプラットフォーム開発の柔軟性を大幅に改善しています。

JavaScriptの最新トレンドには、TypeScriptの台頭、最新のフレームワークとライブラリの人気、WebAssemblyの適用が含まれます。将来の見通しは、より強力なタイプシステム、サーバー側のJavaScriptの開発、人工知能と機械学習の拡大、およびIoTおよびEDGEコンピューティングの可能性をカバーしています。

さまざまなJavaScriptエンジンは、各エンジンの実装原則と最適化戦略が異なるため、JavaScriptコードを解析および実行するときに異なる効果をもたらします。 1。語彙分析:ソースコードを語彙ユニットに変換します。 2。文法分析:抽象的な構文ツリーを生成します。 3。最適化とコンパイル:JITコンパイラを介してマシンコードを生成します。 4。実行:マシンコードを実行します。 V8エンジンはインスタントコンピレーションと非表示クラスを通じて最適化され、Spidermonkeyはタイプ推論システムを使用して、同じコードで異なるパフォーマンスパフォーマンスをもたらします。

JavaScriptは、現代のWeb開発のコア言語であり、その多様性と柔軟性に広く使用されています。 1)フロントエンド開発:DOM操作と最新のフレームワーク(React、Vue.JS、Angularなど)を通じて、動的なWebページとシングルページアプリケーションを構築します。 2)サーバー側の開発:node.jsは、非ブロッキングI/Oモデルを使用して、高い並行性とリアルタイムアプリケーションを処理します。 3)モバイルおよびデスクトップアプリケーション開発:クロスプラットフォーム開発は、反応および電子を通じて実現され、開発効率を向上させます。

この記事では、許可によって保護されたバックエンドとのフロントエンド統合を示し、next.jsを使用して機能的なedtech SaaSアプリケーションを構築します。 FrontEndはユーザーのアクセス許可を取得してUIの可視性を制御し、APIリクエストがロールベースに付着することを保証します

Pythonは、スムーズな学習曲線と簡潔な構文を備えた初心者により適しています。 JavaScriptは、急な学習曲線と柔軟な構文を備えたフロントエンド開発に適しています。 1。Python構文は直感的で、データサイエンスやバックエンド開発に適しています。 2。JavaScriptは柔軟で、フロントエンドおよびサーバー側のプログラミングで広く使用されています。

C/CからJavaScriptへのシフトには、動的なタイピング、ゴミ収集、非同期プログラミングへの適応が必要です。 1)C/Cは、手動メモリ管理を必要とする静的に型付けられた言語であり、JavaScriptは動的に型付けされ、ごみ収集が自動的に処理されます。 2)C/Cはマシンコードにコンパイルする必要がありますが、JavaScriptは解釈言語です。 3)JavaScriptは、閉鎖、プロトタイプチェーン、約束などの概念を導入します。これにより、柔軟性と非同期プログラミング機能が向上します。

私はあなたの日常的な技術ツールを使用して機能的なマルチテナントSaaSアプリケーション(EDTECHアプリ)を作成しましたが、あなたは同じことをすることができます。 まず、マルチテナントSaaSアプリケーションとは何ですか? マルチテナントSaaSアプリケーションを使用すると、Singの複数の顧客にサービスを提供できます
