Sample code for 30+ languages & platforms
SQL Server Requires Chilkat v11.6.0+

OneDrive: Obtain and Refresh a SharePoint Transfer Token

See more OneDrive Examples

Obtain and refresh a delegated SharePoint Online access token for the OneDrive download, upload-session, version-download, and copy-monitor examples. This is for Microsoft 365 work/school accounts, not personal OneDrive. It saves qa_data/tokens/oneDrive-sharepoint.json with the exact host and access_token those transfer examples read, plus a refresh token, lifetime, acquisition time, and cache context. The Graph cache oneDrive.json remains separate.

Register a public application in Microsoft Entra, select the intended organizational account type, and add http://localhost:3017/ as a Mobile and desktop applications redirect URI. Set tenantId to the Directory (tenant) GUID and clientId to the Application (client) ID. Add the appropriate SharePoint delegated permissions in API permissions: use MyFiles.Read for reading the user's files or MyFiles.Write for writing them; use AllSites.Read or AllSites.Write where broader SharePoint site access is needed. Select only the permissions required and obtain consent as tenant policy requires. The user's actual access still applies. Graph permissions alone do not establish this SharePoint grant.

Set sharepointHost from trusted configuration: typically tenant.sharepoint.com for SharePoint libraries or tenant-my.sharepoint.com for the user's business OneDrive. Use the exact host expected by the transfer examples, without a scheme, path, port, or wildcard. This global-cloud example requests https://{host}/.default, which uses configured, consented SharePoint permissions, plus offline_access during authorization. Do not combine .default with dynamic API permission scopes. If newly configured permissions are not already consented, arrange renewed consent; refreshing does not grant them. How .default consent works.

Run action="authorize" for initial PKCE browser sign-in, choosing the same intended user as the Graph workflow. This explicitly replaces an existing cache after validation and backup. Change to action="refresh" for unattended renewal before obtained_at plus expires_in, allowing a safety margin. Refresh sends an explicit SharePoint resource scope and never opens a browser automatically. It saves a rotated refresh token, or retains the previous one when omitted. Revocation, Conditional Access, invalid_grant, or interaction requirements can require a new sign-in.

The local accountKey is an application-defined cache key, not a verified identity claim. The refresh branch requires matching host, tenant, client, account key, and resource scope before sending credentials. Use separate protected caches for different contexts and update the transfer cache path accordingly. Existing hand-written caches without the refresh/context fields need authorize. Do not decode an access token and assume its internal format or audience claim is a stable client contract.

Only validated responses replace the cache. A checked private backup supports recovery; production applications should serialize refreshes and commit credentials atomically in protected storage. Neither token is printed. A loopback listener is required only for initial sign-in; no hosted web server is needed. This is not certificate-based application access, which obtains new tokens through client credentials and has no refresh token.

OneDrive transfer authentication guide. Microsoft's SharePoint delegated permission overview.

Permission: Configured SharePoint delegated permissions and offline_access.

Check the expected HTTP status before using a response body. A false method result can still contain an HTTP error response; status zero means no response arrived. For 401, renew authorization; for 403, check permissions, access grants, and policy; for 429, honor Retry-After with a bounded retry. Reconcile uncertain writes before repeating them. Keep credentials, file contents, upload/download URLs, and detailed diagnostics private.

Microsoft documentation

Chilkat SQL Server Downloads

