'Google साइन-इन' के साथ खाता जोड़ना (Dialogflow)

Assistant के लिए 'Google साइन-इन' का इस्तेमाल करने पर, सबसे आसान और आसान उपयोगकर्ता अनुभव मिलता है उपयोगकर्ताओं और डेवलपर के लिए, खाता लिंक करने और खाता बनाने के लिए. आपकी कार्रवाई बातचीत के दौरान, आपके उपयोगकर्ता की Google प्रोफ़ाइल का ऐक्सेस मांग सकता है. जिसमें उपयोगकर्ता का नाम, ईमेल पता, और प्रोफ़ाइल फ़ोटो शामिल हो.

प्रोफ़ाइल में दी गई जानकारी का इस्तेमाल, आपके हिसाब से उपयोगकर्ता अनुभव देने के लिए किया जा सकता है आपकी कार्रवाई में. अगर दूसरे प्लैटफ़ॉर्म पर आपके ऐप्लिकेशन हैं और वे 'Google साइन-इन' का इस्तेमाल करते हैं, किसी मौजूदा उपयोगकर्ता के खाते को खोजने और उससे लिंक करने, नया खाता बनाने, और उपयोगकर्ता से सीधे तौर पर बातचीत करने का ज़रिया बना सकते हैं.

'Google साइन-इन' के साथ खाता लिंक करने के लिए, उपयोगकर्ता से सहमति देने के लिए कहा जाता है Google प्रोफ़ाइल को ऐक्सेस करने के लिए. फिर आप उनकी प्रोफ़ाइल में मौजूद जानकारी का उपयोग उदाहरण के लिए उनका ईमेल पता, ताकि आपके सिस्टम में उपयोगकर्ता की पहचान की जा सके.

'Google साइन-इन' खाता लिंक करना लागू करना

अपने ऐक्शन.

प्रोजेक्ट कॉन्फ़िगर करें

'Google साइन-इन' खाता लिंक करने की सुविधा का इस्तेमाल करने के लिए अपना प्रोजेक्ट कॉन्फ़िगर करने के लिए, यह तरीका अपनाएं:

  1. Actions Console खोलें और कोई प्रोजेक्ट चुनें.
  2. डेवलप करें टैब पर क्लिक करें और खाता लिंक करना चुनें.
  3. खाता लिंक करना के बगल में मौजूद स्विच को चालू करें.
  4. खाता बनाएं सेक्शन में, हां चुनें.
  5. लिंक करने का टाइप सेक्शन में जाकर, Google साइन इन को चुनें.

  6. क्लाइंट की जानकारी खोलें और आपकी कार्रवाइयों के लिए Google की ओर से जारी किए गए Client ID की वैल्यू का ध्यान रखें.

  7. सेव करें पर क्लिक करें.

पुष्टि करने की प्रोसेस शुरू करना

खाते में साइन इन करने के लिए हेल्पर इंटेंट का इस्तेमाल करें पुष्टि करने की प्रोसेस शुरू करने के लिए.

उपयोगकर्ता जब आपकी कार्रवाई को अपनी Google प्रोफ़ाइल ऐक्सेस करने की अनुमति देगा, तब आपको Google आईडी टोकन, जो हर एक चरण में उपयोगकर्ता की Google प्रोफ़ाइल की जानकारी को शामिल करता है के लिए अनुरोध कर सकते हैं.

उपयोगकर्ता की प्रोफ़ाइल जानकारी को ऐक्सेस करने के लिए, आपको सबसे पहले टोकन की पुष्टि करनी होगी और उसे डिकोड करना होगा इसके लिए, ये काम किए जा सकते हैं:

  1. अपनी भाषा में JWT-डिकोडिंग लाइब्रेरी का इस्तेमाल करके टोकन, और Google की सार्वजनिक कुंजियों का इस्तेमाल करें (JWK में उपलब्ध) या PEM फ़ॉर्मैट) का इस्तेमाल करें.
  2. पुष्टि करें कि टोकन जारी करने वाला बैंक या कंपनी (डिकोड किए गए टोकन में iss फ़ील्ड) https://accounts.google.com है और यह कि ऑडियंस (डिकोड किए गए टोकन में aud फ़ील्ड) आपकी कार्रवाइयों के लिए Google का जारी किया गया क्लाइंट आईडी, जो आपके प्रोजेक्ट को असाइन किया गया है Actions on Google कंसोल में.

डिकोड किए गए टोकन का एक उदाहरण नीचे दिया गया है:

{
  "sub": 1234567890,        // The unique ID of the user's Google Account
  "iss": "https://accounts.google.com",        // The token's issuer
  "aud": "123-abc.apps.googleusercontent.com", // Client ID assigned to your Actions project
  "iat": 233366400,         // Unix timestamp of the token's creation time
  "exp": 233370000,         // Unix timestamp of the token's expiration time
  "name": "Jan Jansen",
  "given_name": "Jan",
  "family_name": "Jansen",
  "email": "jan@gmail.com", // If present, the user's email address
  "locale": "en_US"
}

