Public/Connect-GenesysCloud.ps1
|
<# .SYNOPSIS Obtains a Genesys Cloud OAuth access token by using the client credentials flow. .DESCRIPTION Connect-GenesysCloud requests an access token from the Genesys Cloud login service for the supplied client ID, client secret, and region-specific base URL. When the request succeeds, the function stores the access token, token expiry, and base URL in process-level environment variables so other commands in the current session can reuse them: - GC_ACCESS_TOKEN - GC_TOKEN_EXPIRY - GC_BASE_URL The function returns a small status object that identifies the token environment variable name and the calculated expiration time. The token value itself is not written to the pipeline. .PARAMETER ClientId The OAuth client ID for the Genesys Cloud integration. .PARAMETER ClientSecret The OAuth client secret paired with the client ID. .PARAMETER BaseURL The Genesys Cloud login base URL suffix used to build the token endpoint, such as `mypurecloud.com` or `usw2.pure.cloud`. .OUTPUTS System.Management.Automation.PSCustomObject .EXAMPLE Connect-GenesysCloud -ClientId 'your-client-id' -ClientSecret 'your-client-secret' -BaseURL 'mypurecloud.com' Requests a token from `https://login.mypurecloud.com/oauth/token`, stores the resulting session values in environment variables, and returns the token expiry details. .NOTES This function uses the client credentials grant and is intended for service-to-service authentication scenarios. #> function Connect-GenesysCloud { [CmdletBinding()] param( [Parameter(Mandatory = $true)] [string]$ClientId, [Parameter(Mandatory = $true)] [String]$ClientSecret, [Parameter(Mandatory = $true)] [String]$BaseURL ) $EnvVarName = 'GC_ACCESS_TOKEN' $EnvExpiryVarName = 'GC_TOKEN_EXPIRY' $EnvVarEnvironmentBaseURL = 'GC_BASE_URL' $TokenUrl = '/oauth/token' $URI = "https://login.$BaseURL$TokenUrl" $auth = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes("${ClientId}:${ClientSecret}")) $headers = @{ "Authorization" = "Basic $auth" } $body = @{ grant_type = 'client_credentials' } try { $response = (Invoke-WebRequest -Method 'POST' -Uri $URI -Headers $headers -Body $body).Content | ConvertFrom-Json $Expiry = (Get-Date).AddSeconds($response.expires_in) # Store token as environment variable [Environment]::SetEnvironmentVariable($EnvVarName, $response.access_token) [Environment]::SetEnvironmentVariable($EnvExpiryVarName, $Expiry) [Environment]::SetEnvironmentVariable($EnvVarEnvironmentBaseURL, $BaseURL) # Helpful output (don’t print the token) $Output = [pscustomobject]@{ "Environmental Variable Name" = $EnvVarName "Expires At" = $Expiry } return $Output } catch { throw "Failed to obtain/store Genesys token: $($_.Exception.Message)" } } |