Public/Get-BBAccessToken.ps1

Function Get-BBAccessToken {
    <#
    .SYNOPSIS
        Get access token to access GoBright API
    .DESCRIPTION
        Get access token to access GoBright API
    .PARAMETER BrightBookingApiUrl
        Address of the GoBright API, e.g.: https://t1b.gobright.cloud/
    .PARAMETER BrightBookingApiKey
        API key to access the api
    .EXAMPLE
        Get-BBAccessToken -BrightBookingApiUrl "https://t1b.gobright.cloud/" -BrightBookingApiKey "[your api key]"
    .LINK
        https://support.gobright.com/
    #>


    [CmdletBinding()]
    Param(
      [Parameter(Mandatory=$True)]
       [string]$BrightBookingApiUrl,

      [Parameter(Mandatory=$True)]
       [string]$BrightBookingApiKey
    )
    Process {
        $url = $BrightBookingApiUrl
        $resturi = [System.Uri]::new([System.Uri]::new($url), "/token")                

        $body = @{
            grant_type = "apikey"
            apikey = $BrightBookingApiKey
        }

        $hdrs = @{}

        Try
        {
            $response = Invoke-WebRequest -Uri $resturi -Method Post -Body $body -ContentType 'application/text' -Headers $hdrs -UseBasicParsing
        
            If ($response.StatusCode -eq 200)
            {                
                $jsonresponse = $response.Content | ConvertFrom-Json

                $access_token = $jsonresponse.access_token

                return $access_token
            }
        } 
        Catch 
        {
            $statusCode = $_.Exception.Response.StatusCode.Value__
            $responseText = $_
                        
            Try
            {
                $jsonresponse = $responseText | ConvertFrom-Json
                If ($jsonresponse.SyncRoot)
                {
                    $statusMessage = $jsonresponse.SyncRoot
                }
                Else
                {
                    $statusMessage = $responseText
                }
            } 
            Catch 
            {
                $statusMessage = $responseText
            }
            
            throw "Failed to get access token to the API, check your API key. (statuscode: $statusCode, message: $statusMessage)"
        }
    }
}