अगर आपने Node.js के लिए Actions on Google क्लाइंट लाइब्रेरी या Java क्लाइंट लाइब्रेरी का इस्तेमाल किया है, यह आपके लिए टोकन की पुष्टि करता है और उसे डिकोड करता है. साथ ही, आपको प्रोफ़ाइल की सामग्री, जैसा कि नीचे दिए गए कोड स्निपेट में दिखाया गया है. ध्यान दें कि नीचे दिए गए JSON में, Dialogflow और Actions SDK टूल के लिए वेबहुक के अनुरोध के बारे में बताया गया है.

ये स्निपेट, साइन इन करने के लिए Dialogflow का इस्तेमाल करते हैं:

Node.js
const {dialogflow, SignIn} = require('actions-on-google');
const app = dialogflow({
  // REPLACE THE PLACEHOLDER WITH THE CLIENT_ID OF YOUR ACTIONS PROJECT
  clientId: CLIENT_ID,
});

// Intent that starts the account linking flow.
app.intent('Start Signin', (conv) => {
  conv.ask(new SignIn('To get your account details'));
});
// Create a Dialogflow intent with the `actions_intent_SIGN_IN` event.
app.intent('Get Signin', (conv, params, signin) => {
  if (signin.status === 'OK') {
    const payload = conv.user.profile.payload;
    conv.ask(`I got your account details, ${payload.name}. What do you want to do next?`);
  } else {
    conv.ask(`I won't be able to save your data, but what do you want to do next?`);
  }
});
जावा
private String clientId = "<your_client_id>";

@ForIntent("Start Signin")
public ActionResponse text(ActionRequest request) {
  ResponseBuilder rb = getResponseBuilder(request);
  return rb.add(new SignIn().setContext("To get your account details")).build();
}
@ForIntent("actions.intent.SIGN_IN")
public ActionResponse getSignInStatus(ActionRequest request) {
  ResponseBuilder responseBuilder = getResponseBuilder(request);
  if (request.isSignInGranted()) {
    GoogleIdToken.Payload profile = getUserProfile(request.getUser().getIdToken());
    responseBuilder.add(
        "I got your account details, "
            + profile.get("given_name")
            + ". What do you want to do next?");
  } else {
    responseBuilder.add("I won't be able to save your data, but what do you want to do next?");
  }
  return responseBuilder.build();
}

private GoogleIdToken.Payload getUserProfile(String idToken) {
  GoogleIdToken.Payload profile = null;
  try {
    profile = decodeIdToken(idToken);
  } catch (Exception e) {
    LOGGER.error("error decoding idtoken");
    LOGGER.error(e.toString());
  }
  return profile;
}

private GoogleIdToken.Payload decodeIdToken(String idTokenString)
    throws GeneralSecurityException, IOException {
  HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport();
  JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance();
  GoogleIdTokenVerifier verifier =
      new GoogleIdTokenVerifier.Builder(transport, jsonFactory)
          // Specify the CLIENT_ID of the app that accesses the backend:
          .setAudience(Collections.singletonList(clientId))
          .build();
  GoogleIdToken idToken = verifier.verify(idTokenString);
  return idToken.getPayload();
}
Dialogflow JSON
{
  "responseId": "",
  "queryResult": {
    "queryText": "",
    "action": "",
    "parameters": {},
    "allRequiredParamsPresent": true,
    "fulfillmentText": "",
    "fulfillmentMessages": [],
    "outputContexts": [],
    "intent": {
      "name": "Get Signin",
      "displayName": "Get Signin"
    },
    "intentDetectionConfidence": 1,
    "diagnosticInfo": {},
    "languageCode": ""
  },
  "originalDetectIntentRequest": {
    "source": "google",
    "version": "2",
    "payload": {
      "isInSandbox": true,
      "surface": {
        "capabilities": [
          {
            "name": "actions.capability.SCREEN_OUTPUT"
          },
          {
            "name": "actions.capability.AUDIO_OUTPUT"
          },
          {
            "name": "actions.capability.MEDIA_RESPONSE_AUDIO"
          },
          {
            "name": "actions.capability.WEB_BROWSER"
          }
        ]
      },
      "inputs": [
        {
          "rawInputs": [],
          "intent": "",
          "arguments": [
            {
              "name": "SIGN_IN",
              "extension": {
                "@type": "type.googleapis.com/google.actions.v2.SignInValue",
                "status": "OK"
              }
            }
          ]
        }
      ],
      "user": {
        "idToken": "peJaCGci..."
      },
      "conversation": {},
      "availableSurfaces": [
        {
          "capabilities": [
            {
              "name": "actions.capability.SCREEN_OUTPUT"
            },
            {
              "name": "actions.capability.AUDIO_OUTPUT"
            },
            {
              "name": "actions.capability.MEDIA_RESPONSE_AUDIO"
            },
            {
              "name": "actions.capability.WEB_BROWSER"
            }
          ]
        }
      ]
    }
  },
  "session": ""
}

