Hp warranty check api

Hp warranty check api DEFAULT

One of the reddits I frequent has been seeing a lot of complaints lately about warranty information being incomplete or there&#;s complaints about the pricing of warranty information products. Most of these complaints are aimed at a specific product which is showing very shady sales tactics and general bad business practices lately.

I figured I would try to take up these complaints and solve them with a PowerShell script. This script grabs the warranty information for most major manufactures. It will generate a warranty report based on the input data. The input data can either be a CSV file or the Autotask PSA.

You can also upload the warranty date back to Autotask to keep your warranty information in sync too. Currently I&#;ve only made support for Autotask but I&#;m willing to create one for CW too if there is enough interest 🙂

So lets get started.

Prerequisites

Before we can dive into the script we&#;ll have to collect some API keys. These keys will be used to get the warranty information at the vendors, or there are some &#;gotcha&#;s&#; you must know beforehand.

When you have Dell as a vendor:

  • Go to the Dell TechDirect website and register if you do not yet have an account. Complete the enrollment.
  • After registration, browse to the Dell TechDirect API enrollment page and wait for approval. This is a manual procedure so can take a day or two.
  • When the approval has been given, request a new API key and save this in a secure location.

When you have HP as a vendor:

Officially the HP API has been disabled because it was getting hammered by requests. The unofficial API is still available though so this script is based on that API.

When you have Microsoft as a vendor:

So Microsoft officially does not have a warranty lookup tool, but I found the Surface Diagnostic App does have a way to have programmatic access to the warranty environment. I reverse engineered this method. This is an unofficial and unsupported API so it might not function in the future.

When you have Lenovo as a vendor:

You don&#;t have to do anything 🙂 Lenovo has an open API.

The Script

So now that we have our API keys and data, we can start feeding the script information. This can be via a CSV file or via Autotask. The CSV file should have the following information:

serialnumber,vendor,client ,HP,contoso ,Dell,toiletpaperco ,MS,contoso ,Lenovo,johndoe inc

If you are using Autotask, fill in the API integration key from your API user, and log in when your username/password is requested.

