STANAANDREY

Untitled

Apr 19th, 2026
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.24 KB | None | 0 0
  1. import React, { useState } from 'react';
  2. import { GoogleOAuthProvider, useGoogleLogin } from '@react-oauth/google';
  3.  
  4. const GeminiChat = () => {
  5. const [accessToken, setAccessToken] = useState(null);
  6. const [response, setResponse] = useState("");
  7.  
  8. // This hook handles the "Login with Google" popup
  9. const login = useGoogleLogin({
  10. onSuccess: (tokenResponse) => {
  11. setAccessToken(tokenResponse.access_token);
  12. console.log("User Access Token:", tokenResponse.access_token);
  13. },
  14. // CRITICAL: You must include this scope for Gemini access
  15. scope: 'https://www.googleapis.com/auth/generative-language',
  16. });
  17.  
  18. const askGemini = async () => {
  19. if (!accessToken) return alert("Please login first!");
  20.  
  21. setResponse("Thinking...");
  22.  
  23. // We call the REST API directly using the User's Bearer Token
  24. const url = "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent";
  25.  
  26. try {
  27. const res = await fetch(url, {
  28. method: "POST",
  29. headers: {
  30. "Content-Type": "application/json",
  31. "Authorization": `Bearer ${accessToken}`, // The user pays/uses their quota
  32. },
  33. body: JSON.stringify({
  34. contents: [{ parts: [{ text: "Explain why this request is billed to my account and not the app developer." }] }]
  35. })
  36. });
  37.  
  38. const data = await res.json();
  39. setResponse(data.candidates[0].content.parts[0].text);
  40. } catch (error) {
  41. setResponse("Error: " + error.message);
  42. }
  43. };
  44.  
  45. return (
  46. <div style={{ padding: '20px' }}>
  47. {!accessToken ? (
  48. <button onClick={() => login()}>Login with Google to use Gemini</button>
  49. ) : (
  50. <div>
  51. <p>Logged in! Your quota is now being used.</p>
  52. <button onClick={askGemini}>Ask Gemini</button>
  53. <div style={{ marginTop: '20px', whiteSpace: 'pre-wrap' }}>
  54. <strong>Gemini says:</strong> {response}
  55. </div>
  56. </div>
  57. )}
  58. </div>
  59. );
  60. };
  61.  
  62. // Wrap your app with the Provider
  63. export default function App() {
  64. return (
  65. <GoogleOAuthProvider clientId="YOUR_GOOGLE_CLIENT_ID.apps.googleusercontent.com">
  66. <GeminiChat />
  67. </GoogleOAuthProvider>
  68. );
  69. }
Advertisement
Add Comment
Please, Sign In to add comment