php 在laravel中使用guzzle发布请求

lvjbypge  于 2023-04-19  发布在  PHP
关注(0)|答案(1)|浏览(118)

我试图通知一个松弛通道每当一个新的订单出现在我们的网站。但我很难在Laravel执行此 curl 请求
curl -X POST --data-urlencode "payload={\"channel\": \"#new-order\", \"username\": \"product-notifier\", \"text\": \"New Orders: \n https://mission-control.airbringr.com/orders/item/411980\", \"icon_emoji\": \":smiley:\"}" https://hooks.slack.com/services/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
我一直在想办法

public function slack(Request $request){
        $client = new \GuzzleHttp\Client();
        try {
        
            $client = new Client();
            
            $response = $client->post('https://hooks.slack.com/services/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',[
                'json' => [
                    'payload' =>
                        ['channel'=>'#new-order','username'=> 'product-notifier', 'text'=>'New Orders: \n https://mission-control.airbringr.com/orders/item/411980', 'icon_emoji'=>':smiley:']
                        ],
                        ]
                        
            );
        } catch (\Exception $e) {
            return response()->json($e->getMessage(), 400);
        }
        return response()->json(["message" => "notified successfully"], 200);
    }

但我得到了"Client error:POST https://hooks.slack.com/services/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resulted in a400 Bad Requestresponse:\nmissing_text_or_fallback_or_attachments\n"

但是curl请求在我的终端中工作正常。

有什么建议可以让我做这件事吗?

enyaitl3

enyaitl31#

至少你不需要把数据 Package 在一个有效载荷键中。你可以在文档here中看到。

$response = $client->post('https://hooks.slack.com/services/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',[
    'json' => [
        'channel'=>'#new-order',
        'username'=> 'product-notifier',
        'text'=>'New Orders: \n https://mission-control.airbringr.com/orders/item/411980', 'icon_emoji'=>':smiley:'
        ]
    ],
);

相关问题