नीचे दिए गए स्निपेट, साइन इन करने के लिए Actions SDK टूल का इस्तेमाल करते हैं:

Node.js
const {actionssdk, SignIn} = require('actions-on-google');
const app = actionssdk({
  // REPLACE THE PLACEHOLDER WITH THE CLIENT_ID OF YOUR ACTIONS PROJECT
  clientId: CLIENT_ID,
});

// Intent that starts the account linking flow.
app.intent('actions.intent.TEXT', (conv) => {
  conv.ask(new SignIn('To get your account details'));
});
// Create an Actions SDK intent with the `actions_intent_SIGN_IN` event.
app.intent('actions.intent.SIGN_IN', (conv, params, signin) => {
  if (signin.status === 'OK') {
    const payload = conv.user.profile.payload;
    conv.ask(`I got your account details, ${payload.name}. What do you want to do next?`);
  } else {
    conv.ask(`I won't be able to save your data, but what do you want to do next?`);
  }
});
जावा
private String clientId = "<your_client_id>";

@ForIntent("actions.intent.TEXT")
public ActionResponse text(ActionRequest request) {
  ResponseBuilder rb = getResponseBuilder(request);
  return rb.add(new SignIn().setContext("To get your account details")).build();
}
@ForIntent("actions.intent.SIGN_IN")
public ActionResponse getSignInStatus(ActionRequest request) {
  ResponseBuilder responseBuilder = getResponseBuilder(request);
  if (request.isSignInGranted()) {
    GoogleIdToken.Payload profile = getUserProfile(request.getUser().getIdToken());
    responseBuilder.add(
        "I got your account details, "
            + profile.get("given_name")
            + ". What do you want to do next?");
  } else {
    responseBuilder.add("I won't be able to save your data, but what do you want to do next?");
  }
  return responseBuilder.build();
}

private GoogleIdToken.Payload getUserProfile(String idToken) {
  GoogleIdToken.Payload profile = null;
  try {
    profile = decodeIdToken(idToken);
  } catch (Exception e) {
    LOGGER.error("error decoding idtoken");
    LOGGER.error(e.toString());
  }
  return profile;
}

private GoogleIdToken.Payload decodeIdToken(String idTokenString)
    throws GeneralSecurityException, IOException {
  HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport();
  JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance();
  GoogleIdTokenVerifier verifier =
      new GoogleIdTokenVerifier.Builder(transport, jsonFactory)
          // Specify the CLIENT_ID of the app that accesses the backend:
          .setAudience(Collections.singletonList(this.clientId))
          .build();
  GoogleIdToken idToken = verifier.verify(idTokenString);
  return idToken.getPayload();
}
कार्रवाइयां SDK टूल JSON
{
  "user": {
    "idToken": "peJaCGci..."
  },
  "device": {},
  "surface": {
    "capabilities": [
      {
        "name": "actions.capability.SCREEN_OUTPUT"
      },
      {
        "name": "actions.capability.AUDIO_OUTPUT"
      },
      {
        "name": "actions.capability.MEDIA_RESPONSE_AUDIO"
      },
      {
        "name": "actions.capability.WEB_BROWSER"
      }
    ]
  },
  "conversation": {},
  "inputs": [
    {
      "rawInputs": [],
      "intent": "actions.intent.SIGN_IN",
      "arguments": [
        {
          "name": "SIGN_IN",
          "extension": {
            "@type": "type.googleapis.com/google.actions.v2.SignInValue",
            "status": "OK"
          }
        }
      ]
    }
  ],
  "availableSurfaces": [
    {
      "capabilities": [
        {
          "name": "actions.capability.SCREEN_OUTPUT"
        },
        {
          "name": "actions.capability.AUDIO_OUTPUT"
        },
        {
          "name": "actions.capability.MEDIA_RESPONSE_AUDIO"
        },
        {
          "name": "actions.capability.WEB_BROWSER"
        }
      ]
    }
  ]
}

डेटा को ऐक्सेस करने के अनुरोधों को मैनेज करना

डेटा ऐक्सेस करने के अनुरोध को मैनेज करने के लिए, बस पुष्टि करें कि उपयोगकर्ता ने Google आईडी के ज़रिए दावा किया है टोकन आपके डेटाबेस में पहले से मौजूद है. कोड का यह स्निपेट दिखाता है यह पता लगाने का एक उदाहरण कि कोई उपयोगकर्ता खाता पहले से ही Firestore डेटाबेस में मौजूद है या नहीं.

