【发布时间】:2020-02-21 10:28:38
【问题描述】:
我正在尝试将 JSON 编码数据发布到驻留在我们公司 Microsoft Teams 频道之一中的 webhook 端点。它接受基本的 JSON 编码负载。
我从本地计算机上的 PostMan 开始,并将以下内容发布到我的团队频道连接器 webhook URL:
{
"@context": "https://schema.org/extensions"
"@type": "MessageCard",
"themeColor": "0072C6",
"title": "Test From PostMan",
"text": "This is the text body of the notification card",
"potentialAction": [
{
"@type": "OpenUri",
"name": "View in Browser...",
"targets": [
{ "os": "default", "uri": "https://<REDACTED>" }
]
}
]
}
这很好用,它会将卡片发布到 Teams 频道,并在其下方显示操作按钮。
所以我转向 PHP,并编写了以下代码:
<?php
//api endpoint
$url = 'https://<REDACTED>';
//new curl connection
$ch = curl_init($url);
//build json data array
$postdata = array(
'@context' => 'https://schema.org/extensions',
'@type' => 'MessageCard',
'themeColor' => '0072C6',
'title' => 'Test from curl in PHP',
'text' => 'test string.. test string.. test string.. test string.. test string.. test string.. test string..',
'potentialAction' => array (
'@type' => 'OpenUri',
'name' => 'View in Browser...',
'targets' => array (
'os' => 'default',
'uri' => 'https://<REDACTED>'
)
)
);
//encode json data array
$encodeddata = json_encode($postdata);
//set curl options
curl_setopt($ch, CURLOPT_POSTFIELDS, $encodeddata);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
//debug
echo $result;
//close
curl_close($ch);
?>
当我运行上述程序时,API 出错并响应说它是无效的有效负载。所以我剥离了我的代码,这样我的$postdata 数组就简单多了,如下所示:
//build json data array
$postdata = array(
'@context' => 'https://schema.org/extensions',
'@type' => 'MessageCard',
'themeColor' => '0072C6',
'title' => 'Test from curl in PHP',
'text' => 'test string.. test string.. test string.. test string.. test string.. test string.. test string..'
);
这很好用,我的 PHP 脚本能够将卡片发布到 Teams 频道,只是它下面没有操作按钮。所以我的问题在于我如何在 $postdata 中编码额外的数组?
老实说,我对 PHP 数组的了解有限,我认为我这样做是正确的,但显然我遇到了问题,哈哈。是否有不同/更好/更正确的方法将数组内的多个数组编码为 JSON 数据以进行 POST?
【问题讨论】:
-
我建议您尝试发布到仅转储 $_POST 的本地 PHP 脚本,然后在 JSON 验证器(即jsonlint.com)上验证整个发布 JSON 有效负载。