SQL Server
-- Important: See this note about string length limitations for strings returned by sp_OAMethod calls.
--
CREATE PROCEDURE ChilkatSample
AS
BEGIN
    DECLARE @hr int
    DECLARE @iTmp0 int
    DECLARE @iTmp1 int
    DECLARE @sTmp0 nvarchar(4000)
    DECLARE @success int
    SELECT @success = 0

    --  Assumes Chilkat is unlocked. See Global Unlock Sample.
    SELECT @success = 0
    --  Run authorize once; change to refresh for subsequent unattended renewals.
    DECLARE @action nvarchar(4000)
    SELECT @action = 'authorize'
    DECLARE @tenantId nvarchar(4000)
    SELECT @tenantId = 'YOUR_TENANT_ID'
    DECLARE @clientId nvarchar(4000)
    SELECT @clientId = 'YOUR_APPLICATION_CLIENT_ID'
    --  A trusted bare hostname, e.g. tenant.sharepoint.com or tenant-my.sharepoint.com.
    --  Configure the exact host used by the intended transfer; do not copy an untrusted URL here.
    DECLARE @sharepointHost nvarchar(4000)
    SELECT @sharepointHost = 'YOUR_TENANT.sharepoint.com'
    --  An application-defined key for this user/account, not an access token or password.
    DECLARE @accountKey nvarchar(4000)
    SELECT @accountKey = 'YOUR_LOCAL_ACCOUNT_KEY'
    DECLARE @cachePath nvarchar(4000)
    SELECT @cachePath = 'qa_data/tokens/oneDrive-sharepoint.json'
    DECLARE @backupPath nvarchar(4000)
    SELECT @backupPath = 'qa_data/tokens/oneDrive-sharepoint.json.bak'
    IF (@action <> 'authorize') and (@action <> 'refresh')
      BEGIN

        PRINT 'Choose authorize or refresh.'
        RETURN
      END
    DECLARE @host int
    EXEC @hr = sp_OACreate 'Chilkat.StringBuilder', @host OUT
    IF @hr <> 0
    BEGIN
        PRINT 'Failed to create ActiveX component'
        RETURN
    END

    EXEC sp_OAMethod @host, 'Append', @success OUT, @sharepointHost
    DECLARE @match int
    EXEC @hr = sp_OACreate 'Chilkat.JsonObject', @match OUT

    DECLARE @matched int
    EXEC sp_OAMethod @host, 'RegexMatch', @matched OUT, '(?i)\A[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.sharepoint\.com\z', @match, 100
    IF @matched <> 1
      BEGIN

        PRINT 'Set the trusted SharePoint hostname for this global-cloud example, without a scheme, path, or port.'
        EXEC @hr = sp_OADestroy @host
        EXEC @hr = sp_OADestroy @match
        RETURN
      END
    --  Use the organization's Directory (tenant) ID, not common, organizations, or consumers.
    DECLARE @tenant int
    EXEC @hr = sp_OACreate 'Chilkat.StringBuilder', @tenant OUT

    EXEC sp_OAMethod @tenant, 'Append', @success OUT, @tenantId
    EXEC sp_OAMethod @tenant, 'RegexMatch', @matched OUT, '(?i)\A[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\z', @match, 100
    IF @matched <> 1
      BEGIN

        PRINT 'Set the organization tenant GUID before running.'
        EXEC @hr = sp_OADestroy @host
        EXEC @hr = sp_OADestroy @match
        EXEC @hr = sp_OADestroy @tenant
        RETURN
      END
    DECLARE @http int
    EXEC @hr = sp_OACreate 'Chilkat.Http', @http OUT

    EXEC sp_OASetProperty @http, 'RequireSslCertVerify', 1
    EXEC sp_OASetProperty @http, 'FollowRedirects', 0
    EXEC sp_OASetProperty @http, 'ConnectTimeout', 20
    EXEC sp_OASetProperty @http, 'ReadTimeout', 30
    DECLARE @tokenEndpoint int
    EXEC @hr = sp_OACreate 'Chilkat.StringBuilder', @tokenEndpoint OUT

    EXEC sp_OAMethod @tokenEndpoint, 'Append', @success OUT, 'https://login.microsoftonline.com/'
    EXEC sp_OAMethod @http, 'UrlEncode', @sTmp0 OUT, @tenantId
    EXEC sp_OAMethod @tokenEndpoint, 'Append', @success OUT, @sTmp0
    EXEC sp_OAMethod @tokenEndpoint, 'Append', @success OUT, '/oauth2/v2.0/token'
    DECLARE @authorizeEndpoint int
    EXEC @hr = sp_OACreate 'Chilkat.StringBuilder', @authorizeEndpoint OUT

    EXEC sp_OAMethod @authorizeEndpoint, 'Append', @success OUT, 'https://login.microsoftonline.com/'
    EXEC sp_OAMethod @http, 'UrlEncode', @sTmp0 OUT, @tenantId
    EXEC sp_OAMethod @authorizeEndpoint, 'Append', @success OUT, @sTmp0
    EXEC sp_OAMethod @authorizeEndpoint, 'Append', @success OUT, '/oauth2/v2.0/authorize'
    DECLARE @scopeBuilder int
    EXEC @hr = sp_OACreate 'Chilkat.StringBuilder', @scopeBuilder OUT

    EXEC sp_OAMethod @scopeBuilder, 'Append', @success OUT, 'https://'
    EXEC sp_OAMethod @scopeBuilder, 'Append', @success OUT, @sharepointHost
    EXEC sp_OAMethod @scopeBuilder, 'Append', @success OUT, '/.default'
    DECLARE @resourceScope nvarchar(4000)
    EXEC sp_OAMethod @scopeBuilder, 'GetAsString', @resourceScope OUT
    DECLARE @fac int
    EXEC @hr = sp_OACreate 'Chilkat.FileAccess', @fac OUT

    DECLARE @hadCache int
    EXEC sp_OAMethod @fac, 'FileExists', @hadCache OUT, @cachePath
    DECLARE @previous int
    EXEC @hr = sp_OACreate 'Chilkat.JsonObject', @previous OUT

    EXEC sp_OASetProperty @previous, 'Strict', 1
    IF @hadCache = 1
      BEGIN
        EXEC sp_OAMethod @previous, 'LoadFile', @success OUT, @cachePath
        IF @success <> 1
          BEGIN

            PRINT 'Invalid existing cache; recover its private backup before continuing.'
            EXEC @hr = sp_OADestroy @host
            EXEC @hr = sp_OADestroy @match
            EXEC @hr = sp_OADestroy @tenant
            EXEC @hr = sp_OADestroy @http
            EXEC @hr = sp_OADestroy @tokenEndpoint
            EXEC @hr = sp_OADestroy @authorizeEndpoint
            EXEC @hr = sp_OADestroy @scopeBuilder
            EXEC @hr = sp_OADestroy @fac
            EXEC @hr = sp_OADestroy @previous
            RETURN
          END
      END
    DECLARE @result int
    EXEC @hr = sp_OACreate 'Chilkat.JsonObject', @result OUT

    EXEC sp_OASetProperty @result, 'Strict', 1
    IF @action = 'authorize'
      BEGIN
        --  Register http://localhost:3017/ as a Mobile and desktop applications redirect URI.
        DECLARE @oauth int
        EXEC @hr = sp_OACreate 'Chilkat.OAuth2', @oauth OUT

        EXEC sp_OAMethod @authorizeEndpoint, 'GetAsString', @sTmp0 OUT
        EXEC sp_OASetProperty @oauth, 'AuthorizationEndpoint', @sTmp0
        EXEC sp_OAMethod @tokenEndpoint, 'GetAsString', @sTmp0 OUT
        EXEC sp_OASetProperty @oauth, 'TokenEndpoint', @sTmp0
        EXEC sp_OASetProperty @oauth, 'ClientId', @clientId
        EXEC sp_OASetProperty @oauth, 'LocalHost', 'localhost'
        EXEC sp_OASetProperty @oauth, 'ListenPort', 3017
        EXEC sp_OASetProperty @oauth, 'CodeChallenge', 1
        EXEC sp_OASetProperty @oauth, 'CodeChallengeMethod', 'S256'
        --  No client secret in a public desktop application.
        DECLARE @scopes int
        EXEC @hr = sp_OACreate 'Chilkat.StringBuilder', @scopes OUT

        EXEC sp_OAMethod @scopes, 'Append', @success OUT, 'offline_access '
        EXEC sp_OAMethod @scopes, 'Append', @success OUT, @resourceScope
        EXEC sp_OAMethod @scopes, 'GetAsString', @sTmp0 OUT
        EXEC sp_OASetProperty @oauth, 'Scope', @sTmp0
        EXEC sp_OAMethod @oauth, 'AddAuthQueryParam', @success OUT, 'prompt', 'select_account'
        IF @success <> 1
          BEGIN

            PRINT 'Could not configure the authorization request.'
            EXEC @hr = sp_OADestroy @host
            EXEC @hr = sp_OADestroy @match
            EXEC @hr = sp_OADestroy @tenant
            EXEC @hr = sp_OADestroy @http
            EXEC @hr = sp_OADestroy @tokenEndpoint
            EXEC @hr = sp_OADestroy @authorizeEndpoint
            EXEC @hr = sp_OADestroy @scopeBuilder
            EXEC @hr = sp_OADestroy @fac
            EXEC @hr = sp_OADestroy @previous
            EXEC @hr = sp_OADestroy @result
            EXEC @hr = sp_OADestroy @oauth
            EXEC @hr = sp_OADestroy @scopes
            RETURN
          END
        DECLARE @authUrl nvarchar(4000)
        EXEC sp_OAMethod @oauth, 'StartAuth', @authUrl OUT
        EXEC sp_OAGetProperty @oauth, 'LastMethodSuccess', @iTmp0 OUT
        IF @iTmp0 <> 1
          BEGIN

            PRINT 'Could not start the local authorization listener.'
            EXEC @hr = sp_OADestroy @host
            EXEC @hr = sp_OADestroy @match
            EXEC @hr = sp_OADestroy @tenant
            EXEC @hr = sp_OADestroy @http
            EXEC @hr = sp_OADestroy @tokenEndpoint
            EXEC @hr = sp_OADestroy @authorizeEndpoint
            EXEC @hr = sp_OADestroy @scopeBuilder
            EXEC @hr = sp_OADestroy @fac
            EXEC @hr = sp_OADestroy @previous
            EXEC @hr = sp_OADestroy @result
            EXEC @hr = sp_OADestroy @oauth
            EXEC @hr = sp_OADestroy @scopes
            RETURN
          END
        EXEC sp_OAMethod @oauth, 'LaunchBrowser', @success OUT, @authUrl
        IF @success <> 1
          BEGIN
            EXEC sp_OAMethod @oauth, 'Cancel', @success OUT

            PRINT 'Could not open the system browser.'
            EXEC @hr = sp_OADestroy @host
            EXEC @hr = sp_OADestroy @match
            EXEC @hr = sp_OADestroy @tenant
            EXEC @hr = sp_OADestroy @http
            EXEC @hr = sp_OADestroy @tokenEndpoint
            EXEC @hr = sp_OADestroy @authorizeEndpoint
            EXEC @hr = sp_OADestroy @scopeBuilder
            EXEC @hr = sp_OADestroy @fac
            EXEC @hr = sp_OADestroy @previous
            EXEC @hr = sp_OADestroy @result
            EXEC @hr = sp_OADestroy @oauth
            EXEC @hr = sp_OADestroy @scopes
            RETURN
          END
        DECLARE @waited int
        SELECT @waited = 0
        EXEC sp_OAGetProperty @oauth, 'AuthFlowState', @iTmp0 OUT
        WHILE ((@iTmp0 < 3) and (@waited < 180000))
          BEGIN
            EXEC sp_OAMethod @oauth, 'SleepMs', NULL, 200
            SELECT @waited = @waited + 200
          END
        EXEC sp_OAGetProperty @oauth, 'AuthFlowState', @iTmp0 OUT
        IF @iTmp0 < 3
          BEGIN
            EXEC sp_OAMethod @oauth, 'Cancel', @success OUT

            PRINT 'Authorization timed out.'
            EXEC @hr = sp_OADestroy @host
            EXEC @hr = sp_OADestroy @match
            EXEC @hr = sp_OADestroy @tenant
            EXEC @hr = sp_OADestroy @http
            EXEC @hr = sp_OADestroy @tokenEndpoint
            EXEC @hr = sp_OADestroy @authorizeEndpoint
            EXEC @hr = sp_OADestroy @scopeBuilder
            EXEC @hr = sp_OADestroy @fac
            EXEC @hr = sp_OADestroy @previous
            EXEC @hr = sp_OADestroy @result
            EXEC @hr = sp_OADestroy @oauth
            EXEC @hr = sp_OADestroy @scopes
            RETURN
          END
        EXEC sp_OAGetProperty @oauth, 'AuthFlowState', @iTmp0 OUT
        IF @iTmp0 <> 3
          BEGIN

            EXEC sp_OAGetProperty @oauth, 'AuthFlowState', @iTmp0 OUT
            PRINT 'Authorization did not complete. Flow state: ' + @iTmp0
            EXEC @hr = sp_OADestroy @host
            EXEC @hr = sp_OADestroy @match
            EXEC @hr = sp_OADestroy @tenant
            EXEC @hr = sp_OADestroy @http
            EXEC @hr = sp_OADestroy @tokenEndpoint
            EXEC @hr = sp_OADestroy @authorizeEndpoint
            EXEC @hr = sp_OADestroy @scopeBuilder
            EXEC @hr = sp_OADestroy @fac
            EXEC @hr = sp_OADestroy @previous
            EXEC @hr = sp_OADestroy @result
            EXEC @hr = sp_OADestroy @oauth
            EXEC @hr = sp_OADestroy @scopes
            RETURN
          END
        EXEC sp_OAGetProperty @oauth, 'AccessTokenResponse', @sTmp0 OUT
        EXEC sp_OAMethod @result, 'Load', @success OUT, @sTmp0
        IF @success <> 1
          BEGIN

            PRINT 'Invalid token response; existing cache unchanged.'
            EXEC @hr = sp_OADestroy @host
            EXEC @hr = sp_OADestroy @match
            EXEC @hr = sp_OADestroy @tenant
            EXEC @hr = sp_OADestroy @http
            EXEC @hr = sp_OADestroy @tokenEndpoint
            EXEC @hr = sp_OADestroy @authorizeEndpoint
            EXEC @hr = sp_OADestroy @scopeBuilder
            EXEC @hr = sp_OADestroy @fac
            EXEC @hr = sp_OADestroy @previous
            EXEC @hr = sp_OADestroy @result
            EXEC @hr = sp_OADestroy @oauth
            EXEC @hr = sp_OADestroy @scopes
            RETURN
          END
        EXEC sp_OAMethod @result, 'JsonTypeOf', @iTmp0 OUT, 'refresh_token'
        EXEC sp_OAMethod @result, 'StringOfEquals', @iTmp1 OUT, 'refresh_token', '', 1
        IF (@iTmp0 <> 1) or (@iTmp1 = 1)
          BEGIN

            PRINT 'Expected a nonempty refresh_token in the JSON.'
            EXEC @hr = sp_OADestroy @host
            EXEC @hr = sp_OADestroy @match
            EXEC @hr = sp_OADestroy @tenant
            EXEC @hr = sp_OADestroy @http
            EXEC @hr = sp_OADestroy @tokenEndpoint
            EXEC @hr = sp_OADestroy @authorizeEndpoint
            EXEC @hr = sp_OADestroy @scopeBuilder
            EXEC @hr = sp_OADestroy @fac
            EXEC @hr = sp_OADestroy @previous
            EXEC @hr = sp_OADestroy @result
            EXEC @hr = sp_OADestroy @oauth
            EXEC @hr = sp_OADestroy @scopes
            RETURN
          END
      END
    ELSE
      BEGIN
        IF @hadCache <> 1
          BEGIN

            PRINT 'No SharePoint token cache. Run authorize first.'
            EXEC @hr = sp_OADestroy @host
            EXEC @hr = sp_OADestroy @match
            EXEC @hr = sp_OADestroy @tenant
            EXEC @hr = sp_OADestroy @http
            EXEC @hr = sp_OADestroy @tokenEndpoint
            EXEC @hr = sp_OADestroy @authorizeEndpoint
            EXEC @hr = sp_OADestroy @scopeBuilder
            EXEC @hr = sp_OADestroy @fac
            EXEC @hr = sp_OADestroy @previous
            EXEC @hr = sp_OADestroy @result
            EXEC @hr = sp_OADestroy @oauth
            EXEC @hr = sp_OADestroy @scopes
            RETURN
          END
        EXEC sp_OAMethod @previous, 'StringOfEquals', @iTmp0 OUT, 'host', @sharepointHost, 1
        IF @iTmp0 <> 1
          BEGIN

            PRINT 'Cache context differs from the configured host, tenant, app, or account. Authorize deliberately or use a separate cache.'
            EXEC @hr = sp_OADestroy @host
            EXEC @hr = sp_OADestroy @match
            EXEC @hr = sp_OADestroy @tenant
            EXEC @hr = sp_OADestroy @http
            EXEC @hr = sp_OADestroy @tokenEndpoint
            EXEC @hr = sp_OADestroy @authorizeEndpoint
            EXEC @hr = sp_OADestroy @scopeBuilder
            EXEC @hr = sp_OADestroy @fac
            EXEC @hr = sp_OADestroy @previous
            EXEC @hr = sp_OADestroy @result
            EXEC @hr = sp_OADestroy @oauth
            EXEC @hr = sp_OADestroy @scopes
            RETURN
          END
        EXEC sp_OAMethod @previous, 'StringOfEquals', @iTmp0 OUT, 'tenant_id', @tenantId, 1
        IF @iTmp0 <> 1
          BEGIN

            PRINT 'Cache context differs from the configured host, tenant, app, or account. Authorize deliberately or use a separate cache.'
            EXEC @hr = sp_OADestroy @host
            EXEC @hr = sp_OADestroy @match
            EXEC @hr = sp_OADestroy @tenant
            EXEC @hr = sp_OADestroy @http
            EXEC @hr = sp_OADestroy @tokenEndpoint
            EXEC @hr = sp_OADestroy @authorizeEndpoint
            EXEC @hr = sp_OADestroy @scopeBuilder
            EXEC @hr = sp_OADestroy @fac
            EXEC @hr = sp_OADestroy @previous
            EXEC @hr = sp_OADestroy @result
            EXEC @hr = sp_OADestroy @oauth
            EXEC @hr = sp_OADestroy @scopes
            RETURN
          END
        EXEC sp_OAMethod @previous, 'StringOfEquals', @iTmp0 OUT, 'client_id', @clientId, 1
        IF @iTmp0 <> 1
          BEGIN

            PRINT 'Cache context differs from the configured host, tenant, app, or account. Authorize deliberately or use a separate cache.'
            EXEC @hr = sp_OADestroy @host
            EXEC @hr = sp_OADestroy @match
            EXEC @hr = sp_OADestroy @tenant
            EXEC @hr = sp_OADestroy @http
            EXEC @hr = sp_OADestroy @tokenEndpoint
            EXEC @hr = sp_OADestroy @authorizeEndpoint
            EXEC @hr = sp_OADestroy @scopeBuilder
            EXEC @hr = sp_OADestroy @fac
            EXEC @hr = sp_OADestroy @previous
            EXEC @hr = sp_OADestroy @result
            EXEC @hr = sp_OADestroy @oauth
            EXEC @hr = sp_OADestroy @scopes
            RETURN
          END
        EXEC sp_OAMethod @previous, 'StringOfEquals', @iTmp0 OUT, 'account_key', @accountKey, 1
        IF @iTmp0 <> 1
          BEGIN

            PRINT 'Cache context differs from the configured host, tenant, app, or account. Authorize deliberately or use a separate cache.'
            EXEC @hr = sp_OADestroy @host
            EXEC @hr = sp_OADestroy @match
            EXEC @hr = sp_OADestroy @tenant
            EXEC @hr = sp_OADestroy @http
            EXEC @hr = sp_OADestroy @tokenEndpoint
            EXEC @hr = sp_OADestroy @authorizeEndpoint
            EXEC @hr = sp_OADestroy @scopeBuilder
            EXEC @hr = sp_OADestroy @fac
            EXEC @hr = sp_OADestroy @previous
            EXEC @hr = sp_OADestroy @result
            EXEC @hr = sp_OADestroy @oauth
            EXEC @hr = sp_OADestroy @scopes
            RETURN
          END
        EXEC sp_OAMethod @previous, 'StringOfEquals', @iTmp0 OUT, 'resource_scope', @resourceScope, 1
        IF @iTmp0 <> 1
          BEGIN

            PRINT 'Cache context differs from the configured host, tenant, app, or account. Authorize deliberately or use a separate cache.'
            EXEC @hr = sp_OADestroy @host
            EXEC @hr = sp_OADestroy @match
            EXEC @hr = sp_OADestroy @tenant
            EXEC @hr = sp_OADestroy @http
            EXEC @hr = sp_OADestroy @tokenEndpoint
            EXEC @hr = sp_OADestroy @authorizeEndpoint
            EXEC @hr = sp_OADestroy @scopeBuilder
            EXEC @hr = sp_OADestroy @fac
            EXEC @hr = sp_OADestroy @previous
            EXEC @hr = sp_OADestroy @result
            EXEC @hr = sp_OADestroy @oauth
            EXEC @hr = sp_OADestroy @scopes
            RETURN
          END
        EXEC sp_OAMethod @previous, 'JsonTypeOf', @iTmp0 OUT, 'refresh_token'
        EXEC sp_OAMethod @previous, 'StringOfEquals', @iTmp1 OUT, 'refresh_token', '', 1
        IF (@iTmp0 <> 1) or (@iTmp1 = 1)
          BEGIN

            PRINT 'Expected a nonempty refresh_token in the JSON.'
            EXEC @hr = sp_OADestroy @host
            EXEC @hr = sp_OADestroy @match
            EXEC @hr = sp_OADestroy @tenant
            EXEC @hr = sp_OADestroy @http
            EXEC @hr = sp_OADestroy @tokenEndpoint
            EXEC @hr = sp_OADestroy @authorizeEndpoint
            EXEC @hr = sp_OADestroy @scopeBuilder
            EXEC @hr = sp_OADestroy @fac
            EXEC @hr = sp_OADestroy @previous
            EXEC @hr = sp_OADestroy @result
            EXEC @hr = sp_OADestroy @oauth
            EXEC @hr = sp_OADestroy @scopes
            RETURN
          END
        DECLARE @req int
        EXEC @hr = sp_OACreate 'Chilkat.HttpRequest', @req OUT

        EXEC sp_OASetProperty @req, 'HttpVerb', 'POST'
        EXEC sp_OASetProperty @req, 'ContentType', 'application/x-www-form-urlencoded'
        EXEC sp_OAMethod @req, 'AddParam', NULL, 'client_id', @clientId
        EXEC sp_OAMethod @req, 'AddParam', NULL, 'grant_type', 'refresh_token'
        EXEC sp_OAMethod @previous, 'StringOf', @sTmp0 OUT, 'refresh_token'
        EXEC sp_OAMethod @req, 'AddParam', NULL, 'refresh_token', @sTmp0
        --  Explicit resource scope keeps the renewal on SharePoint, not Microsoft Graph.
        EXEC sp_OAMethod @req, 'AddParam', NULL, 'scope', @resourceScope
        DECLARE @resp int
        EXEC @hr = sp_OACreate 'Chilkat.HttpResponse', @resp OUT

        EXEC sp_OAMethod @tokenEndpoint, 'GetAsString', @sTmp0 OUT
        EXEC sp_OAMethod @http, 'HttpReq', @success OUT, @sTmp0, @req, @resp
        EXEC sp_OAGetProperty @resp, 'StatusCode', @iTmp0 OUT
        IF (@success <> 1) and (@iTmp0 = 0)
          BEGIN

            PRINT 'No token response received; existing cache unchanged.'
            EXEC @hr = sp_OADestroy @host
            EXEC @hr = sp_OADestroy @match
            EXEC @hr = sp_OADestroy @tenant
            EXEC @hr = sp_OADestroy @http
            EXEC @hr = sp_OADestroy @tokenEndpoint
            EXEC @hr = sp_OADestroy @authorizeEndpoint
            EXEC @hr = sp_OADestroy @scopeBuilder
            EXEC @hr = sp_OADestroy @fac
            EXEC @hr = sp_OADestroy @previous
            EXEC @hr = sp_OADestroy @result
            EXEC @hr = sp_OADestroy @oauth
            EXEC @hr = sp_OADestroy @scopes
            EXEC @hr = sp_OADestroy @req
            EXEC @hr = sp_OADestroy @resp
            RETURN
          END
        EXEC sp_OAGetProperty @resp, 'StatusCode', @iTmp0 OUT
        IF @iTmp0 <> 200
          BEGIN

            EXEC sp_OAGetProperty @resp, 'StatusCode', @iTmp0 OUT
            PRINT 'Token renewal failed. HTTP status: ' + @iTmp0
            EXEC sp_OAGetProperty @resp, 'StatusCode', @iTmp0 OUT
            IF @iTmp0 = 429
              BEGIN

                EXEC sp_OAMethod @resp, 'GetHeaderField', @sTmp0 OUT, 'Retry-After'
                PRINT 'Retry-After: ' + @sTmp0
              END

            PRINT 'Check consent and token validity. If interaction is required, run authorize deliberately.'
            EXEC @hr = sp_OADestroy @host
            EXEC @hr = sp_OADestroy @match
            EXEC @hr = sp_OADestroy @tenant
            EXEC @hr = sp_OADestroy @http
            EXEC @hr = sp_OADestroy @tokenEndpoint
            EXEC @hr = sp_OADestroy @authorizeEndpoint
            EXEC @hr = sp_OADestroy @scopeBuilder
            EXEC @hr = sp_OADestroy @fac
            EXEC @hr = sp_OADestroy @previous
            EXEC @hr = sp_OADestroy @result
            EXEC @hr = sp_OADestroy @oauth
            EXEC @hr = sp_OADestroy @scopes
            EXEC @hr = sp_OADestroy @req
            EXEC @hr = sp_OADestroy @resp
            RETURN
          END
        IF @success <> 1
          BEGIN

            PRINT 'Token response did not complete; existing cache unchanged.'
            EXEC @hr = sp_OADestroy @host
            EXEC @hr = sp_OADestroy @match
            EXEC @hr = sp_OADestroy @tenant
            EXEC @hr = sp_OADestroy @http
            EXEC @hr = sp_OADestroy @tokenEndpoint
            EXEC @hr = sp_OADestroy @authorizeEndpoint
            EXEC @hr = sp_OADestroy @scopeBuilder
            EXEC @hr = sp_OADestroy @fac
            EXEC @hr = sp_OADestroy @previous
            EXEC @hr = sp_OADestroy @result
            EXEC @hr = sp_OADestroy @oauth
            EXEC @hr = sp_OADestroy @scopes
            EXEC @hr = sp_OADestroy @req
            EXEC @hr = sp_OADestroy @resp
            RETURN
          END
        EXEC sp_OAGetProperty @resp, 'BodyStr', @sTmp0 OUT
        EXEC sp_OAMethod @result, 'Load', @success OUT, @sTmp0
        IF @success <> 1
          BEGIN

            PRINT 'Invalid refresh response; existing cache unchanged.'
            EXEC @hr = sp_OADestroy @host
            EXEC @hr = sp_OADestroy @match
            EXEC @hr = sp_OADestroy @tenant
            EXEC @hr = sp_OADestroy @http
            EXEC @hr = sp_OADestroy @tokenEndpoint
            EXEC @hr = sp_OADestroy @authorizeEndpoint
            EXEC @hr = sp_OADestroy @scopeBuilder
            EXEC @hr = sp_OADestroy @fac
            EXEC @hr = sp_OADestroy @previous
            EXEC @hr = sp_OADestroy @result
            EXEC @hr = sp_OADestroy @oauth
            EXEC @hr = sp_OADestroy @scopes
            EXEC @hr = sp_OADestroy @req
            EXEC @hr = sp_OADestroy @resp
            RETURN
          END
        EXEC sp_OAMethod @result, 'JsonTypeOf', @iTmp0 OUT, 'refresh_token'
        IF @iTmp0 = -1
          BEGIN
            EXEC sp_OAMethod @previous, 'StringOf', @sTmp0 OUT, 'refresh_token'
            EXEC sp_OAMethod @result, 'UpdateString', @success OUT, 'refresh_token', @sTmp0
          END
        ELSE
          BEGIN
            EXEC sp_OAMethod @result, 'JsonTypeOf', @iTmp0 OUT, 'refresh_token'
            EXEC sp_OAMethod @result, 'StringOfEquals', @iTmp1 OUT, 'refresh_token', '', 1
            IF (@iTmp0 <> 1) or (@iTmp1 = 1)
              BEGIN

                PRINT 'Expected a nonempty refresh_token in the JSON.'
                EXEC @hr = sp_OADestroy @host
                EXEC @hr = sp_OADestroy @match
                EXEC @hr = sp_OADestroy @tenant
                EXEC @hr = sp_OADestroy @http
                EXEC @hr = sp_OADestroy @tokenEndpoint
                EXEC @hr = sp_OADestroy @authorizeEndpoint
                EXEC @hr = sp_OADestroy @scopeBuilder
                EXEC @hr = sp_OADestroy @fac
                EXEC @hr = sp_OADestroy @previous
                EXEC @hr = sp_OADestroy @result
                EXEC @hr = sp_OADestroy @oauth
                EXEC @hr = sp_OADestroy @scopes
                EXEC @hr = sp_OADestroy @req
                EXEC @hr = sp_OADestroy @resp
                RETURN
              END
          END
      END
    EXEC sp_OAMethod @result, 'JsonTypeOf', @iTmp0 OUT, 'access_token'
    EXEC sp_OAMethod @result, 'StringOfEquals', @iTmp1 OUT, 'access_token', '', 1
    IF (@iTmp0 <> 1) or (@iTmp1 = 1)
      BEGIN

        PRINT 'Expected a nonempty access_token in the JSON.'
        EXEC @hr = sp_OADestroy @host
        EXEC @hr = sp_OADestroy @match
        EXEC @hr = sp_OADestroy @tenant
        EXEC @hr = sp_OADestroy @http
        EXEC @hr = sp_OADestroy @tokenEndpoint
        EXEC @hr = sp_OADestroy @authorizeEndpoint
        EXEC @hr = sp_OADestroy @scopeBuilder
        EXEC @hr = sp_OADestroy @fac
        EXEC @hr = sp_OADestroy @previous
        EXEC @hr = sp_OADestroy @result
        EXEC @hr = sp_OADestroy @oauth
        EXEC @hr = sp_OADestroy @scopes
        EXEC @hr = sp_OADestroy @req
        EXEC @hr = sp_OADestroy @resp
        RETURN
      END
    EXEC sp_OAMethod @result, 'JsonTypeOf', @iTmp0 OUT, 'expires_in'
    EXEC sp_OAMethod @result, 'IntOf', @iTmp1 OUT, 'expires_in'
    IF (@iTmp0 <> 2) or (@iTmp1 <= 0)
      BEGIN

        PRINT 'Expected a positive access-token lifetime; existing cache unchanged.'
        EXEC @hr = sp_OADestroy @host
        EXEC @hr = sp_OADestroy @match
        EXEC @hr = sp_OADestroy @tenant
        EXEC @hr = sp_OADestroy @http
        EXEC @hr = sp_OADestroy @tokenEndpoint
        EXEC @hr = sp_OADestroy @authorizeEndpoint
        EXEC @hr = sp_OADestroy @scopeBuilder
        EXEC @hr = sp_OADestroy @fac
        EXEC @hr = sp_OADestroy @previous
        EXEC @hr = sp_OADestroy @result
        EXEC @hr = sp_OADestroy @oauth
        EXEC @hr = sp_OADestroy @scopes
        EXEC @hr = sp_OADestroy @req
        EXEC @hr = sp_OADestroy @resp
        RETURN
      END
    EXEC sp_OAMethod @result, 'StringOfEquals', @iTmp0 OUT, 'token_type', 'Bearer', 0
    IF @iTmp0 <> 1
      BEGIN

        PRINT 'Expected a bearer access token; existing cache unchanged.'
        EXEC @hr = sp_OADestroy @host
        EXEC @hr = sp_OADestroy @match
        EXEC @hr = sp_OADestroy @tenant
        EXEC @hr = sp_OADestroy @http
        EXEC @hr = sp_OADestroy @tokenEndpoint
        EXEC @hr = sp_OADestroy @authorizeEndpoint
        EXEC @hr = sp_OADestroy @scopeBuilder
        EXEC @hr = sp_OADestroy @fac
        EXEC @hr = sp_OADestroy @previous
        EXEC @hr = sp_OADestroy @result
        EXEC @hr = sp_OADestroy @oauth
        EXEC @hr = sp_OADestroy @scopes
        EXEC @hr = sp_OADestroy @req
        EXEC @hr = sp_OADestroy @resp
        RETURN
      END
    DECLARE @obtained int
    EXEC @hr = sp_OACreate 'Chilkat.CkDateTime', @obtained OUT

    EXEC sp_OAMethod @obtained, 'SetFromCurrentSystemTime', @success OUT
    IF @success <> 1
      BEGIN

        PRINT 'Could not timestamp the access token.'
        EXEC @hr = sp_OADestroy @host
        EXEC @hr = sp_OADestroy @match
        EXEC @hr = sp_OADestroy @tenant
        EXEC @hr = sp_OADestroy @http
        EXEC @hr = sp_OADestroy @tokenEndpoint
        EXEC @hr = sp_OADestroy @authorizeEndpoint
        EXEC @hr = sp_OADestroy @scopeBuilder
        EXEC @hr = sp_OADestroy @fac
        EXEC @hr = sp_OADestroy @previous
        EXEC @hr = sp_OADestroy @result
        EXEC @hr = sp_OADestroy @oauth
        EXEC @hr = sp_OADestroy @scopes
        EXEC @hr = sp_OADestroy @req
        EXEC @hr = sp_OADestroy @resp
        EXEC @hr = sp_OADestroy @obtained
        RETURN
      END
    EXEC sp_OAMethod @obtained, 'GetAsTimestamp', @sTmp0 OUT, 0
    EXEC sp_OAMethod @result, 'UpdateString', @success OUT, 'obtained_at', @sTmp0
    --  The transfer examples read host and access_token; these extra fields bind future refreshes.
    EXEC sp_OAMethod @result, 'UpdateString', @success OUT, 'host', @sharepointHost
    EXEC sp_OAMethod @result, 'UpdateString', @success OUT, 'tenant_id', @tenantId
    EXEC sp_OAMethod @result, 'UpdateString', @success OUT, 'client_id', @clientId
    EXEC sp_OAMethod @result, 'UpdateString', @success OUT, 'account_key', @accountKey
    EXEC sp_OAMethod @result, 'UpdateString', @success OUT, 'resource_scope', @resourceScope
    EXEC sp_OAMethod @fac, 'DirEnsureExists', @success OUT, 'qa_data/tokens'
    IF @success <> 1
      BEGIN

        PRINT 'Could not create the private cache directory.'
        EXEC @hr = sp_OADestroy @host
        EXEC @hr = sp_OADestroy @match
        EXEC @hr = sp_OADestroy @tenant
        EXEC @hr = sp_OADestroy @http
        EXEC @hr = sp_OADestroy @tokenEndpoint
        EXEC @hr = sp_OADestroy @authorizeEndpoint
        EXEC @hr = sp_OADestroy @scopeBuilder
        EXEC @hr = sp_OADestroy @fac
        EXEC @hr = sp_OADestroy @previous
        EXEC @hr = sp_OADestroy @result
        EXEC @hr = sp_OADestroy @oauth
        EXEC @hr = sp_OADestroy @scopes
        EXEC @hr = sp_OADestroy @req
        EXEC @hr = sp_OADestroy @resp
        EXEC @hr = sp_OADestroy @obtained
        RETURN
      END
    IF @hadCache = 1
      BEGIN
        EXEC sp_OAMethod @previous, 'WriteFile', @success OUT, @backupPath
        IF @success <> 1
          BEGIN

            PRINT 'Could not back up the previous cache; no replacement attempted.'
            EXEC @hr = sp_OADestroy @host
            EXEC @hr = sp_OADestroy @match
            EXEC @hr = sp_OADestroy @tenant
            EXEC @hr = sp_OADestroy @http
            EXEC @hr = sp_OADestroy @tokenEndpoint
            EXEC @hr = sp_OADestroy @authorizeEndpoint
            EXEC @hr = sp_OADestroy @scopeBuilder
            EXEC @hr = sp_OADestroy @fac
            EXEC @hr = sp_OADestroy @previous
            EXEC @hr = sp_OADestroy @result
            EXEC @hr = sp_OADestroy @oauth
            EXEC @hr = sp_OADestroy @scopes
            EXEC @hr = sp_OADestroy @req
            EXEC @hr = sp_OADestroy @resp
            EXEC @hr = sp_OADestroy @obtained
            RETURN
          END
      END
    EXEC sp_OAMethod @result, 'WriteFile', @success OUT, @cachePath
    IF @success <> 1
      BEGIN

        PRINT 'Could not save the new cache; recover the private backup if an older cache existed.'
        EXEC @hr = sp_OADestroy @host
        EXEC @hr = sp_OADestroy @match
        EXEC @hr = sp_OADestroy @tenant
        EXEC @hr = sp_OADestroy @http
        EXEC @hr = sp_OADestroy @tokenEndpoint
        EXEC @hr = sp_OADestroy @authorizeEndpoint
        EXEC @hr = sp_OADestroy @scopeBuilder
        EXEC @hr = sp_OADestroy @fac
        EXEC @hr = sp_OADestroy @previous
        EXEC @hr = sp_OADestroy @result
        EXEC @hr = sp_OADestroy @oauth
        EXEC @hr = sp_OADestroy @scopes
        EXEC @hr = sp_OADestroy @req
        EXEC @hr = sp_OADestroy @resp
        EXEC @hr = sp_OADestroy @obtained
        RETURN
      END
    --  Never print the tokens, token response, or authorization URL.

    PRINT 'SharePoint token cache saved. The OneDrive transfer examples can now load it.'

    EXEC @hr = sp_OADestroy @host
    EXEC @hr = sp_OADestroy @match
    EXEC @hr = sp_OADestroy @tenant
    EXEC @hr = sp_OADestroy @http
    EXEC @hr = sp_OADestroy @tokenEndpoint
    EXEC @hr = sp_OADestroy @authorizeEndpoint
    EXEC @hr = sp_OADestroy @scopeBuilder
    EXEC @hr = sp_OADestroy @fac
    EXEC @hr = sp_OADestroy @previous
    EXEC @hr = sp_OADestroy @result
    EXEC @hr = sp_OADestroy @oauth
    EXEC @hr = sp_OADestroy @scopes
    EXEC @hr = sp_OADestroy @req
    EXEC @hr = sp_OADestroy @resp
    EXEC @hr = sp_OADestroy @obtained


END
GO