Zig
Zig
Get Google Account Info from OAuth2 Access Token
See more Google APIs Examples
In the Google OAuth2 authorization flow, an application can know the email address of the Google account used to authorize access by requesting and processing user information from the Google UserInfo endpoint after obtaining an access token.Chilkat Zig Downloads
const std = @import("std");
const chilkat = @import("chilkat");
pub fn main(init: std.process.Init) !void {
const alloc = init.arena.allocator();
// This example assumes the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
const http = try chilkat.Http.init();
defer http.deinit();
// Implements the following CURL command:
// curl -H "Authorization: Bearer YOUR_ACCESS_TOKEN" https://www.googleapis.com/oauth2/v3/userinfo
// Use the following online tool to generate HTTP code from a CURL command
// Convert a cURL Command to HTTP Source Code
// Adds the "Authorization: Bearer YOUR_ACCESS_TOKEN" header.
http.setAuthToken("YOUR_ACCESS_TOKEN");
const sb_response_body = try chilkat.StringBuilder.init();
defer sb_response_body.deinit();
http.quickGetSb("https://www.googleapis.com/oauth2/v3/userinfo", sb_response_body) catch {
std.debug.print("{s}\n", .{try http.getLastErrorText(alloc)});
return;
};
const j_resp = try chilkat.JsonObject.init();
defer j_resp.deinit();
j_resp.loadSb(sb_response_body) catch {};
j_resp.setEmitCompact(false);
std.debug.print("Response Body:\n", .{});
std.debug.print("{s}\n", .{try j_resp.emit(alloc)});
const resp_status_code = http.getLastStatus();
std.debug.print("Response Status Code = {d}\n", .{resp_status_code});
if (resp_status_code >= 400) {
std.debug.print("Response Header:\n", .{});
std.debug.print("{s}\n", .{try http.getLastHeader(alloc)});
std.debug.print("Failed.\n", .{});
return;
}
// Sample JSON response:
// (Sample code for parsing the JSON response is shown below)
// {
// "sub": "112233445678901234567",
// "name": "John Doe",
// "given_name": "John",
// "family_name": "Doe",
// "profile": "https://plus.google.com/112233445678901234567",
// "picture": "https://lh3.googleusercontent.com/a-/AOh14GiU-EXAMPLE",
// "email": "johndoe@example.com",
// "email_verified": true,
// "locale": "en"
// }
// Sample code for parsing the JSON response...
// Use the following online tool to generate parsing code from sample JSON:
// Generate Parsing Code from JSON
_ = try j_resp.stringOf(alloc, "sub");
_ = try j_resp.stringOf(alloc, "name");
_ = try j_resp.stringOf(alloc, "given_name");
_ = try j_resp.stringOf(alloc, "family_name");
_ = try j_resp.stringOf(alloc, "profile");
_ = try j_resp.stringOf(alloc, "picture");
_ = try j_resp.stringOf(alloc, "email");
_ = j_resp.boolOf("email_verified");
_ = try j_resp.stringOf(alloc, "locale");
}