SQL Server
SQL Server
Get XOAUTH2 Access Token from Google OAuth 2.0 Authorization Server
See more HTTP Examples
Obtains an OAUTH2 access token from the Google OAuth 2.0 Authorization Server. This is for Server to server applications using Google API's that need an access token. See https://developers.google.com/accounts/docs/OAuth2ServiceAccountChilkat SQL Server Downloads
-- 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
-- Important: Do not use nvarchar(max). See the warning about using nvarchar(max).
DECLARE @sTmp0 nvarchar(4000)
DECLARE @success int
SELECT @success = 0
-- This example assumes the Chilkat API to have been previously unlocked.
-- See Global Unlock Sample for sample code.
DECLARE @http int
EXEC @hr = sp_OACreate 'Chilkat.Http', @http OUT
IF @hr <> 0
BEGIN
PRINT 'Failed to create ActiveX component'
RETURN
END
-- --------------------------------------------------------------------------------
-- 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
-- --------------------------------------------------------------------------------
-- Begin by loading your Google service account key (.p12)
DECLARE @cert int
EXEC @hr = sp_OACreate 'Chilkat.Cert', @cert OUT
EXEC sp_OAMethod @cert, 'LoadPfxFile', @success OUT, 'c:/someDirectory/keys/chilkat25-cbd7b42afbd8.p12', 'notasecret'
IF @success <> 1
BEGIN
EXEC sp_OAGetProperty @cert, 'LastErrorText', @sTmp0 OUT
PRINT @sTmp0
EXEC @hr = sp_OADestroy @http
EXEC @hr = sp_OADestroy @cert
RETURN
END
-- The ISS is your service account email address ending in gserviceaccount.com.
DECLARE @iss nvarchar(4000)
SELECT @iss = 'chilkatsvc@chilkat25.iam.gserviceaccount.com'
-- The scope is always the following string:
DECLARE @scope nvarchar(4000)
SELECT @scope = 'https://mail.google.com/'
-- The sub is your company email address
DECLARE @oauth_sub nvarchar(4000)
SELECT @oauth_sub = 'bob@yourcompany.com'
-- The access token is valid for this number of seconds.
DECLARE @numSec int
SELECT @numSec = 3600
DECLARE @accessToken nvarchar(4000)
EXEC sp_OAMethod @http, 'G_SvcOauthAccessToken', @accessToken OUT, @iss, @scope, @oauth_sub, @numSec, @cert
EXEC sp_OAGetProperty @http, 'LastMethodSuccess', @iTmp0 OUT
IF @iTmp0 <> 1
BEGIN
EXEC sp_OAGetProperty @http, 'LastErrorText', @sTmp0 OUT
PRINT @sTmp0
EXEC @hr = sp_OADestroy @http
EXEC @hr = sp_OADestroy @cert
RETURN
END
ELSE
BEGIN
PRINT 'access token: ' + @accessToken
END
-- The access token allows us to send unlimited emails while it's valid. Once it expires, we must obtain and use a new one.
EXEC @hr = sp_OADestroy @http
EXEC @hr = sp_OADestroy @cert
END
GO