$source = "CSV" #AT, CSV, ITG, CW ##### Sync Settings $SyncWithSource = $true #Sync status warranty dates/status back to PSA/Management system. Only works with dynamic sources like ITG and AT. $OverwriteWarranty = $true #Overwrites the date already found in AT with the one based on this API, unless the API could not find information. $CreateHTMLReport = $true #Creates an HTML report. ###### File locations $ReportsLocation = "C:\temp\reports" #Only required if Reporting is enabled. $sourcefile = "C:\temp\temp.csv" #only required if source is not autotask. $ATLogPath = "C:\temp\AT.txt" #Only used to log which objects have been synced with AT as AT does not have a audit log. ##### AT API Settings $ATAPIKey = "Your-API-Key-For-Autotask" #only required if source is Autotask. ##### ITG API Settings $ITGAPIKey = "Your-API-Key-For-ITG" #only required if source is ITG $ITGAPIURL = "https://api.eu.itglue.com" #only required if source is ITG ##### CW API Settings $CWAPIURL = "https://api-staging.connectwisedev.com/v4_6_release/apis/" #https://developer.connectwise.com/Best_Practices/Manage_Cloud_URL_Formatting?mt-learningpath=manage $CWApiKeyPublic = "CWPublicKey" #Only required if source is CW $CWApiKeyPrivate = "CwPrivateKey" #Only required if source is CW $CWcompanyid = "CompanyID_1" #Only required if source is CW ##### Warranty Vendor API Keys $DellClientID = "Dell-Client-ID" $DellClientSecret = "Dell-Client-Secret" function get-HPWarranty([Parameter(Mandatory = $true)]$SourceDevice, $Client) { $MWSID = (invoke-restmethod -uri &#;https://support.hp.com/us-en/checkwarranty/multipleproducts/&#; -SessionVariable &#;session&#; -Method get) -match &#;.*mwsid":"(?<wssid>.*)".hp.com/hp-pps-services/os/multiWarranty?ssid=$($matches.wssid)" -WebSession $session -Method "POST" -ContentType "application/json" -Body $HPbody if ($HPreq.productWarrantyDetailsVO.warrantyResultList.obligationStartDate) { $WarObj = [PSCustomObject]@{ &#;Serial&#; = $SourceDevice &#;Warranty Product name&#; = $hpreq.productWarrantyDetailsVO.warrantyResultList.warrantyType | Out-String &#;StartDate&#; = $hpreq.productWarrantyDetailsVO.warrantyResultList.obligationStartDate | sort-object | select-object -last 1 &#;EndDate&#; = $hpreq.productWarrantyDetailsVO.warrantyResultList.obligationEndDate | sort-object | select-object -last 1 &#;Warranty Status&#; = $hpreq.productWarrantyDetailsVO.obligationStatus &#;Client&#; = $Client } } else { $WarObj = [PSCustomObject]@{ &#;Serial&#; = $SourceDevice &#;Warranty Product name&#; = &#;Could not get warranty information&#; &#;StartDate&#; = $null &#;EndDate&#; = $null &#;Warranty Status&#; = &#;Could not get warranty information&#; &#;Client&#; = $Client } } return $WarObj } function get-DellWarranty([Parameter(Mandatory = $true)]$SourceDevice, $client) { $today = Get-Date -Format yyyy-MM-dd $AuthURI = "https://apigtwb2c.us.dell.com/auth/oauth/v2/token" if ($Global:TokenAge -lt (get-date).AddMinutes()) { $global:Token = $null } If ($null -eq $global:Token) { $OAuth = "$global:DellClientID`:$global:DellClientSecret" $Bytes = [System.Text.Encoding]::ASCII.GetBytes($OAuth) $EncodedOAuth = [Convert]::ToBase64String($Bytes) $headersAuth = @{ "authorization" = "Basic $EncodedOAuth" } $Authbody = &#;grant_type=client_credentials&#; $AuthResult = Invoke-RESTMethod -Method Post -Uri $AuthURI -Body $AuthBody -Headers $HeadersAuth $global:token = $AuthResult.access_token $Global:TokenAge = (get-date) } $headersReq = @{ "Authorization" = "Bearer $global:Token" } $ReqBody = @{ servicetags = $SourceDevice } $WarReq = Invoke-RestMethod -Uri "https://apigtwb2c.us.dell.com/PROD/sbil/eapi/v5/asset-entitlements" -Headers $headersReq -Body $ReqBody -Method Get -ContentType "application/json" $warlatest = $warreq.entitlements.enddate | sort-object | select-object -last 1 $WarrantyState = if ($warlatest -le $today) { "Expired" } else { "OK" } if ($warreq.entitlements.serviceleveldescription) { $WarObj = [PSCustomObject]@{ &#;Serial&#; = $SourceDevice &#;Warranty Product name&#; = $warreq.entitlements.serviceleveldescription -join "`n" &#;StartDate&#; = (($warreq.entitlements.startdate | sort-object -Descending | select-object -last 1) -split &#;T&#;)[0] &#;EndDate&#; = (($warreq.entitlements.enddate | sort-object | select-object -last 1) -split &#;T&#;)[0] &#;Warranty Status&#; = $WarrantyState &#;Client&#; = $Client } } else { $WarObj = [PSCustomObject]@{ &#;Serial&#; = $SourceDevice &#;Warranty Product name&#; = &#;Could not get warranty information&#; &#;StartDate&#; = $null &#;EndDate&#; = $null &#;Warranty Status&#; = &#;Could not get warranty information&#; &#;Client&#; = $Client } } return $WarObj } function get-LenovoWarranty([Parameter(Mandatory = $true)]$SourceDevice, $client) { $today = Get-Date -Format yyyy-MM-dd $APIURL = "https://ibase.lenovo.com/POIRequest.aspx" $SourceXML = "xml=<wiInputForm source=&#;ibase&#;><id>LSC3</id><pw>IBA4LSC3</pw><product></product><serial>$SourceDevice</serial><wiOptions><machine/><parts/><service/><upma/><entitle/></wiOptions></wiInputForm>" $Req = Invoke-RestMethod -Uri $APIURL -Method POST -Body $SourceXML -ContentType &#;application/x-www-form-urlencoded&#; if ($req.wiOutputForm) { $warlatest = $Req.wiOutputForm.warrantyInfo.serviceInfo.wed | sort-object | select-object -last 1 $WarrantyState = if ($warlatest -le $today) { "Expired" } else { "OK" } $WarObj = [PSCustomObject]@{ &#;Serial&#; = $Req.wiOutputForm.warrantyInfo.machineinfo.serial &#;Warranty Product name&#; = $Req.wiOutputForm.warrantyInfo.machineinfo.productname -join "`n" &#;StartDate&#; = $Req.wiOutputForm.warrantyInfo.serviceInfo.warstart | sort-object -Descending | select-object -last 1 &#;EndDate&#; = $Req.wiOutputForm.warrantyInfo.serviceInfo.azurewebsites.net/api/key&#; -Method Get $AesCSP = New-Object System.Security.Cryptography.AesCryptoServiceProvider $AesCSP.GenerateIV() $AesCSP.GenerateKey() $AESIVString = [System.Convert]::ToBase64String($AesCSP.IV) $AESKeyString = [System.Convert]::ToBase64String($AesCSP.Key) $AesKeyPair = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes("$AESIVString,$AESKeyString")) $bodybytes = [System.Text.Encoding]::UTF8.GetBytes($body) $bodyenc = [System.Convert]::ToBase64String($AesCSP.CreateEncryptor().TransformFinalBlock($bodybytes, 0, $bodybytes.Length)) $RSA = New-Object System.Security.Cryptography.RSACryptoServiceProvider $RSA.ImportCspBlob([System.Convert]::FromBase64String($PublicKey)) $EncKey = [System.Convert]::ToBase64String($rsa.Encrypt([System.Text.Encoding]::UTF8.GetBytes($AesKeyPair), $false)) $FullBody = @{ Data = $bodyenc Key = $EncKey } | ConvertTo-Json $WarReq = Invoke-RestMethod -uri "https://surfacewarrantyservice.azurewebsites.net/api/v2/warranty" -Method POST -body $FullBody -ContentType "application/json" if ($WarReq.warranties) { $WarrantyState = foreach ($War in ($WarReq.warranties.effectiveenddate -split &#;T&#;)[0]) { if ($War -le $today) { "Expired" } else { "OK" } } $WarObj = [PSCustomObject]@{ &#;Serial&#; = $SourceDevice &#;Warranty Product name&#; = $WarReq.warranties.name -join "`n" &#;StartDate&#; = (($WarReq.warranties.effectivestartdate | sort-object -Descending | select-object -last 1) -split &#;T&#;)[0] &#;EndDate&#; = (($WarReq.warranties.effectiveenddate | sort-object | select-object -last 1) -split &#;T&#;)[0] &#;Warranty Status&#; = $WarrantyState &#;Client&#; = $Client } } else { $WarObj = [PSCustomObject]@{ &#;Serial&#; = $SourceDevice &#;Warranty Product name&#; = &#;Could not get warranty information&#; &#;StartDate&#; = $null &#;EndDate&#; = $null &#;Warranty Status&#; = &#;Could not get warranty information&#; &#;Client&#; = $Client } } return $WarObj } function Get-WarrantyCSV($sourcefile) { write-host "Source is CSV file. Grabbing all devices." -ForegroundColor Green $CSVLines = import-csv -path $sourcefile -Delimiter "," $warrantyObject = foreach ($Line in $CSVLines) { switch ($line.vendor) { HP { get-HPWarranty -SourceDevice $line.SerialNumber -Client $line.client } Dell { get-DellWarranty -SourceDevice $line.SerialNumber -Client $line.client } Lenovo { get-LenovoWarranty -SourceDevice $line.SerialNumber -Client $line.client } MS { Get-MSWarranty -SourceDevice $line.SerialNumber -Client $line.client } } } return $warrantyObject } function Get-WarrantyAutotask($APIKey) { write-host "Source is Autotask." -ForegroundColor Green If (Get-Module -ListAvailable -Name "Autotask") { Import-module "Autotask" } Else { install-module "Autotask" -Force } $Credential = Get-Credential -Message "Enter your Autotask Credentials" remove-module autotask Import-Module Autotask -ArgumentList $Credential, $global:ATAPIKey write-host "Logging into Autotask. Grabbing all client information." -ForegroundColor "Green" $AllClients = $AllAccounts = Get-AtwsAccount -All | Where-Object { $_.Active -eq $true } write-host "Client information found. Grabbing all devices" -ForegroundColor "Green" $AllDevices = Get-AtwsInstalledProduct -All | Where-Object { $_.Active -eq $true -and $null -ne $_.SerialNumber } write-host "Collecting information. This can take a long time." -ForegroundColor "Green" $i = 0 $warrantyObject = foreach ($Device in $AllDevices) { $i++ Write-Progress -Activity "Grabbing Warranty information" -status "Processing $($device.serialnumber). Device $i of $($Alldevices.Count)" -percentComplete ($i / $Alldevices.Count * ) $Client = ($AllClients | Where-Object { $_.id -eq $device.AccountID }).AccountName #We use a guess-smart method for serialnumbers. #Dell is always 7, Lenovo is always 8, 10 is HP, 12 is Surface. #This is because we cannot safely find the manafacture in the AT info. switch ($device.SerialNumber.Length) { 7 { $WarState = get-DellWarranty -SourceDevice $device.SerialNumber -client $Client } 8 { $WarState = get-LenovoWarranty -SourceDevice $device.SerialNumber -client $Client } 10 { $WarState = get-HPWarranty -SourceDevice $device.SerialNumber -client $Client } 12 { $WarState = Get-MSWarranty -SourceDevice $device.SerialNumber -client $Client } } if ($script:SyncWithSource -eq $true) { switch ($script:OverwriteWarranty) { $true { if ($null -ne $warstate.EndDate) { $device | Set-AtwsInstalledProduct -WarrantyExpirationDate $warstate.EndDate "$Client / $($device.SerialNumber) with AT ID $($device.id) warranty has been overwritten to $($warstate.EndDate)" | out-file $script:ATLogPath -Append -Force } } $false { if ($null -eq $device.WarrantyExpirationDate -and $null -ne $warstate.EndDate) { $device | Set-AtwsInstalledProduct -WarrantyExpirationDate $warstate.EndDate "$Client / $($device.SerialNumber) with AT ID $($device.id) warranty has been set to $($warstate.EndDate)" | out-file $script:ATLogPath -Append -Force } } } } $WarState } return $warrantyObject } function Get-WarrantyITG() { write-host "Source is IT-Glue. Grabbing all devices." -ForegroundColor Green If (Get-Module -ListAvailable -Name "ITGlueAPI") { Import-module ITGlueAPI } Else { Install-Module ITGlueAPI -Force Import-Module ITGlueAPI } #Settings IT-Glue logon information Add-ITGlueBaseURI -base_uri $Global:ITGAPIURL Add-ITGlueAPIKey $Global:ITGAPIKey write-host "Getting IT-Glue configuration list" -foregroundColor green $i = 0 $AllITGlueConfigs = @() do { $AllITGlueConfigs += (Get-ITglueconfigurations -page_size -page_number $i).data $i++ Write-Host "Retrieved $($AllITGlueConfigs.count) configurations" -ForegroundColor Yellow }while ($AllITGlueConfigs.count % -eq 0 -and $AllITGlueConfigs.count -ne 0) $warrantyObject = foreach ($device in $AllITGlueConfigs) { $i++ Write-Progress -Activity "Grabbing Warranty information" -status "Processing $($device.attributes.&#;serial-number&#;). Device $i of $($AllITGlueConfigs.Count)" -percentComplete ($i / $AllITGlueConfigs.Count * ) $Client = ($AllClients | Where-Object { $_.id -eq $device.AccountID }).AccountName $client = $device.attributes.&#;organization-name&#; switch ($device.attributes.&#;serial-number&#;.Length) { 7 { $WarState = get-DellWarranty -SourceDevice $device.attributes.&#;serial-number&#; -client $Client } 8 { $WarState = get-LenovoWarranty -SourceDevice $device.attributes.&#;serial-number&#; -client $Client } 10 { $WarState = get-HPWarranty -SourceDevice $device.attributes.&#;serial-number&#; -client $Client } 12 { $WarState = Get-MSWarranty -SourceDevice $device.attributes.&#;serial-number&#; -client $Client } } if ($script:SyncWithSource -eq $true) { $FlexAssetBody = @{ "type" = "configurations" "attributes" = @{ &#;warranty-expires-at&#; = $warstate.EndDate } } switch ($script:OverwriteWarranty) { $true { if ($null -ne $warstate.EndDate) { Set-ITGlueConfigurations -id $device.id -data $FlexAssetBody } } $false { if ($null -eq $device.WarrantyExpirationDate -and $null -ne $warstate.EndDate) { Set-ITGlueConfigurations -id $device.id -data $FlexAssetBody } } } } $WarState } return $warrantyObject } function Get-WarrantyCW() { write-host "Source is Connectwise Manage. Grabbing all devices." -ForegroundColor Green $Base64Key = [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes("$($Global:CWcompanyid)+$($Global:CWApiKeyPublic):$($global:CWApiKeyPrivate)")) $Header = @{ &#;clientId&#; = &#;dda6-fabfb-7aa2bbefa&#; #This is the warranty script client id. Do not change. &#;Authorization&#; = "Basic $Base64Key" &#;Content-Type&#; = &#;application/json&#; } $i = 0 $Devices = @() do { $Devices += invoke-restmethod -headers $header -method GET -uri "$($Global:CWAPIURL)/company/configurations?pageSize=&page=$i" $i++ Write-Host "Retrieved $($devices.count) configurations" -ForegroundColor Yellow }while ($devices.count % -eq 0 -and $devices.count -ne 0) $warrantyObject = foreach ($device in $Devices) { $i++ Write-Progress -Activity "Grabbing Warranty information" -status "Processing $($device.serialnumber). Device $i of $($devices.Count)" -percentComplete ($i / $Devices.Count * ) $client = $device.company.name switch ($device.serialnumber.Length) { 7 { $WarState = get-DellWarranty -SourceDevice $device.serialnumber -client $Client } 8 { $WarState = get-LenovoWarranty -SourceDevice $device.serialnumber -client $Client } 10 { $WarState = get-HPWarranty -SourceDevice $device.serialnumber -client $Client } 12 { $WarState = Get-MSWarranty -SourceDevice $device.serialnumber -client $Client } } if ($script:SyncWithSource -eq $true) { if (!$device.warrantyExpirationDate) { $device | Add-Member -NotePropertyName "warrantyExpirationDate" -NotePropertyValue "$($WarState.enddate)TZ" } else { $device.warrantyExpirationDate = "$($WarState.enddate)TZ" } $CWBody = $device | ConvertTo-Json switch ($script:OverwriteWarranty) { $true { if ($null -ne $warstate.EndDate) { invoke-restmethod -headers $header -method put -uri "$($Global:CWAPIURL)/company/configurations/$($device.id)" -body $CWBody } } $false { if ($null -eq $device.WarrantyExpirationDate -and $null -ne $warstate.EndDate) { invoke-restmethod -headers $header -method put -uri "$($Global:CWAPIURL)/company/configurations/$($device.id)" -body $CWBody } } } } $WarState } return $warrantyObject } switch ($source) { AT { $warrantyObject = Get-WarrantyAutotask -APIKey $ATAPIKey | Sort-Object -Property Client } CSV { $warrantyObject = Get-WarrantyCSV -Sourcefile $sourcefile | Sort-Object -Property Client } ITG { $warrantyObject = Get-WarrantyITG | Sort-Object -Property Client } CW { $warrantyObject = Get-WarrantyCW | Sort-Object -Property Client } } write-host "Done updating warrenties. Generating reports if required." -ForegroundColor Green $head = @" <script> function myFunction() { const filter = document.querySelector(&#;#myInput&#;).value.toUpperCase(); const trs = document.querySelectorAll(&#;table tr:not(.header)&#;); trs.forEach(tr => tr.style.display = [tr.children].find(td => td.innerHTML.toUpperCase().includes(filter)) ? &#;&#; : &#;none&#;); }</script> <Title>Warranty Report</Title> <style> body { background-color:#E5E4E2; font-family:Monospace; font-sizept; } td, th { border:0px solid black; border-collapse:collapse; white-space:pre; } th { color:white; background-color:black; } table, tr, td, th { padding: 2px; margin: 0px; white-space:pre; } tr:nth-child(odd) {background-color: lightgray} table { width%;margin-left:5px; margin-bottompx; } h2 { font-family:Tahoma; color:#6D7B8D; } .footer { color:green; margin-leftpx; font-family:Tahoma; font-size:8pt; font-style:italic; } #myInput { background-image: url(&#;https://www.w3schools.com/css/searchicon.png&#;); /* Add a search icon to input */ background-position: 10px 12px; /* Position the search icon */ background-repeat: no-repeat; /* Do not repeat the icon image */ width: 50%; /* Full-width */ font-size: 16px; /* Increase font-size */ padding: 12px 20px 12px 40px; /* Add some padding */ border: 1px solid #ddd; /* Add a grey border */ margin-bottom: 12px; /* Add some space below the input */ } </style> "@ $PreContent = @" <H1> Warranty Report </H1> <br> Please consult the report for more information. you can use the search window to find a specific device, date, or warranty state. <br/> <br/> <input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search"> "@ if ($CreateHTMLReport -eq $true) { $CheckReportFolder = Test-Path($ReportsLocation) if (!$CheckReportFolder) { new-item -ItemType Directory -Path $ReportsLocation -Force | Out-Null } foreach ($client in $warrantyObject.client | Select-Object -Unique) { write-host "Generating report for $Client at $($ReportsLocation)\$client.html" -ForegroundColor Green $warrantyObject | Where-Object { $_.Client -eq $client } | convertto-html -Head $head -precontent $precontent | out-file "$($ReportsLocation)\$client.html" } }

