使用PHP表单的Slack Incoming Webhook

时间:2015-08-11 11:20:44

标签: php html json slack-api

我正在尝试创建一个PHP脚本,该脚本会自动将文本从我的webform中的<textarea>推送到Slack通道。

HTML:

<form action="http://main.xfiddle.com/<?php echo pf_file('g7f-ds0'); ?>" method="post" id="myform" name="myform">   
<textarea name="text" id="" rows="3" cols="30">
</textarea> <br /><br />
<button id="mysubmit" type="submit" name="submit">Submit</button><br /><br /></form>

我设法编写了一个PHP脚本,将硬编码消息发布到Slack,如下所示:

    <?php

//API Url
$url = 'https://hooks.slack.com/services/T02NZ01FU/B08TTAPGE/000000000000000000';

//Initiate cURL.
$ch = curl_init($url);

//The JSON data.
$payload = array(
   ’text' => 'Testing text with PHP'
);

//Encode the array into JSON.
$jsonDataEncoded = json_encode($payload);

//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);

//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);

//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); 

//Execute the request
$result = curl_exec($ch);
?>

但出于某种原因,当我尝试从<textarea name="text" rows="3" cols="30"></textarea>获取文本并将其保存到变量中时,它不起作用。我将它添加到PHP的开头以设置文本变量:

if(isset($_POST['submit']))
$textdata = $_POST['text'];

然后将$ payload更改为

'text' => $textdata

2 个答案:

答案 0 :(得分:1)

如何使用curl

来缓解传入的webhook的一个简单示例
<?php
define('SLACK_WEBHOOK', 'https://hooks.slack.com/services/xxx/yyy/zzz');
function slack($txt) {
  $msg = array('text' => $txt);
  $c = curl_init(SLACK_WEBHOOK);
  curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($c, CURLOPT_SSL_VERIFYPEER, false);
  curl_setopt($c, CURLOPT_POST, true);
  curl_setopt($c, CURLOPT_POSTFIELDS, array('payload' => json_encode($msg)));
  curl_exec($c);
  curl_close($c);
}
?>

摘自here

的摘录

答案 1 :(得分:0)

这里有两个可能的问题。

  1. 帖子中的PHP格式不正确。

    ’text' => 'Testing text with PHP'替换为 'text' => 'Testing text with PHP'

  2. 您的卷曲设置不正确。请参阅以下帖子debug curl并修正可能出现的错误 - no trusted SSL certificates