Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React, { useState } from 'react';
- import { GoogleOAuthProvider, useGoogleLogin } from '@react-oauth/google';
- const GeminiChat = () => {
- const [accessToken, setAccessToken] = useState(null);
- const [response, setResponse] = useState("");
- // This hook handles the "Login with Google" popup
- const login = useGoogleLogin({
- onSuccess: (tokenResponse) => {
- setAccessToken(tokenResponse.access_token);
- console.log("User Access Token:", tokenResponse.access_token);
- },
- // CRITICAL: You must include this scope for Gemini access
- scope: 'https://www.googleapis.com/auth/generative-language',
- });
- const askGemini = async () => {
- if (!accessToken) return alert("Please login first!");
- setResponse("Thinking...");
- // We call the REST API directly using the User's Bearer Token
- const url = "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent";
- try {
- const res = await fetch(url, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- "Authorization": `Bearer ${accessToken}`, // The user pays/uses their quota
- },
- body: JSON.stringify({
- contents: [{ parts: [{ text: "Explain why this request is billed to my account and not the app developer." }] }]
- })
- });
- const data = await res.json();
- setResponse(data.candidates[0].content.parts[0].text);
- } catch (error) {
- setResponse("Error: " + error.message);
- }
- };
- return (
- <div style={{ padding: '20px' }}>
- {!accessToken ? (
- <button onClick={() => login()}>Login with Google to use Gemini</button>
- ) : (
- <div>
- <p>Logged in! Your quota is now being used.</p>
- <button onClick={askGemini}>Ask Gemini</button>
- <div style={{ marginTop: '20px', whiteSpace: 'pre-wrap' }}>
- <strong>Gemini says:</strong> {response}
- </div>
- </div>
- )}
- </div>
- );
- };
- // Wrap your app with the Provider
- export default function App() {
- return (
- <GoogleOAuthProvider clientId="YOUR_GOOGLE_CLIENT_ID.apps.googleusercontent.com">
- <GeminiChat />
- </GoogleOAuthProvider>
- );
- }
Advertisement
Add Comment
Please, Sign In to add comment