Chilkat Examples

ChilkatHOMEAndroid™AutoItCC#C++Chilkat2-PythonCkPythonClassic ASPDataFlexDelphi DLLGoJavaNode.jsObjective-CPHP ExtensionPerlPowerBuilderPowerShellPureBasicRubySQL ServerSwiftTclUnicode CUnicode C++VB.NETVBScriptVisual Basic 6.0Visual FoxProXojo Plugin

DataFlex Examples
Web API Categories

ASN.1
AWS KMS
AWS Misc
Amazon EC2
Amazon Glacier
Amazon S3
Amazon S3 (new)
Amazon SES
Amazon SNS
Amazon SQS
Async
Azure Cloud Storage
Azure Key Vault
Azure Service Bus
Azure Table Service
Base64
Box
CAdES
CSR
CSV
Cert Store
Certificates
Cloud Signature CSC
Code Signing
Compression
DKIM / DomainKey
DNS
DSA
Diffie-Hellman
Digital Signatures
Dropbox
Dynamics CRM
EBICS
ECC
Ed25519
Email Object
Encryption
FTP
FileAccess
Firebase
GMail REST API
GMail SMTP/IMAP/POP
Geolocation
Google APIs
Google Calendar
Google Cloud SQL
Google Cloud Storage
Google Drive
Google Photos
Google Sheets
Google Tasks
Gzip
HTML-to-XML/Text
HTTP
HTTP Misc
IMAP
JSON
JSON Web Encryption (JWE)
JSON Web Signatures (JWS)
JSON Web Token (JWT)
Java KeyStore (JKS)
MHT / HTML Email
MIME
Microsoft Graph
Misc
NTLM
OAuth1
OAuth2
OIDC
Office365
OneDrive
OpenSSL
Outlook
Outlook Calendar
Outlook Contact
PDF Signatures
PEM
PFX/P12
PKCS11
POP3
PRNG
REST
REST Misc
RSA
SCP
SCard
SFTP
SMTP
SSH
SSH Key
SSH Tunnel
ScMinidriver
Secrets
SharePoint
SharePoint Online
Signing in the Cloud
Socket/SSL/TLS
Spider
Stream
Tar Archive
ULID/UUID
Upload
WebSocket
X
XAdES
XML
XML Digital Signatures
XMP
Zip
curl
uncategorized

 

 

 

(DataFlex) Get Google API Access Token using JSON Private Key

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

Chilkat ActiveX Downloads

ActiveX for 32-bit and 64-bit Windows

Use ChilkatAx-win32.pkg

