Public/Get-BBAccessToken.ps1

Function Get-BBAccessToken {
    <#
    .SYNOPSIS
        Get access token to access BrightBooking API
    .DESCRIPTION
        Get access token to access BrightBooking API
    .PARAMETER BrightBookingApiUrl
        Address of the BrightBooking API, e.g.: https://eu1.api.brightbooking.eu/
    .PARAMETER BrightBookingApiKey
        API key to access the api
    .EXAMPLE
        Get-BBAccessToken -BrightBookingApiUrl "https://eu1.api.brightbooking.eu/" -BrightBookingApiKey "[your api key]"
    .LINK
        http://wiki.brightbooking.eu/
    #>


    [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
        
            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)"
        }
    }
}