Sample code for 30+ languages & platforms
Zig Requires Chilkat v11.0.0+

Group: Refresh OAuth2 Access Token

See more Microsoft Group Examples

Refreshes an expired or non-expired OAuth2 access token for the Microsoft Group REST API.

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.

    const json = try chilkat.JsonObject.init();
    defer json.deinit();
    json.loadFile("qa_data/tokens/msGraphGroup.json") catch {
        return;
    };

    const req = try chilkat.HttpRequest.init();
    defer req.deinit();
    req.addParam("grant_type", "refresh_token");
    req.addParam("redirect_uri", "http://localhost:3017/");
    req.addParam("client_id", "MICROSOFT-GRAPH-CLIENT-ID");
    req.addParam("client_secret", "MICROSOFT-GRAPH-CLIENT-SECRET");
    req.addParam("refresh_token", try json.stringOf(alloc, "refresh_token"));
    req.addParam("scope", "openid profile offline_access user.readwrite group.readwrite.all files.readwrite");

    const http = try chilkat.Http.init();
    defer http.deinit();

    req.setHttpVerb("POST");
    req.setContentType("application/x-www-form-urlencoded");

    const resp = try chilkat.HttpResponse.init();
    defer resp.deinit();
    http.httpReq("https://login.microsoftonline.com/common/oauth2/v2.0/token", req, resp) catch {
        std.debug.print("{s}\n", .{try http.getLastErrorText(alloc)});
        return;
    };

    // Load the JSON response.
    json.load(try resp.getBodyStr(alloc)) catch {};
    json.setEmitCompact(false);

    // Show the JSON response.
    std.debug.print("{s}\n", .{try json.emit(alloc)});

    std.debug.print("Response status code: {d}\n", .{resp.getStatusCode()});

    // If the response status code is not 200, then it's an error.
    if (resp.getStatusCode() != 200) {
        return;
    }

    // Save the refreshed access token JSON to a file for future requests.
    const fac = try chilkat.FileAccess.init();
    defer fac.deinit();
    fac.writeEntireTextFile("qa_data/tokens/msGraphGroup.json", try json.emit(alloc), "utf-8", false) catch {};

    std.debug.print("Success.\n", .{});
}