You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Azure Function无法解析Pipedream发送的JSON问题求助

问题:Azure Function无法解析Pipedream发送的JSON数据

我是MSP(托管服务提供商)员工,正在搭建员工离职自动化流程:用Pipedream接收HTTP请求处理后转发到Azure Function,通过PowerShell调用Exchange Online API将用户邮箱转为共享邮箱(Graph API不支持此操作)。

目前核心问题:Azure Function无法解析Pipedream发送的JSON,导致邮箱转换逻辑无法触发。已排除以下问题:

  • Pipedream发送的JSON格式正确({"Name": "***"})
  • 请求URL包含有效函数密钥
  • Azure Function内的邮箱转换逻辑单独测试正常

Pipedream发送请求的Python代码

import requests
import json

def handler(pd: "pipedream"):
    url = "***"
    headers = {
        "Content-Type": "application/json"
    }
    
    username_value = pd.steps["create_username"]["$return_value"]["username"]
    payload = {
      "Name": username_value
    }
    
    response = requests.post(url, headers=headers, json=payload)
    
    print("Payload being sent:", json.dumps(payload))
    print("Status Code:", response.status_code)
    print("Response Body:", response.text)

Azure Function PowerShell代码

using namespace System.Net

# Input bindings are passed in via param block.
param($Request, $TriggerMetadata)

# Add initial logging
Write-Host "Function triggered"

# Variables for OAuth 2.0 authentication
$tenantId = "***"
$clientId = "***"
$clientSecret = "***"
$tokenEndpoint = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token"

# Log the raw request body
Write-Host "Raw Request Body: $($Request.Body)"

# Try to parse the JSON request body
try {
    $requestBody = $Request.Body | ConvertFrom-Json
}
catch {
    Write-Host "Failed to parse JSON: $_"
    return
}

# Extract the "Name" value from the JSON request
$name = $requestBody.Name

# Log the extracted name value
Write-Host "Extracted Name: $name"

# Ensure that $name has a value
if (-not [System.String]::IsNullOrEmpty($name)) {
    Write-Host "Name parameter received: $name"

    try {
        Write-Host "Obtaining access token"
        $body = @{
            grant_type    = "client_credentials"
            scope         = "https://outlook.office365.com/.default"
            client_id     = $clientId
            client_secret = $clientSecret
        }
        $tokenResponse = Invoke-RestMethod -Method Post -Uri $tokenEndpoint -ContentType "application/x-www-form-urlencoded" -Body $body
        $accessToken = $tokenResponse.access_token

        Write-Host "Access token obtained successfully."

        # Connect to Exchange Online using the obtained access token
        Write-Host "Connecting to Exchange Online"
        Connect-ExchangeOnline -AppId $clientId -AccessToken $accessToken -Organization $tenantId -ShowBanner:$false

        # Convert the mailbox to shared
        Write-Host "Converting mailbox to shared: $name"
        Set-Mailbox -Identity $name -Type Shared -ErrorAction Stop
        Write-Host "Mailbox converted to shared successfully."
    }
    catch {
        Write-Host "Error during script execution: $_"
    }
}
else {
    Write-Host "Name parameter is missing or empty in the JSON request."
}

Write-Host "Script execution completed."

Azure Function依赖文件

# This file enables modules to be automatically managed by the Functions service.
# See https://aka.ms/functionsmanageddependency for additional information.
#
@{
    # For latest supported version, go to 'https://www.powershellgallery.com/packages/Az'. 
    # To use the Az module in your function app, please uncomment the line below.
    # 'Az' = '12.*'
    'ExchangeOnlineManagement' = '3.*'
    'PowerShellGet' = '2.*'
    'PackageManagement' = '1.*'
}

函数调用日志

8/8/2024, 12:24:36 PM
Information
Executing 'Functions.Convert_to_Shared_Mailbox' (Reason='This function was programmatically called via the host APIs.', Id=97bb041f-a775-4091-ad9e-aeb8314dc193)

8/8/2024, 12:24:37 PM
Information
INFORMATION: Function triggered

8/8/2024, 12:24:37 PM
Information
INFORMATION: Raw Request Body: System.Management.Automation.OrderedHashtable

8/8/2024, 12:24:37 PM
Information
INFORMATION: Failed to parse JSON: Conversion from JSON failed with error: Unexpected character encountered while parsing value: S. Path '', line 0, position 0.

8/8/2024, 12:24:37 PM
Information
Executed 'Functions.Convert_to_Shared_Mailbox' (Succeeded, Id=97bb041f-a775-4091-ad9e-aeb8314dc193, Duration=1104ms)

解决方案

从日志可见,$Request.Body已经是OrderedHashtable类型,说明Azure Functions的PowerShell运行时已经自动将JSON解析为哈希表,无需再执行ConvertFrom-Json,这是解析失败的核心原因。

修改后的Azure Function代码如下:

using namespace System.Net

param($Request, $TriggerMetadata)

Write-Host "Function triggered"

$tenantId = "***"
$clientId = "***"
$clientSecret = "***"
$tokenEndpoint = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token"

# 直接从已解析的哈希表中获取Name参数
$name = $Request.Body.Name

Write-Host "Extracted Name: $name"

if (-not [System.String]::IsNullOrEmpty($name)) {
    Write-Host "Name parameter received: $name"

    try {
        Write-Host "Obtaining access token"
        $body = @{
            grant_type    = "client_credentials"
            scope         = "https://outlook.office365.com/.default"
            client_id     = $clientId
            client_secret = $clientSecret
        }
        $tokenResponse = Invoke-RestMethod -Method Post -Uri $tokenEndpoint -ContentType "application/x-www-form-urlencoded" -Body $body
        $accessToken = $tokenResponse.access_token

        Write-Host "Access token obtained successfully."

        Write-Host "Connecting to Exchange Online"
        Connect-ExchangeOnline -AppId $clientId -AccessToken $accessToken -Organization $tenantId -ShowBanner:$false

        Write-Host "Converting mailbox to shared: $name"
        Set-Mailbox -Identity $name -Type Shared -ErrorAction Stop
        Write-Host "Mailbox converted to shared successfully."
    }
    catch {
        Write-Host "Error during script execution: $_"
    }
}
else {
    Write-Host "Name parameter is missing or empty in the JSON request."
}

Write-Host "Script execution completed."

关键修改点:

  • 删除了ConvertFrom-Json的解析代码,直接通过$Request.Body.Name获取参数
  • 若需要保留请求体日志,可改为Write-Host "Raw Request Body: $($Request.Body | ConvertTo-Json)",以JSON格式打印已解析的哈希表

内容的提问来源于stack exchange,提问作者CodeWithClark

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 17:14:56