Sample code for 30+ languages & platforms
Zig

Get Google API Access Token using P12 Service Account Key

See more Google APIs Examples

Demonstrates how to get a Google API access token using a P12 service account key.

Chilkat Zig Downloads

Zig
const std = @import("std");
const chilkat = @import("chilkat");

pub fn main(init: std.process.Init) !void {
    const alloc = init.arena.allocator();

    // This example requires the Chilkat API to have been previously unlocked.
    // See Global Unlock Sample for sample code.

    // --------------------------------------------------------------------------------
    // For a step-by-step guide for setting up your Google Workspace service account,
    // see Setup Google Workspace Account for Sending SMTP GMail from a Service Account
    // --------------------------------------------------------------------------------

    // First load the PKCS12 (.p12 / .pfx) into a PFX object.
    const pfx = try chilkat.Pfx.init();
    defer pfx.deinit();
    pfx.loadPfxFile("qa_data/pfx/chilkat25-cbd7b42afbd8.p12", "notasecret") catch {
        std.debug.print("{s}\n", .{try pfx.getLastErrorText(alloc)});
        return;
    };

    const g_auth = try chilkat.AuthGoogle.init();
    defer g_auth.deinit();
    try g_auth.setP12(pfx);

    // The ISS is your service account email address ending in gserviceaccount.com.
    const iss = "chilkatsvc@chilkat25.iam.gserviceaccount.com";

    // The scope is always the following string:
    const scope = "https://mail.google.com/";

    // The sub is your company email address
    const oauth_sub = "info@chilkat.xyz";

    // The access token is valid for this number of seconds.
    const num_sec = 3600;

    g_auth.setEmailAddress(iss);
    g_auth.setScope(scope);
    g_auth.setExpireNumSeconds(num_sec);
    g_auth.setSubEmailAddress(oauth_sub);

    // Connect to www.googleapis.com
    const tls_sock = try chilkat.Socket.init();
    defer tls_sock.deinit();
    tls_sock.connect("www.googleapis.com", 443, true, 5000) catch {
        std.debug.print("{s}\n", .{try tls_sock.getLastErrorText(alloc)});
        return;
    };

    // Send the request to obtain the access token.
    g_auth.obtainAccessToken(tls_sock) catch {
        std.debug.print("{s}\n", .{try g_auth.getLastErrorText(alloc)});
        return;
    };

    // Examine the access token:
    std.debug.print("Access Token: {s}\n", .{try g_auth.getAccessToken(alloc)});
}