Node.js
const admin = require('firebase-admin');
const functions = require('firebase-functions');
admin.initializeApp();
const auth = admin.auth();
const db = admin.firestore();

// Save the user in the Firestore DB after successful signin
app.intent('Get Sign In', async (conv, params, signin) => {
  if (signin.status !== 'OK') {
    return conv.close(`Let's try again next time.`);
  }
  const color = conv.data[Fields.COLOR];
  const {email} = conv.user;
  if (!conv.data.uid && email) {
    try {
      conv.data.uid = (await auth.getUserByEmail(email)).uid;
    } catch (e) {
      if (e.code !== 'auth/user-not-found') {
        throw e;
      }
      // If the user is not found, create a new Firebase auth user
      // using the email obtained from the Google Assistant
      conv.data.uid = (await auth.createUser({email})).uid;
    }
  }
  if (conv.data.uid) {
    conv.user.ref = db.collection('users').doc(conv.data.uid);
  }
  conv.close(`I saved ${color} as your favorite color for next time.`);
});

// Retrieve the user's favorite color if an account exists, ask if it doesn't.
app.intent('Default Welcome Intent', async (conv) => {
  const {payload} = conv.user.profile;
  const name = payload ? ` ${payload.given_name}` : '';
  conv.ask(`Hi${name}!`);
  // conv.user.ref contains the id of the record for the user in a Firestore DB
  if (conv.user.ref) {
    const doc = await conv.user.ref.get();
    if (doc.exists) {
      const color = doc.data()[Fields.COLOR];
      return conv.ask(`Your favorite color was ${color}. ` +
        'Tell me a color to update it.');
    }
  }
  conv.ask(`What's your favorite color?`);
});
जावा
private class FirestoreManager {
  private final Firestore db;
  private final DocumentReference userDocRef;
  private final String uid;
  public FirestoreManager(String databaseUrl, String email)
      throws IOException, FirebaseAuthException {
    if (FirebaseApp.getApps().isEmpty()) {
      // Use the application default credentials (works on GCP based hosting).
      FirebaseOptions options =
          new FirebaseOptions.Builder()
              .setCredentials(GoogleCredentials.getApplicationDefault())
              .setDatabaseUrl(databaseUrl)
              .build();
      FirebaseApp.initializeApp(options);
    }
    this.db = FirestoreClient.getFirestore();
    UserRecord userRecord;
    try {
      userRecord = FirebaseAuth.getInstance().getUserByEmail(email);
    } catch (FirebaseAuthException e) {
      if (e.getErrorCode() == FIREBASE_USER_NOT_FOUND_ERROR) {
        UserRecord.CreateRequest createRequest = new UserRecord.CreateRequest().setEmail(email);
        userRecord = FirebaseAuth.getInstance().createUser(createRequest);
      } else {
        throw e;
      }
    }
    uid = userRecord.getUid();
    userDocRef = db.collection(FIRESTORE_USERS_PATH).document(uid);
  }

  public String readUserColor() throws ExecutionException, InterruptedException {
    ApiFuture<DocumentSnapshot> future = userDocRef.get();
    // future.get() blocks on response
    DocumentSnapshot document = future.get();
    if (document.exists()) {
      return document.get(COLOR_KEY).toString();
    } else {
      return "";
    }
  }
  public Timestamp writeUserColor(String color) throws ExecutionException, InterruptedException {
    Map<String, Object> docData = new HashMap<>();
    docData.put(COLOR_KEY, color);
    ApiFuture<WriteResult> future = userDocRef.set(docData);
    // future.get() blocks on response
    return future.get().getUpdateTime();
  }
}

@ForIntent("Get Sign In")
public ActionResponse getSignIn(ActionRequest request) {
  LOGGER.info("Get sign in intent start.");
  ResponseBuilder responseBuilder = getResponseBuilder(request);
  if (request.isSignInGranted()) {
    String color = request.getConversationData().get(COLOR_KEY).toString();
    GoogleIdToken.Payload profile = getUserProfile(request.getUser().getIdToken());
    try {
      FirestoreManager firestoreManager =
          new FirestoreManager(DATABASE_URL, profile.getEmail());
      saveColor(firestoreManager, color);
    } catch (Exception e) {
      LOGGER.error(e.toString());
    }
    responseBuilder
        .add("I saved " + color + " as your favorite color for next time.")
        .endConversation();
  } else {
    responseBuilder.add("Let's try again next time");
  }
  LOGGER.info("Get sign in intent end.");
  return responseBuilder.build();
}

private void saveColor(FirestoreManager firestoreManager, String color) {
  try {
    Timestamp updateTime = firestoreManager.writeUserColor(color);
    LOGGER.info(String.format("Update time: %s", updateTime.toString()));
  } catch (Exception e) {
    LOGGER.error(e.toString());
  }
}