fingerprint

Login

call

Contact

help

Help

billbee: load orders and articles

1 ratings
billbeeAPIRESTOrdersArticlePowerShell

What it does

Mit dieser Ressource ist es möglich die REST API von billbee (https://www.billbee.io/) abzufragen. Es werden die Bestellungen geladen und deren Artikel aufgeführt. Je nach Anwendungsfall kann man mit der API noch mehr anstellen.

Description

Loading the orders and the articles from the billbee API

Creation Details

  • Author: Sebastian Renners
  • Created: 14.04.2022 21:53:55
  • Last modification: 22.04.2022 21:23:57
Resource Image:

Input Parameters

Name: minorderdate

Description: Type in a date in the format "yyyy-MM-dd". For example 2022-04-15 (15th of April 2022). If no date is set, the current date will be used.

Resource Parameters

Name: apiusername

Description: Define the username for the API access

Name: apikey

Description: Define the API key to get API access.

Code

[CmdletBinding()]
Param(
    [Parameter(Mandatory=$false)]
    [string]$installPath="not-set",
    [Parameter(Mandatory=$false)]
    [string]$jobId="not-set",
    [Parameter(Mandatory=$false)]
    [string]$action="not-set"
)

$debugScript = 0;
if ($debugScript -eq 1) {
    $installPath = "C:\addy\" # Debugging
    #$jobId = "xxxxxxxxxxx" # only for debugging #
}
# Only use TLSv1.1 and TLSv1.2
$AllProtocols = [System.Net.SecurityProtocolType]'Tls11,Tls12'
[System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols

$errorCount = 0 # counting errors. If this variable is greater than 0, the script should not run

# loading functions
write-host "$(get-date -f  "dd.MM.yyyy HH:mm:ss") include functions"
if (test-path "$($installPath)scripts\functions.global.ps1") {
    write-host "Functions-File exists"
    import-module "$($installPath)scripts\functions.global.ps1" -force
} else {
    write-host "Functions-File do not exist. Increasing ErrorCounter." 
    $errorCount++
}

# setting the location
set-location $installPath

# generate a unique machineID #this is important
$machineId = Get-MachineId
  
# write a log online and offline
if ($debugScript -eq 0) {
    write-addylog -Message "All parameter initialized"
}

# Handling with parameters
if ($debugScript -eq 0) {
    # Load parameter information about this job
    $jsonBody = @{ localCurrentTime = $(get-date -f  "dd.MM.yyyy HH:mm:ss")}
    $body = (ConvertTo-Json -Depth 4 $jsonBody) 
    $resultInitializeInvoke = Invoke-RestMethod -Uri "$addyhostaddress/api/v1/heartbeat-consumer?action=checkforjobs&jobId=$jobId" -Method POST -Body $body -ContentType 'application/json; charset=UTF-8' -Headers @{"Publickey"="$publickey";"Privatekey"="$privatekey";"Machineid" = "$machineId"} # -Headers @{'Authorization'='Basic YWRtaW46YWRtaW4'}
    #$resultInitializeInvoke # troubleshooting # write-addylog "Job details: $resultInitializeInvoke"
}
###################### YOUR SCRIPT STARTS HERE ############################
write-addylog  "Start the Script" #-Level "INFO","ERROR", "WARN"

write-addylog "Loading the resource parameters"
# Your login username or mail address. Set the password in the api settings from billbee 
[string]$ParamApiUsername = $resultInitializeInvoke.scriptParameter.apiusername #"apiusername" is definied in the Resource Parameter. 
$ParamApiUsername = $ParamApiUsername.trim()

# You will get the API key from the billbee support. See https://www.billbee.io/hilfecenter/api
[string]$ParamApiKey = $resultInitializeInvoke.scriptParameter.apikey #"apikey" is definied in the Resource Parameter.
$ParamApiKey = $ParamApiKey.trim()

write-addylog "Loading the input parameter"
$addyPayloadResourceInput = $resultInitializeInvoke.jobDataArray.businessAutomationJobsPendingPayload.payload
$ParamMinOrderDate = $addyPayloadResourceInput.minorderdate #"minorderdate" is definied in the Resource input Parameter. This are now a parameter for this script 

# assign the variables
$credUsername = $ParamApiUsername 
$ApiKey = $ParamApiKey

write-addylog "Starting the billbee order handling"
start-sleep 1

# set the billbee api password here https://app.billbee.io/app_v2/settings/api/general 
# load the password from the secure string. 
$credSecureStringFilename = Get-StringHash -String $($credUsername + $env:USERNAME + "billbe")
# build the filepath for the secure credential file
$SecureStringPath = "$($installPath)SecureStrings\$credSecureStringFilename.txt"

if (test-path $SecureStringPath) {
    #debug# write-host "$(get-date -f  "dd.MM.yyyy HH:mm:ss") SecureString FullPath exist." -f green
    #write-loglocal -Message "SecureString FullPath exist." -Level "INFO" -path "$($installPath)logs\scriptHandler-$($scriptHandlerId).txt"
} else {
    #promt to add the password
    write-host "$(get-date -f  "dd.MM.yyyy HH:mm:ss") Need to type in the password for user: $credUsername"
    $credPasswordSecureString = read-host -assecurestring "Password for $credUsername"

    #store SecureString
    write-host "$(get-date -f  "dd.MM.yyyy HH:mm:ss") Storing the password as a secure string"
    $credSecureStringContent = $credPasswordSecureString | ConvertFrom-SecureString 

    #check if the folder exists
    if (test-path "$($installPath)SecureStrings\") {
        write-host "$(get-date -f  "dd.MM.yyyy HH:mm:ss") SecureString Folder already exist"
    } else {
        write-host "$(get-date -f  "dd.MM.yyyy HH:mm:ss") SecureString Folder structure does not exist"
        new-item -ItemType Directory -Path "$($installPath)\SecureStrings\" -ErrorAction Continue | Out-Null
    }

    write-host "$(get-date -f  "dd.MM.yyyy HH:mm:ss") Create SecureString file"    
    Set-Content $SecureStringPath $credSecureStringContent -Force
}

$credPassword = get-content $SecureStringPath | convertto-securestring
$billbeeCreds = New-Object System.Management.Automation.PSCredential -ArgumentList $credUsername,$credPassword

write-addylog "Initializing the url to get the orders"

#build the url
$BaseUrl = "https://app.billbee.io/api/v1/"
$FunctionUrlParameter = "orders"
#$RequestUrl = "$($BaseUrl)$($FunctionUrlParameter)"

if (($ParamMinOrderDate -eq "") -or ($NULL -eq $ParamMinOrderDate)) {
    write-addylog "No min order date set. Taking the current date."
    $MinOrderDate = get-date -Format 'yyyy-MM-dd'
} else {
    write-addylog "Min order date set from the input parameter."
    #$MinOrderDate = "2022-04-15" # troubleshooting
    $MinOrderDate = $ParamMinOrderDate
}

$specialParameter = "?minOrderDate=$($MinOrderDate)"
#orderStateId=1&orderStateId=2&orderStateId=3
$RequestUrl = "$($BaseUrl)$($FunctionUrlParameter)$($specialParameter)"

write-addylog "Loading the orders for date: $MinOrderDate"
start-sleep 1
$JsonOrders = Invoke-RestMethod -Uri $RequestUrl -Method GET -Credential $billbeeCreds -Headers @{"X-Billbee-Api-Key"=$ApiKey;} -ContentType 'application/json'
# handling possible errors here!
write-addylog "Order Count: $($JsonOrders.Data.count)"

start-sleep 1

# troubleshooting
#$JsonOrders.Data[0]
#$JsonOrders.Data.invoiceNumber

$i = 0
$SkippedOrderArray = @()
foreach ($OrderElement in $JsonOrders.Data) {
    $i++
    $skipOrder = 0
    write-host "`nOrder $($i) of $($JsonOrders.Data.count)" -f yellow

    write-host "[$($OrderElement.OrderNumber)] OrderNumber: $($OrderElement.OrderNumber)"
    write-host "[$($OrderElement.OrderNumber)] Id: $($OrderElement.Id)"
    write-host "[$($OrderElement.OrderNumber)] State: $($OrderElement.State)"

    if ($OrderElement.OrderNumber -eq $NULL) {
        write-host "[$($OrderElement.OrderNumber)] Order without order number!" -f magenta
        start-sleep 1
    }
    <#
    1: bestellt
    2: bestätigt
    3: bezahlt
    4: versendet
    5: reklamation
    6: gelöscht
    7: abgeschlossen
    8: storniert
    9: archiviert

    11: angemahnt
    12: 2. Manhnung
    13: gepackt
    14: angeboten
    15: zahlungserinnerung
    16: im fulfillment
    #>

    #get the customer data
    write-host "[$($OrderElement.OrderNumber)] Customer Name: $($OrderElement.Customer.Name)"
    write-host "[$($OrderElement.OrderNumber)] Customer Email: $($OrderElement.Customer.Email)"
    write-host "[$($OrderElement.OrderNumber)] Customer Tel1: $($OrderElement.Customer.Tel1)"
    write-host "[$($OrderElement.OrderNumber)] Customer Number: $($OrderElement.Customer.Number)"
    write-host "[$($OrderElement.OrderNumber)] Customer Id: $($OrderElement.Customer.Id)"

    #get the ShippingAddress  #$OrderElement.ShippingAddress
    if ($OrderElement.ShippingAddress.FirstName -eq "") {
        write-host "[$($OrderElement.OrderNumber)] FirstName not given" -f red
        $skipOrder++
    }
    if ($OrderElement.ShippingAddress.LastName -eq "") {
        write-host "[$($OrderElement.OrderNumber)] LastName not given" -f red
        $skipOrder++
    }
    if ($OrderElement.ShippingAddress.Street -eq "") {
        write-host "[$($OrderElement.OrderNumber)] Street not given" -f red
        $skipOrder++
    }
    if ($OrderElement.ShippingAddress.HouseNumber -eq "") {
        write-host "[$($OrderElement.OrderNumber)] HouseNumber not given" -f red
        $skipOrder++
    }
    if ($OrderElement.ShippingAddress.Zip -eq "") {
        write-host "[$($OrderElement.OrderNumber)] Zip not given" -f red
        $skipOrder++
    }    
    if ($OrderElement.ShippingAddress.City -eq "") {
        write-host "[$($OrderElement.OrderNumber)] City not given" -f red
        $skipOrder++
    }
    if ($OrderElement.ShippingAddress.CountryISO2 -eq "") {
        write-host "[$($OrderElement.OrderNumber)] CountryISO2 not given" -f red
        $skipOrder++
    }
    if ($skipOrder -ne 0) {
        write-host "[$($OrderElement.OrderNumber)] An important information is not given. " -f red
        $SkippedOrderArray += $OrderElement # load the skipped order in an another array
    }

    # check the order #$OrderElement.OrderItems
    write-host "[$($OrderElement.OrderNumber)] Order Items Count: $($OrderElement.OrderItems.Count)" -f magenta
    write-host "[$($OrderElement.OrderNumber)] Checking the orders..."
    start-sleep 1

    $x = 0 #orders count
    foreach ($OrderItems in $OrderElement.OrderItems) {
        $x++
        write-host "[$($OrderElement.OrderNumber)] ($x of $($OrderElement.OrderItems.count))"

        write-host "[$($OrderElement.OrderNumber)] [$($OrderItems.InvoiceSKU)] Quantity: $($OrderItems.Quantity)"

        # Do your stuff with this articles in the order

    } #foreach ($OrderItems in $OrderElement.OrderItems) {

} #foreach ($OrderElement in $JsonOrders.Data) {

if ($SkippedOrderArray.count -eq 0) {
    write-addylog "There are no skipped orders."
} else {
    write-addylog "This are the skipped orders: $SkippedOrderArray"
}

###################### YOUR SCRIPT ENDS HERE ############################
#setting the state #this is important!
if ($debugScript -eq 0) {
    write-addylog "update state of this job to done"
    update-modifiedState -jobId $jobId -modifiedState "done" -publickey $publickey -privatekey $privatekey -machineId $machineId

    Start-Sleep 3 
    write-addylog "End of script reached" 

    Start-Sleep 1
    exit
}

Rating

login and obtain the library resource to set a rating.