After executing the script, the HTML reports will look like this:

And that&#;s it! the script isn&#;t perfect yet and could use some more error handling which I&#;ll work on in the coming weeks but I really think this is a fantastic solution to get rid of warranty information providers that are asking big bucks. 🙂

So as always, Happy PowerShelling!

Update 1: Added ITGlue as source.

Update 2: Added CW as resource

Update 3: Added some better logic for the script, also the script is on Github now! https://github.com/KelvinTegelaar/PowerShellWarrantyReports

Sours: https://www.cyberdrain.com/automating-with-powershell-automating-warranty-information-reporting/

Using the Warranty API with cURL

We received a message from a frustrated forum participant who wanted to know why our API returned unusable characters instead of usable data.

Gzipped

The Product Warranty API uses compression (gzip) to return the status of existing jobs and the results of completed jobs. This data must be uncompressed when it reaches the client - otherwise, what you see will look something like this:

??Qk?0E?J?sթ??eilm?o?m?Pld??XE??%*?? > ?w?mJr???????_q8??E????K Fh?F?????f ???kY~{?0z?,<9{??J??l?a?ԶY??.M????a/??W`??WM?s?}x???M?v93??Q}Z?4??׻?3???OG?E%E?r?! ??T%(?R??A?b?b?xB??lB?I?F$U?H?2?}????TA?ëU?K 핞?]Y?4???Z???4k79 U?b*?b??38??f? ?g[]y?4??????G????N?E)0EA??<?k?d??]Z%i???G??l?????:???G??? ?8?????F\Gz

The affected participant was using cURL to manage warranty lookups, but had not included the --compressed flag (which will automatically treat retrieved content as compressed and uncompress it for you) when checking the status of batch jobs.

cURL code

If you would like to use cURL to manage your warranty lookups, a typical set of commands might look like this:

1. Create an access token using your API key and API secret. The access token is necessary for the remaining steps.

# Create an access token (No --compress flag needed): curl -d "apiKey=API_KEY&apiSecret=API_SECRET&grantType=client_credential&scope=warranty" -X POST "https://css.api.hp.com/oauth/v1/token" -H "Accept: application/json" # Returns: {"access_token":"ACCESS_TOKEN","expires_in":"","scope":"warranty"} # Replace "API_KEY" and "API_SECRET" with your key and secret. "ACCESS_TOKEN" will be a string you use as a bearer token for authentication.

2. Create a batch job comprised of serial numbers and (optionally) product numbers.

# Create new batch job (No --compress flag needed): curl -d '[{"sn":"SERIAL_NUMBER_1", "pn":"PRODUCT_NUMBER_1"},{"sn":"SERIAL_NUMBER_2", "pn":"PRODUCT_NUMBER_2"},]' -X POST "https://css.api.hp.com/productWarranty/v1/jobs" -H "Content-Type: application/json" -H "Authorization: Bearer ACCESS_TOKEN" -H "Accept: application/json" # Returns: {"jobId":"JOB_ID","estimatedTime":ESTIMATED_TIME} # Replace "SERIAL_NUMBER_#" and "PRODUCT_NUMBER_#" with serial numbers and product numbers. # Note: Product numbers are optional.

3. Check the status of the batch job. The amount of time it takes is a function of how many serial numbers you need to look up. Batch jobs theoretically can accept up to serial numbers.

# Check the status of the batch job (--compressed flag required): curl --compressed "https://css.api.hp.com/productWarranty/v1/jobs/JOB_ID" -H "Authorization: Bearer ACCESS_TOKEN" -H "Accept: application/json" # Returns: {"jobId":"JOB_ID","status":"STATUS","productsProcessed":PRODUCT_COUNT,"expirationDate":"DATE"} # Replace "JOB_ID" with the jobId returned in step 2. # Note: A status of "completed" will be returned when the entire batch job is finished.

4. Retrieve the results of the job.

# Retrieve the results (--compressed flag required): curl --compressed "https://css.api.hp.com/productWarranty/v1/jobs/JOB_ID/results" -H "Authorization: Bearer ACCESS_TOKEN" -H "Accept: application/json" # Returns: <Array of results for each entry submitted> # Note: Each member of the array will have a "status" field indicating whether its warranty is expired.

IMPORTANT NOTE: Steps 3 and 4 require the --compressed flag.

Sours: https://developers.hp.com/hp-product-warranty/blog/using-warranty-api-curl
  1. Yamaha amplifiers for sale
  2. Ravi vixx age
  3. Citrus heights police twitter
  4. Mills nutrients vs canna

Product Warranty API Scripts

Please note: The beta Warranty API is currently unavailable.
We will resume operations at a later time.


For small numbers of devices, please consider HP Support's manual Warranty Checking web form. 

 Existing API users will get a level response from the API. We apologize for any inconvenience. 


Welcome to the Warranty Lookup API sample script repository.

This page presents several example scripts to help you implement the Warranty Lookup API in your environment.

Looking up server warranties? HP Inc. does not make or warranty servers. Please go to the Hewlett Packard Enterprise web form.

Should you use v or v?

Companies often have a mix of device warranties. New devices are covered by the original factory warranty. Older devices may be covered by an extended warranty contract. Not sure what mix your company has? Consider using API v to identify which devices are already on an extended warrant contract.

  • Version reports the expiration date but not the type of warranty. API v won't tell you if the expiring warranty is an original factory warranty or an extended warranty.
  • Version  also reports the type of warranty (factory or extended). API v helps you decide whether an aging device should continue on an extended warranty or be replaced.​

​What do you want from the Warranty API?


Scripts for API v

API v gives detailed warranty information for each current warranty

Here are example scripts for API v

  • Node.js (any supported platform)
  • Python (any supported platform)
  • cURL (any supported platform, manual commands only)

From our friends at HP Legal: No warranty on warranty scripts
HP Inc. makes no warranty, express or implied, about the fitness of the scripts below for any purpose. They are intended solely to demonstrate how to use the API, and are not intended for production use.

Node.js for v

Prerequisites for Node.js

  • A local installation of Node.js binaries
  • A data source for serial numbers and product numbers in JSON

/* * warranty-example-node.js * Author: Damon Kaswell, HP Developers Portal (Inspired by Robert Olsén) * Description: Gets warranty information based on product number and serial number. */ const https = require('https'); const zlib = require('zlib'); const fs = require('fs'); /* Variables */ const apiKey = 'Enter key here'; const apiSecret = 'Enter secret here'; const host = 'css.api.hp.com'; const queryPath = '/productWarranty/v2/jobs'; const tokenPath = '/oauth/v1/token'; const port = ; const tokenBody = `apiKey=${apiKey}&apiSecret=${apiSecret}&grantType=client_credentials&scope=warranty`; /* Input values * * Replace with an appropriate data source for serial numbers and product numbers. * For example, you could use the following syntax to read data from a JSON file: * * const dataArray = require('/path/to/file.json'); * * NOTE: Product numbers are optional. Exclude them if you can't get them. */ const dataArray = [ { sn: 'SERIAL_NUMBER', pn: 'PRODUCT_NUMBER' } ]; /* Access token * * The API requires an access token, which it generates from your API key and secret. */ const getAccessToken = () => { const path = tokenPath; const method = 'POST'; const headers = { 'Accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded' } const options = { host, path, port, method, headers }; return new Promise((resolve, reject) => { const req = https.request(options, (res) => { res.setEncoding('utf8'); let raw = ''; res.on('data', (chunk) => { raw += chunk; }); res.on('end', () => { try { const json = JSON.parse(raw); resolve(json.access_token); } catch (err) { reject('There was an error retrieving the access token: ', err); } }); }); req.write(tokenBody); req.end(); }); }; /* Create the batch job */ const createJob = (access_token) => { console.log('Creating new batch job'); const path = queryPath; const method = 'POST'; const headers = { 'Accept': 'application/json', 'Authorization': `Bearer ${access_token}`, 'Content-Type': 'application/json' } const options = { host, path, port, method, headers }; return new Promise((resolve, reject) => { const req = https.request(options, (res) => { res.setEncoding('utf8'); let raw = ''; res.on('data', (chunk) => { raw += chunk; }); res.on('end', () => { try { const json = JSON.parse(raw); console.log(` Batch job created successfully. Job ID: ${json.jobId} Estimated time in seconds to completion: ${json.estimatedTime}\n` ); resolve({ jobId: json.jobId, estimatedTime: json.estimatedTime, access_token }); } catch (err) { reject('There was an error retrieving the jobId: ', err); } }); }); const body = JSON.stringify(dataArray); req.write(body); req.end(); }); } /* Monitor the batch job */ const monitorJob = (result) => { const time = result.estimatedTime > ? : ; console.log(`Next job check in ${time / } minutes\n`); setTimeout(() => { getJobStatus(result); }, time); }; /* Get the current status of the job and print results */ const getJobStatus = (result) => { console.log('Getting job status'); const { jobId, access_token } = result; const path = `${queryPath}/${jobId}`; const headers = { 'Authorization': `Bearer ${access_token}`, 'Accept-Encoding': 'gzip,deflate' } const options = { host, path, port, headers }; const req = https.get(options); req.on('response', (res) => { const buffer = []; const gunzip = zlib.createGunzip(); res.pipe(gunzip); gunzip.on('data', data => { buffer.push(data.toString()); }) .on('end', () => { const json = JSON.parse(buffer.join('')); if (json.status !== 'completed') { if (json.estimatedTime > ) { console.log(`Estimated time in seconds to completion: ${json.estimatedTime}\nNext job check in 10 minutes\n`); setTimeout(() => { getJobStatus(result); }, ); } else if (json.estimatedTime > ) { console.log(`Estimated time in seconds to completion: ${json.estimatedTime}\nNext job check in 5 minutes\n`); setTimeout(() => { getJobStatus(result); }, ); } else if (json.estimatedTime < ) { console.log(`Estimated time in seconds to completion: ${json.estimatedTime}\nNext job check in 1 minute\n`); setTimeout(() => { getJobStatus(result); }, ); } } else { setTimeout(() => { getJobResults(result); }, ); } }); }); }; /* Get the batch job's results * * Here we write the job's results out to console. Modify the output from this * function to suit your needs. For example, use the fs module to write the * output out as a new JSON file. */ const getJobResults = (result) => { const now = new Date().getTime(); const { jobId, access_token } = result; const path = `${queryPath}/${jobId}/results`; const headers = { 'Authorization': `Bearer ${access_token}`, 'Accept-Encoding': 'gzip,deflate' } const options = { host, path, port, headers }; const req = https.get(options); req.on('response', (res) => { if (res.headers['content-encoding'] === 'gzip') { const buffer = []; const gunzip = zlib.createGunzip(); res.pipe(gunzip); gunzip.on('data', data => { buffer.push(data.toString()); }) .on('end', () => { console.log('\nBatch job complete:\n'); const json = JSON.parse(buffer.join('')); json.forEach(entry => { let warrantyString = ''; let active = false; entry.offers.forEach(offer => { const endTime = new Date(offer.serviceObligationLineItemEndDate).getTime(); if (endTime > now) { active = true; } warrantyString = warrantyString + ` Warranty: ${offer.offerDescription} Start Date: ${offer.serviceObligationLineItemStartDate} End Date: ${offer.serviceObligationLineItemEndDate}\n` }); console.log(` SERIAL NUMBER: ${entry.product.serialNumber} STATUS: ${active === false ? 'No active warranty' : 'Warranty active'} WARRANTIES:\n${warrantyString}`); }); const filename = `${jobId}.json`; fs.writeFile(filename, json, err => { if (err) { console.log(`\nWarranty information was retrieved for ${json.length} objects.\nRaw data could not be written to file.`); } else { console.log(`\nWarranty information was retrieved for ${json.length} objects.\nTo view raw data, see ${filename}.`); } }) }); } }); } getAccessToken() .then(access_token => { setTimeout(() => { createJob(access_token) .then(result => monitorJob(result)) .catch(err => console.log(`Something went wrong:\n\n${err}`)); }, ); });
Python for v

Prerequisites (Python)

  • The request library (pip install request)
  • The json library (pip install json)
  • A data source for a dictionary of serial numbers and product numbers

### # warranty-example-python.py # Author: Damon Kaswell, HP Developers Portal (Inspired by Robert Olsen) # Description: Gets warranty information based on product number and serial number. ### import requests import json import time import dateutil.parser import datetime apiKey='Enter API key here' apiSecret='Enter API secret here' tokenBody = { 'apiKey': apiKey, 'apiSecret': apiSecret, 'grantType': 'client_credentials', 'scope': 'warranty' } ### # Input values # # These can come from any source. In this example, we create a dictionary of dummy # values, but any source can be used to populate a dictionary that contains usable # warranty information. ### data = [ { 'sn': '[SERIAL_NUMBER]', 'pn': '[PART_NUMBER]' }, { 'sn': '[SERIAL_NUMBER_2]', 'pn': '[PART_NUMBER_2]' } ] def _url(path): return 'https://css.api.hp.com' + path # Get the access token tokenHeaders = { 'Accept': 'application/json' } tokenResponse = requests.post(_url('/oauth/v1/token'), data=tokenBody, headers=tokenHeaders) tokenJson = tokenResponse.json() token = tokenJson['access_token'] # Create the batch job jobHeaders = { 'Accept': 'application/json', 'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json' } print('Creating new batch job') jobResponse = requests.post(_url('/productWarranty/v2/jobs/'), data=json.dumps(data), headers=jobHeaders) job = jobResponse.json() print('Batch job created successfully.') print('') print('Job ID: ' + job['jobId']) print('Estimated time in seconds to completion: ' + str(job['estimatedTime'])) print('') # Wait before monitoring the job if (job['estimatedTime'] > ): time.sleep(40) else: time.sleep(20) # Monitor the job headers = { 'Authorization': 'Bearer ' + token, 'Accept-Encoding': 'gzip,deflate' } status = 'incomplete' while (status == 'incomplete'): monitorResponse = requests.get(_url('/productWarranty/v2/jobs/' + job['jobId']), headers=headers) monitor = monitorResponse.json() if (monitor['status'] != "completed"): if (monitor['estimatedTime'] > ): print('Estimated time in seconds to completion: ' + str(monitor['estimatedTime']) + '\nNext job check in 10 minutes\n') time.sleep() elif (monitor['estimatedTime'] > ): print('Estimated time in seconds to completion: ' + str(monitor['estimatedTime']) + '\nNext job check in 5 minutes\n') time.sleep() else: print('Estimated time in seconds to completion: ' + str(monitor['estimatedTime']) + '\nNext job check in 1 minute\n') time.sleep(10) else: status = 'complete' # Retrieve results resultsResponse = requests.get(_url('/productWarranty/v2/jobs/' + job['jobId'] + '/results'), headers=headers) results = resultsResponse.json() print 'Batch job complete:' print '' today = datetime.date.today() for r in results: warrantyString = '' statusString = 'No active warranty' for offer in r['offers']: warrantyString += warrantyString + ' Warranty: ' + offer['offerDescription'] + '\n Start Date: ' + offer['serviceObligationLineItemStartDate'] + '\n End Date: ' + offer['serviceObligationLineItemEndDate'] parsed = dateutil.parser.parse(offer['serviceObligationLineItemEndDate']).date() if today < parsed: statusString = 'Warranty active' print '' print 'SERIAL NUMBER: ' + r['product']['serialNumber'] print 'STATUS: ' + statusString print 'WARRANTIES: \n' + warrantyString + '\n' try: f=open(job['jobId'] + '.json', 'w') print >> f, json.dumps(results) print '\nWarranty information was retrieved for ' + str(len(results)) + ' objects.\nTo view raw data, see ' + job['jobId'] + '.json.' f.close() except Exception: print '\nWarranty information was retrieved for ' + str(len(results)) + ' objects.\nRaw data could not be written to file.'
cURL for v

Prerequisites for cURL

  • (Windows) Install from here (external site)
  • A JSON data source for a list of serial numbers and product numbers

# warranty-example-curl.sh # Author: Damon Kaswell, HP Developers Portal # Description: Sample commands to get warranty information based on product number and serial number. # Instructions: # # These commands can be incorporated into a script or run as-is one at a time. Windows users, # make sure you have curl installed. It does not come with Windows by default. # WARNING: Do NOT attempt to run this file as a script as-is. It will not work. # 1. Command to create an access token # Returns: {"access_token":"ACCESS_TOKEN","expires_in":"","scope":"warranty"} # Replace "API_KEY" and "API_SECRET" with your key and secret. "ACCESS_TOKEN" will be a string you use as a bearer token for authentication. curl -d "apiKey=API_KEY&apiSecret=API_SECRET&grantType=client_credentials&scope=warranty" -X POST "https://css.api.hp.com/oauth/v1/token" -H "Accept: application/json" # 2. Create new batch job # Returns: {"jobId":"JOB_ID","estimatedTime":ESTIMATED_TIME} # Replace "SERIAL_NUMBER_#" and "PRODUCT_NUMBER_#" with serial numbers and product numbers. You can also specify a JSON file (e.g., curl -d ./serials.json -X POST) # Replace "ACCESS_TOKEN" with the access token returned in step 1. # NOTE: Product numbers are optional. curl -d '[{"sn":"SERIAL_NUMBER_1", "pn":"PRODUCT_NUMBER_1"},{"sn":"SERIAL_NUMBER_2", "pn":"PRODUCT_NUMBER_2},]' -X POST "https://css.api.hp.com/productWarranty/v2/jobs" -H "Content-Type: application/json" -H "Authorization: Bearer ACCESS_TOKEN" -H "Accept: application/json" # 3. Check the status of the batch job # Returns: {"jobId":"JOB_ID","status":"STATUS","productsProcessed":PRODUCT_COUNT,"expirationDate":"DATE"} # Replace "JOB_ID" with the jobId returned in step 2. # Replace "ACCESS_TOKEN" with the access token returned step 1. # NOTE: A status of "completed" will be returned when the entire batch job is finished. curl --compressed "https://css.api.hp.com/productWarranty/v2/jobs/JOB_ID" -H "Authorization: Bearer ACCESS_TOKEN" -H "Accept: application/json" # 4. Retrieve the final results # Returns:

Scripts for API v

API v gives a single expiration date – the date the current warranty expires.

Here are example scripts for API v

  • PowerShell (Windows) (Submitted by developer Robert Olsén)
  • Node.js (any supported platform)
  • Python (any supported platform)
  • cURL (any supported platform, manual commands only)
  • PHP and more coming soon
PowerShell for v

Prerequisites for PowerShell

  • Active Directory custom properties for serial number and product number
  • PowerShell access with Domain Administrator permissions

### # warranty-example-powershell.ps1 # Author: Robert Olsén (Adapted by HP Developers Portal) # Description: Gets warranty information based on product number and serial number. ### ### # Needed for newer versions of .Net ### [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 ### # Input values # # These can come from any source. In this example, we assume attributes in Active Directory # where the serial and product number is stored, as well as an attribute to store the # warranty information. ### $Computers=Get-ADComputer -Filter {(serialNumber -like '*') -and (productNumber -like '*') -and (warrantyStatus -notlike '*')} -Properties serialNumber,productNumber -ResultSetSize ### # Access token # # The API requires an access token, which it generates from your API key and secret. ### $apiKey="Enter key here" $apiSecret="Enter secret here" $tokenURI="https://css.api.hp.com/oauth/v1/token" $tokenHeaders= @{"accept"="application/json"} $tokenBody="apiKey="+$apiKey+"&apiSecret="+$apiSecret+"&grantType=client_credentials&scope=warranty" $authkeyResponse=Invoke-WebRequest -Method POST -Uri $tokenURI -Headers $tokenHeaders -Body $tokenBody -ContentType application/x-www-form-urlencoded $authkey=($authkeyResponse | ConvertFrom-Json | Select-Object -Property "access_token").access_token ## Create the batch job $queryURI="https://css.api.hp.com/productWarranty/v1/jobs" $queryHeaders= @{} $queryHeaders["accept"] = "application/json" $queryHeaders["Authorization"]="Bearer " + $authkey $queryBody=ConvertTo-Json @(foreach ($computer in $computers){ [ordered]@{"sn"=[string]$computer.serialNumber;"pn"=$computer.productNumber} }) try{ Write-Output "Creating new batch job" $queryResponse=Invoke-WebRequest -Method POST -Uri $queryURI -Headers $queryHeaders -Body $queryBody -ContentType application/json $jobId=($queryResponse | ConvertFrom-Json | Select-Object -Property "jobId").jobId $estimatedTime=($queryResponse | ConvertFrom-Json | Select-Object -Property "estimatedTime").estimatedTime $JobStatusURI=$queryURI+"/"+$jobId $JobResultsURI=$queryURI+"/"+$jobId+"/results" Write-Output "Batch job created successfully." Write-Output "" Write-Output "Job ID: $($jobId)" Write-Output "Estimated time in seconds to completion: $($estimatedTime)" Write-Output "" if ($estimatedTime -gt ) { Write-Output "Next job check in 10 minutes" Write-Output "" Start-Sleep } if ($estimatedTime -lt ) { Write-Output "Next job check in 5 minutes" Write-Output "" Start-Sleep } ### # Monitor the batch job # # This function uses a while loop to intermittently check the status of the job. # While you can increase the frequency here, it isn't recommended, because you # can rapidly run out of queries in a day by checking the status of jobs too # often. ### $JobStatus=Invoke-WebRequest -Method GET -Uri $JobStatusURI -Headers $queryHeaders | ConvertFrom-Json while ($jobstatus.status -ne "completed") { if ($JobStatus.estimatedTime -gt '') { Write-Output "Estimated time in seconds to completion: $($JobStatus.estimatedTime)" Write-Output "Next job check in 10 minutes" Write-Output "" Start-Sleep } if (($JobStatus.estimatedTime -gt '') -and ($JobStatus.estimatedTime -lt '')) { Write-Output "Estimated time in seconds to completion: $($JobStatus.estimatedTime)" Write-Output "Next job check in 5 minutes" Write-Output "" Start-Sleep } if ($JobStatus.estimatedTime -lt '') { Write-Output "Estimated time in seconds to completion: $($JobStatus.estimatedTime)" Write-Output "Next job check in 1 minutes" Write-Output "" Start-Sleep 60 } $JobStatus=Invoke-WebRequest -Method GET -Uri $JobStatusURI -Headers $queryHeaders | ConvertFrom-Json } $JobResults=Invoke-WebRequest -Method GET -Uri $JobResultsURI -Headers $queryHeaders | ConvertFrom-Json ### # Here we write the resulting output to Active Directory. Replace with the appropriate output # mechanism for your environment. For example, use Write-Output to output to the console, or # Out-File to output to a comma-delimited file. ### Write-Output "Writing information to computer objects in Active Directory" foreach ($entry in $JobResults) { $sn=$entry.sn try {Get-ADComputer -filter {SerialNumber -eq $sn} | Set-ADComputer -Replace @{warrantyStatus=$($entry.status);warrantyEndDate=$($entry.endDate)} } catch { Write-Output "Error writing Status: $($entry.status) and EndDate $($entry.endDate) on computer:" (Get-ADComputer -filter {SerialNumber -eq $sn} | select name).name } } Write-Output "Warranty information was updated on $($computers.count) objects." Write-Output "" } catch { Write-Output "Something went wrong:" Write-Output "" $error[0] }
Node.js for v

Prerequisites for Node.js

  • A local installation of Node.js binaries
  • A data source for serial numbers and product numbers in JSON

/* * warranty-example-node.js * Author: Damon Kaswell, HP Developers Portal (Inspired by Robert Olsén) * Description: Gets warranty information based on product number and serial number. */ const https = require('https'); const zlib = require('zlib'); /* Variables */ const apiKey = 'Enter key here'; const apiSecret = 'Enter secret here'; const host = 'css.api.hp.com'; const queryPath = '/productWarranty/v1/jobs'; const tokenPath = '/oauth/v1/token'; const port = ; const tokenBody = `apiKey=${apiKey}&apiSecret=${apiSecret}&grantType=client_credentials&scope=warranty`; /* Input values * * Replace with an appropriate data source for serial numbers and product numbers. * For example, you could use the following syntax to read data from a JSON file: * * const dataArray = require('/path/to/file.json'); * * NOTE: Product numbers are optional. Exclude them if you can't get them. */ const dataArray = [ { sn: 'CNUN3', pn: 'SPUC' }, { sn: '5CGLPY', pn: 'W4R30UC#ABA' } ]; /* Access token * * The API requires an access token, which it generates from your API key and secret. */ const getAccessToken = () => { const path = tokenPath; const method = 'POST'; const headers = { 'Accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded' } const options = { host, path, port, method, headers }; return new Promise((resolve, reject) => { const req = https.request(options, (res) => { res.setEncoding('utf8'); let raw = ''; res.on('data', (chunk) => { raw += chunk; }); res.on('end', () => { try { const json = JSON.parse(raw); resolve(json.access_token); } catch (err) { reject('There was an error retrieving the access token: ', err); } }); }); req.write(tokenBody); req.end(); }); }; /* Create the batch job */ const createJob = (access_token) => { console.log('Creating new batch job'); const path = queryPath; const method = 'POST'; const headers = { 'Accept': 'application/json', 'Authorization': `Bearer ${access_token}`, 'Content-Type': 'application/json' } const options = { host, path, port, method, headers }; return new Promise((resolve, reject) => { const req = https.request(options, (res) => { res.setEncoding('utf8'); let raw = ''; res.on('data', (chunk) => { raw += chunk; }); res.on('end', () => { try { const json = JSON.parse(raw); console.log(` Batch job created successfully. Job ID: ${json.jobId} Estimated time in seconds to completion: ${json.estimatedTime}\n` ); resolve({ jobId: json.jobId, estimatedTime: json.estimatedTime, access_token }); } catch (err) { reject('There was an error retrieving the jobId: ', err); } }); }); const body = JSON.stringify(dataArray); req.write(body); req.end(); }); } /* Monitor the batch job */ const monitorJob = (result) => { const time = result.estimatedTime > ? : ; console.log(`Next job check in ${time / } minutes\n`); setTimeout(() => { getJobStatus(result); }, time); }; /* Get the current status of the job and print results */ const getJobStatus = (result) => { console.log('Getting job status'); const { jobId, access_token } = result; const path = `${queryPath}/${jobId}`; const headers = { 'Authorization': `Bearer ${access_token}`, 'Accept-Encoding': 'gzip,deflate' } const options = { host, path, port, headers }; const req = https.get(options); req.on('response', (res) => { const buffer = []; const gunzip = zlib.createGunzip(); res.pipe(gunzip); gunzip.on('data', data => { buffer.push(data.toString()); }) .on('end', () => { const json = JSON.parse(buffer.join('')); if (json.status !== 'completed') { if (json.estimatedTime > ) { console.log(`Estimated time in seconds to completion: ${json.estimatedTime}\nNext job check in 10 minutes\n`); setTimeout(() => { getJobStatus(result); }, ); } else if (json.estimatedTime > ) { console.log(`Estimated time in seconds to completion: ${json.estimatedTime}\nNext job check in 5 minutes\n`); setTimeout(() => { getJobStatus(result); }, ); } else if (json.estimatedTime < ) { console.log(`Estimated time in seconds to completion: ${json.estimatedTime}\nNext job check in 1 minute\n`); setTimeout(() => { getJobStatus(result); }, ); } } else { setTimeout(() => { getJobResults(result); }, ); } }); }); }; /* Get the batch job's results * * Here we write the job's results out to console. Modify the output from this * function to suit your needs. For example, use the fs module to write the * output out as a new JSON file. */ const getJobResults = (result) => { const { jobId, access_token } = result; const path = `${queryPath}/${jobId}/results`; const headers = { 'Authorization': `Bearer ${access_token}`, 'Accept-Encoding': 'gzip,deflate' } const options = { host, path, port, headers }; const req = https.get(options); req.on('response', (res) => { if (res.headers['content-encoding'] === 'gzip') { const buffer = []; const gunzip = zlib.createGunzip(); res.pipe(gunzip); gunzip.on('data', data => { buffer.push(data.toString()); }) .on('end', () => { console.log('\nBatch job complete:\n'); const json = JSON.parse(buffer.join('')); json.forEach(entry => { console.log(`\nSERIAL NUMBER: ${entry.sn}\nSTATUS: ${entry.status}\nEND DATE: ${entry.endDate}\n`); }); console.log(`\nWarranty information was retrieved for ${json.length} objects.\n`); }); } }); } getAccessToken() .then(access_token => { setTimeout(() => { createJob(access_token) .then(result => monitorJob(result)) .catch(err => console.log(`Something went wrong:\n\n${err}`)); }, ); });
Python for v

Prerequisites (Python)

  • The request library (pip install request)
  • The json library (pip install json)
  • A data source for a dictionary of serial numbers and product numbers

### # warranty-example-python.py # Author: Damon Kaswell, HP Developers Portal (Inspired by Robert Olsen) # Description: Gets warranty information based on product number and serial number. ### import requests import json import time apiKey='Enter key here' apiSecret='Enter secret here' tokenBody = { 'apiKey': apiKey, 'apiSecret': apiSecret, 'grantType': 'client_credentials', 'scope': 'warranty' } ### # Input values # # These can come from any source. In this example, we create a dictionary of dummy # values, but any source can be used to populate a dictionary that contains usable # warranty information. ### data = [ { 'sn': 'CNUN3', 'pn': 'SPUC' }, { 'sn': '5CGLPY', 'pn': 'W4R30UC#ABA' } ] def _url(path): return 'https://css.api.hp.com' + path # Get the access token tokenHeaders = { 'Accept': 'application/json' } tokenResponse = requests.post(_url('/oauth/v1/token'), data=tokenBody, headers=tokenHeaders) tokenJson = tokenResponse.json() token = tokenJson['access_token'] # Create the batch job jobHeaders = { 'Accept': 'application/json', 'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json' } print('Creating new batch job') jobResponse = requests.post(_url('/productWarranty/v1/jobs/'), data=json.dumps(data), headers=jobHeaders) job = jobResponse.json() print('Batch job created successfully.') print('') print('Job ID: ' + job['jobId']) print('Estimated time in seconds to completion: ' + str(job['estimatedTime'])) print('') # Wait before monitoring the job if (job['estimatedTime'] > ): time.sleep() else: time.sleep() # Monitor the job headers = { 'Authorization': 'Bearer ' + token, 'Accept-Encoding': 'gzip,deflate' } status = 'incomplete' while (status == 'incomplete'): monitorResponse = requests.get(_url('/productWarranty/v1/jobs/' + job['jobId']), headers=headers) monitor = monitorResponse.json() if (monitor['status'] != "completed"): if (monitor['estimatedTime'] > ): print('Estimated time in seconds to completion: ' + str(monitor['estimatedTime']) + '\nNext job check in 10 minutes\n') time.sleep() elif (monitor['estimatedTime'] > ): print('Estimated time in seconds to completion: ' + str(monitor['estimatedTime']) + '\nNext job check in 5 minutes\n') time.sleep() else: print('Estimated time in seconds to completion: ' + str(monitor['estimatedTime']) + '\nNext job check in 1 minute\n') time.sleep(60) else: status = 'complete' # Retrieve results resultsResponse = requests.get(_url('/productWarranty/v1/jobs/' + job['jobId'] + '/results'), headers=headers) results = resultsResponse.json() print 'Batch job complete:' print '' for r in results: print '' print 'SERIAL NUMBER: ' + r['sn'] print 'STATUS: ' + r['status'] print 'END DATE: ' + r['endDate'] print ''
cURL for v

Prerequisites for cURL

  • (Windows) Install from here (external site)
  • A JSON data source for a list of serial numbers and product numbers

# warranty-example-curl # Author: Damon Kaswell, HP Developers Portal # Description: Sample commands to get warranty information based on product number and serial number. # Instructions: # # These commands can be incorporated into a script or run as-is one at a time. Windows users, # make sure you have curl installed. It does not come with Windows by default. # 1. Command to create an access token # Returns: {"access_token":"ACCESS_TOKEN","expires_in":"","scope":"warranty"} # Replace "API_KEY" and "API_SECRET" with your key and secret. "ACCESS_TOKEN" will be a string you use as a bearer token for authentication. curl -d "apiKey=API_KEY&apiSecret=API_SECRET&grantType=client_credentials&scope=warranty" -X POST "https://css.api.hp.com/oauth/v1/token" -H "Accept: application/json" # 2. Create new batch job # Returns: {"jobId":"JOB_ID","estimatedTime":ESTIMATED_TIME} # Replace "SERIAL_NUMBER_#" and "PRODUCT_NUMBER_#" with serial numbers and product numbers. You can also specify a JSON file (e.g., curl -d ./serials.json -X POST) # Replace "ACCESS_TOKEN" with the access token returned in step 1. # NOTE: Product numbers are optional. curl -d '[{"sn":"SERIAL_NUMBER_1", "pn":"PRODUCT_NUMBER_1"},{"sn":"SERIAL_NUMBER_2", "pn":"PRODUCT_NUMBER_2},]' -X POST "https://css.api.hp.com/productWarranty/v1/jobs" -H "Content-Type: application/json" -H "Authorization: Bearer ACCESS_TOKEN" -H "Accept: application/json" # 3. Check the status of the batch job # Returns: {"jobId":"JOB_ID","status":"STATUS","productsProcessed":PRODUCT_COUNT,"expirationDate":"DATE"} # Replace "JOB_ID" with the jobId returned in step 2. # Replace "ACCESS_TOKEN" with the access token returned step 1. # NOTE: A status of "completed" will be returned when the entire batch job is finished. curl --compressed "https://css.api.hp.com/productWarranty/v1/jobs/JOB_ID" -H "Authorization: Bearer ACCESS_TOKEN" -H "Accept: application/json" # 4. Retrieve the final results # Returns: <array of results for each entry submitted, in JSON format> # Replace "JOB_ID" with the jobId returned in step 2. # Replace "ACCESS_TOKEN" with the access token returned step 1. # Note: Each member of the array will have a "status" field indicating whether its warranty is expired. curl --compressed "https://css.api.hp.com/productWarranty/v1/jobs/JOB_ID/results" -H "Authorization: Bearer ACCESS_TOKEN" -H "Accept: application/json"
Example web app

Instructions for using the example web application

The example web application will allow you to copy and paste up to serial numbers for batch processing. Note that while it is fully functional, it is intended as an example, not for production use.

Note: The example web app uses Bootstrap styling via CDN, so internet access is required.


<!DOCTYPE HTML> <!-- warranty-example-web.html Author: Damon Kaswell, HP Developers Portal (Inspired by Robert Olsén) Description: Gets warranty information based on a comma-delimited list of serial numbers. --> <html lang="en"> <head> <title="Warranty Lookup API Web Example"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap//css/bootstrap.min.api.hp.com'; const queryPath = '/productWarranty/v1/jobs'; const tokenPath = '/oauth/v1/token'; const tokenBody = `apiKey=${apiKey}&apiSecret=${apiSecret}&grantType=client_credentials&scope=warranty`; let completion; const output = document.getElementById('results'); const progressbar = document.getElementById('progressbar'); /* Access token * * The API requires an access token, which it generates from your API key and secret. */ const getAccessToken = () => { progressbar.innerHTML = 'Getting access token'; progressbar.classList.add('progress-bar-striped', 'progress-bar-animated'); progressbar.setAttribute('style', 'width: 50%;'); const url = `${host}${tokenPath}`; const method = 'POST'; const headers = { 'Accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded' } const options = { method, headers, body: tokenBody }; return fetch(url, options) .then(res => res.json()) .then(result => { progressbar.setAttribute('style', 'width: %;'); output.innerHTML = 'Token fetched, creating batch job'; return result.access_token; }) .catch(err => { progressbar.setAttribute('style', 'width: 0;'); console.log(err); output.innerHTML = 'There was an error retrieving the access token: ' + err; }); }; /* Create the batch job */ const createJob = (access_token) => { progressbar.setAttribute('style', 'width: 50%;'); progressbar.innerHTML = 'Creating batch job'; output.classList.add('alert', 'alert-primary'); const values = document.getElementById('serials').value.split(','); const body = values.map(value => { return { 'sn': value }; }); const url = host + queryPath; const method = 'POST'; const headers = { 'Accept': 'application/json', 'Authorization': `Bearer ${access_token}`, 'Content-Type': 'application/json' } const options = { method, headers, body: JSON.stringify(body) }; return fetch(url, options) .then(res => res.json()) .then(result => { progressbar.setAttribute('style', 'width: %;'); progressbar.innerHTML = 'Batch job created'; output.innerHTML = 'Batch job created sucessfully. Monitoring'; return { jobId: result.jobId, estimatedTime: result.estimatedTime, access_token } }) .catch(err => { console.log(err); progressbar.setAttribute('style', 'width: 0;'); output.innerHTML = 'There was an error retrieving the jobId: ' + err; }); } /* Monitor the batch job */ const monitorJob = (result) => { progressbar.innerHTML = '<span class="text-dark">Waiting for results</span>'; const time = result.estimatedTime > ? : ; completion = +result.estimatedTime; output.innerHTML = `Next job check in ${time / } minutes`; progressbar.setAttribute('style', 'width: 0;'); setTimeout(() => { output.innerHTML = 'Getting job status'; getJobStatus(result); }, time); }; /* Get the current status of the job and print results */ const getJobStatus = (result) => { const { jobId, access_token } = result; const url = `${host}${queryPath}/${jobId}`; const headers = { 'Authorization': `Bearer ${access_token}`, 'Accept-Encoding': 'gzip,deflate' } const options = { headers, method: 'GET' }; fetch(url, options) .then(res => res.json()) .then(resultCheck => { progressbar.setAttribute('style', 'width: ' + Math.floor((resultCheck.estimatedTime / completion) * ) + '%;') if(resultCheck.status !== 'completed') { if (resultCheck.estimatedTime > ) { output.innerHTML = `Estimated time in seconds to completion: ${resultCheck.estimatedTime}. Next job check in 10 minutes`; setTimeout(() => { getJobStatus(result); }, ); } else if (resultCheck.estimatedTime > ) { output.innerHTML = `Estimated time in seconds to completion: ${resultCheck.estimatedTime}. Next job check in 5 minutes`; setTimeout(() => { getJobStatus(result); }, ); } else if (resultCheck.estimatedTime < ) { output.innerHTML = `Estimated time in seconds to completion: ${resultCheck.estimatedTime}. Next job check in 1 minutes`; setTimeout(() => { getJobStatus(result); }, ); } } else { setTimeout(() => { getJobResults(result); }, ); } }) .catch(err => { console.log(err); progressbar.setAttribute('style', 'width: 0;'); }); }; /* Get the batch job's results * * Here we write the job's results out to console. Modify the output from this * function to suit your needs. */ const getJobResults = (result) => { progressbar.innerHTML = 'Getting results'; const { jobId, access_token } = result; const url = `${host}${queryPath}/${jobId}/results`; const headers = { 'Authorization': `Bearer ${access_token}`, 'Accept-Encoding': 'gzip,deflate' } const options = { headers, method: 'GET' }; fetch(url, options) .then(res => res.json()) .then(result => { output.classList.remove('alert', 'alert-primary'); output.innerHTML = 'Job completed successfully. Compiling results'; let final = ''; result.forEach(entry => { final += `<br/>SERIAL NUMBER: ${entry.sn}<br/>STATUS: ${entry.status}<br/>END DATE: ${entry.endDate}<br/>`; }); final += `Warranty information was retrieved for ${result.length} objects.`; output.innerHTML = final; progressbar.setAttribute('style', 'width: %;'); progressbar.classList.remove('progress-bar-striped', 'progress-bar-animated'); progressbar.innerHTML = 'Complete'; }) .catch(err => { progressbar.setAttribute('style', 'width: 0;'); console.log(err); }); } const startJob = () => { getAccessToken() .then(access_token => { setTimeout(() => { createJob(access_token) .then(result => monitorJob(result)) .catch(err => { output.innerHTML = `Something went wrong: ${err}`; console.log(err); }); }, ); }); } document.getElementById('submit').onclick = startJob; </script> </body> </html>

 

Sours: https://developers.hp.com/hp-product-warranty/doc/product-warranty-api-scripts

At least distracting from the pain in the anus. We stroke him, we stroke him (we were surprised, studying the history of the language in the first year, when Fyodor Markovich, our eagle, said that this word, jerk off, now. A slang term, used to mean just fondle). this heir to Qin Shih-huandi and, indeed, a rod.

Api hp warranty check

I remember, rather short-haired, light golden (then I learned - dyed) curly (then I learned - curled) hair, some unusually bright (then I learned - makeup) facial. Features, narrow mirrored glasses, overly bright clothes (clearly memorable details - a casually tied multi-colored neckerchief), below the scarf - a light shirt in bright patterns unbuttoned almost to the navel, under it, in a deep cut of a crimson woolen T-shirt (and the word "neckline" suggests itself), a tanned chest.

Bright green short trousers "tight". Colorful socks.

Register for a MyHPSupport Account - HP Support - @HPSupport

During this time, I counted about two dozen different pets and Lena in some places made two turns at once with the key. Pulling the clamp plates and thereby flattening my penis, head and gently squeezing the eggs. I didnt hurt and I didnt even feel sick, although the distance was slowly but reduced.

Soon Dima joined us and began to explain to me what and how I should do in this or that case.

You will also be interested:

Time the dressing room was filled with the creak of the trestle bed and the squelching of the body on the body. I went into a tight one and without stopping began to watch how someone else's penis penetrates into such a dear pussy. My mouth was dry and I could not utter a word.



530 531 532 533 534