Procedure Test
    Handle hoFac
    String sJsonKey
    Handle hoGAuth
    Variant vTlsSock
    Handle hoTlsSock
    Boolean iSuccess
    String sAccessToken
    Handle hoMailman
    Variant vEmail
    Handle hoEmail
    String sTemp1
    Boolean bTemp1

    // 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 JSON key into a string.
    Get Create (RefClass(cComCkFileAccess)) To hoFac
    If (Not(IsComObjectCreated(hoFac))) Begin
        Send CreateComObject of hoFac
    End
    Get ComReadEntireTextFile Of hoFac "qa_data/googleApi/chilkat25-b4214220e565.json" "utf-8" To sJsonKey
    Get ComLastMethodSuccess Of hoFac To bTemp1
    If (bTemp1 <> True) Begin
        Get ComLastErrorText Of hoFac To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    // A Google service account JSON private key looks like this:

    // {
    //   "type": "service_account",
    //   "project_id": "chilkat25",
    //   "private_key_id": "b4214220f565881e19eeb97c2699bf5a0d1e3e0b",
    //   "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvQ...NXcM=\n-----END PRIVATE KEY-----\n",
    //   "client_email": "chilkatsvc@chilkat25.iam.gserviceaccount.com",
    //   "client_id": "109122032928932715958",
    //   "auth_uri": "https://accounts.google.com/o/oauth2/auth",
    //   "token_uri": "https://oauth2.googleapis.com/token",
    //   "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
    //   "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/chilkatsvc%40chilkat25.iam.gserviceaccount.com",
    //   "universe_domain": "googleapis.com"
    // }

    Get Create (RefClass(cComChilkatAuthGoogle)) To hoGAuth
    If (Not(IsComObjectCreated(hoGAuth))) Begin
        Send CreateComObject of hoGAuth
    End
    Set ComJsonKey Of hoGAuth To sJsonKey

    // Specify a scope.
    Set ComScope Of hoGAuth To "https://mail.google.com/"

    // Request an access token that is valid for this many seconds.
    Set ComExpireNumSeconds Of hoGAuth To 3600

    // When using a Google Workspace account with Gmail APIs, a service account can impersonate a user 
    // via a process called domain-wide delegation — and the "sub" claim in the JWT is what enables this.
    // Domain-wide delegation allows a Google Workspace administrator to authorize a service account to 
    // act on behalf of any user in the domain, without user interaction.

    // This is required for server-to-server access to user data — such as reading/sending Gmail from a background service.
    // This is your company email address.
    Set ComSubEmailAddress Of hoGAuth To "info@chilkat.xyz"

    // Connect to www.googleapis.com using TLS
    Get Create (RefClass(cComChilkatSocket)) To hoTlsSock
    If (Not(IsComObjectCreated(hoTlsSock))) Begin
        Send CreateComObject of hoTlsSock
    End
    Get ComConnect Of hoTlsSock "www.googleapis.com" 443 True 5000 To iSuccess
    If (iSuccess <> True) Begin
        Get ComLastErrorText Of hoTlsSock To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    // Send the request to obtain the access token.
    Get pvComObject of hoTlsSock to vTlsSock
    Get ComObtainAccessToken Of hoGAuth vTlsSock To iSuccess
    If (iSuccess <> True) Begin
        Get ComLastErrorText Of hoGAuth To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    // Examine the access token:
    Get ComAccessToken Of hoGAuth To sAccessToken
    Showln "Access Token: " sAccessToken

    // Sample output:
    // ya29.a0AW4XtxjGTD67Z8 .... IRw0218

    // The access token allows us to send unlimited emails while it's valid. Once it expires, we must obtain and use a new one.

    // -----------------------------------------------------------------------
    Get Create (RefClass(cComChilkatMailMan)) To hoMailman
    If (Not(IsComObjectCreated(hoMailman))) Begin
        Send CreateComObject of hoMailman
    End

    // Set the properties for the GMail SMTP server:
    Set ComSmtpHost Of hoMailman To "smtp.gmail.com"
    Set ComSmtpPort Of hoMailman To 587
    Set ComStartTLS Of hoMailman To True

    Set ComSmtpUsername Of hoMailman To "info@chilkat.xyz"
    Set ComOAuth2AccessToken Of hoMailman To sAccessToken

    // Create a new email object
    Get Create (RefClass(cComChilkatEmail)) To hoEmail
    If (Not(IsComObjectCreated(hoEmail))) Begin
        Send CreateComObject of hoEmail
    End

    Set ComSubject Of hoEmail To "This is a test"
    Set ComBody Of hoEmail To "This is a test"
    Set ComFrom Of hoEmail To "Chilkat Test <info@chilkat.xyz>"
    Get ComAddTo Of hoEmail "Chilkat Software" "info@chilkatsoft.com" To iSuccess
    // To add more recipients, call AddTo, AddCC, or AddBcc once per recipient.

    Get pvComObject of hoEmail to vEmail
    Get ComSendEmail Of hoMailman vEmail To iSuccess
    If (iSuccess <> True) Begin
        Get ComLastErrorText Of hoMailman To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    Get ComCloseSmtpConnection Of hoMailman To iSuccess
    If (iSuccess <> True) Begin
        Showln "Connection to SMTP server not closed cleanly."
    End

    Showln "Successfully sent email using Gmail with a service account key."


End_Procedure

 

© 2000-2025 Chilkat Software, Inc. All Rights Reserved.