Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
677 views
in Technique[技术] by (71.8m points)

PHP / Curl Incoming Webhook to MS Teams doesn't work all of the time

I am using an incoming webhook on a web app to post some data to teams. I got this working in CURL after looking up some implementation methods, but it should be noted I have no experience in CURL. The thing is, it works about half the time, then the other half this comes up in the error log:

[01-Feb-2021 09:00:59 Europe/London] Error: Could not resolve host: outlook.office.com

Was hoping someone can take a look and see if there is something obvious I am doing wrong. This is the code used in my PHP file (with the webhook ID removed for privacy)

// Generated by curl-to-PHP: http://incarnate.github.io/curl-to-php/

$ch = curl_init();           
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
curl_setopt($ch, CURLOPT_URL, 'webhook-id-here');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{"text": "$teamsMessage"}");

$headers = array();
$headers[] = 'Content-Type:application/x-www-form-urlencoded';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$result = curl_exec($ch);
if (curl_errno($ch)) {
    error_log("Error: " . curl_error($ch), 0);
}

curl_close($ch);
question from:https://stackoverflow.com/questions/66046872/php-curl-incoming-webhook-to-ms-teams-doesnt-work-all-of-the-time

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Looks like a DNS problem. Could not resolve host: outlook.office.com.

Maybe any firewall involved in blocking that? Remove CURLOPT_SSL_VERIFYPEER and CURLOPT_IPRESOLVE.

Try this simplified solution, which works well for me. I am using JSON header instead of form encoding.

// Paste the URL here
$url = 'https://outlook.office.com/webhook/XXX';

// Use the text encoded as MARKDOWN.
// Any markdown character needs to be escaped!
$body = ['text' => 'Hello World'];

$curlHandle = curl_init($url);
curl_setopt_array($curlHandle, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER     => ['Content-Type: application/json'],
    CURLOPT_POSTFIELDS     => json_encode($body)
]);

$response = curl_exec($curlHandle);
curl_close($curlHandle);
if ($response !== '1') throw new Exception('No Response from MS incoming webhook API');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...