php - Laravel 4 使用数据从 Controller 向外部 URL 发出发布请求

标签 php curl laravel http-post laravel-4

我正在寻找一种从 Controller 向外部 URL 发出发布请求的方法。发布的数据是一个 php 数组。要接收的 url 是外部 url 中的电子商务 API。该帖子必须从 Controller 方法完成。 url 应回复“成功”、“错误”、“失败”或“trylater”字符串。我尝试了以下但没有成功:

    return Redirect::to("https://backoffice.host.iveri.com/Lite/Transactions/New/Authorise.aspx", compact($array));

我也试过 curl :

    $url = 'https://backoffice.host.iveri.com/Lite/Transactions/New/Authorise.aspx';
    //url-ify the data for the POST
    $fields_string ='';
    foreach($array as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
    rtrim($fields_string,'& ');

    //open connection
    $ch = curl_init();

    //set the url, number of POST vars, POST data
    curl_setopt($ch,CURLOPT_URL, $url);
    curl_setopt($ch,CURLOPT_POST, count($array));
    curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    //execute post
    $result = curl_exec($ch);

    //close connection
    curl_close($ch);

发送的数组的一部分是 API 用于响应的回调:

'Lite_Website_Successful_url' => 'https://mydomain.com/order/'.$order_id,
'Lite_Website_Fail_url' => 'https://mydomain.com/checkout/fail',
'Lite_Website_TryLater_url' => 'https://mydomain.com/checkout/trylater',
'Lite_Website_Error_url' => 'https://mydomain.com/checkout/error'

请让我知道如何正确地执行 POST 请求,并将其携带的数据发送到外部 url。来自 Controller 的 ajax 帖子也会有所帮助,但我尝试过但没有成功。但我更喜欢 laravel php 的答案。谢谢。

最佳答案

我们可以在 Laravel 中使用 Guzzle 包,它是一个用于发送 HTTP 请求的 PHP HTTP 客户端。

你可以通过composer安装Guzzle

composer require guzzlehttp/guzzle:~6.0

或者您可以将 Guzzle 指定为项目现有 composer.json 中的依赖项

{
   "require": {
      "guzzlehttp/guzzle": "~6.0"
   }
}

在laravel中POST请求的示例代码,使用Guzzle如下所示,

use GuzzleHttp\Client;
class yourController extends Controller {
public function saveApiData()
{
    $client = new Client();
    $res = $client->request('POST', 'https://url_to_the_api', [
        'form_params' => [
            'client_id' => 'test_id',
            'secret' => 'test_secret',
        ]
    ]);

    $result= $res->getBody();
    dd($result);

关于php - Laravel 4 使用数据从 Controller 向外部 URL 发出发布请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18770184/

相关文章:

php - 如何在 php 中创建带有嵌套对象的响应 json?

php - 如何使用 POST 将变量传递到下一页

php - 如何防止导航栏元素重叠?

linux - 在 bash 脚本中使用 curl 并获取 curl : (3) Illegal characters found in URL

bash - 用于代理和网页登录的 curl 命令

laravel - 如何禁用Laravel Scheduler日志

php - 获取变量数组的数据库数据

php - Stripe native PHP 库与使用普通 cURL

php - Laravel/MYSQL (Eloquent) - 查询大表

Laravel 护照 : Is it possible to set expire_at for each access_token separately?