PowerShell表单对接Freshdesk API遇JSON格式错误求助
Hey there, let's tackle that "request body has invalid json format" error you're hitting with your PowerShell Freshdesk integration. I’ve worked through similar API formatting issues before, so here’s a step-by-step breakdown to debug and fix this:
1. Validate Your JSON Serialization
PowerShell’s default ConvertTo-Json has a low depth limit (2 levels) and might mishandle special characters or nested data. Make sure you’re properly serializing your form data with sufficient depth, and that all fields match Freshdesk’s API requirements:
# Example: Structure your ticket data to match Freshdesk's schema $ticketData = @{ subject = $formSubject.Text # Replace with your form control references description = $formDescription.Text email = $formEmail.Text priority = 2 # Freshdesk uses 1-4 (Low to Urgent) status = 2 # Valid status codes depend on your Freshdesk setup } # Convert to JSON with enough depth to handle nested fields $jsonBody = $ticketData | ConvertTo-Json -Depth 10
Pro tip: Print the generated JSON with Write-Host $jsonBody and check for syntax issues like unclosed quotes, trailing commas, or unescaped special characters (newlines, quotes in the description).
2. Fix Your Request Headers
Freshdesk requires specific headers to recognize your JSON payload and authenticate you. Missing or incorrect headers are a common cause of "invalid JSON" errors:
$headers = @{ "Content-Type" = "application/json" # Critical: Tells Freshdesk to expect JSON "Authorization" = "Basic " + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes("$FDApiKey:x")) }
The authorization header uses your API key as the username, with x as a placeholder password (Freshdesk ignores the password field for API key auth).
3. Ensure TLS 1.2 is Enforced Correctly
Your TLS 1.2 line needs to run before making the API call to take effect. Place it at the start of your function:
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
4. Add Detailed Error Handling
Freshdesk often returns specific error details that get hidden in generic exceptions. Add this catch block to see exactly what’s wrong:
try { $response = Invoke-RestMethod -Uri "https://your-subdomain.freshdesk.com/api/v2/tickets" -Method Post -Headers $headers -Body $jsonBody Write-Host "Ticket created! ID: $($response.id)" } catch { Write-Host "Error:" Write-Host "Status Code: $($_.Exception.Response.StatusCode.value__)" # Fetch Freshdesk's detailed error message if ($_.Exception.Response) { $streamReader = New-Object System.IO.StreamReader($_.Exception.Response.GetResponseStream()) $errorDetails = $streamReader.ReadToEnd() | ConvertFrom-Json Write-Host "Freshdesk Error: $($errorDetails.description)" } }
Full Working Example
Putting it all together, your sendRequest function should look something like this:
function sendRequest() { # Configuration $FDApiKey = "your-api-key-here" $freshdeskSubdomain = "your-company" # e.g., if your URL is acme.freshdesk.com, use "acme" # Force TLS 1.2 [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 # Collect form data $ticketData = @{ subject = $formSubject.Text description = $formDescription.Text email = $formEmail.Text priority = 2 status = 2 } # Serialize to valid JSON $jsonBody = $ticketData | ConvertTo-Json -Depth 10 # Set headers $headers = @{ "Content-Type" = "application/json" "Authorization" = "Basic " + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes("$FDApiKey:x")) } # Submit request try { $response = Invoke-RestMethod -Uri "https://$freshdeskSubdomain.freshdesk.com/api/v2/tickets" -Method Post -Headers $headers -Body $jsonBody Write-Host "Ticket submitted successfully! ID: $($response.id)" } catch { Write-Host "Failed to submit ticket:" Write-Host "Status Code: $($_.Exception.Response.StatusCode.value__)" if ($_.Exception.Response) { $reader = New-Object System.IO.StreamReader($_.Exception.Response.GetResponseStream()) $errorJson = $reader.ReadToEnd() | ConvertFrom-Json Write-Host "Freshdesk Details: $($errorJson.description)" } } }
Double-check Freshdesk’s API docs to confirm you’re including all required fields (like subject, description, and email) and using valid values for fields like priority and status.
内容的提问来源于stack exchange,提问作者Justin Merwin

