【问题标题】:convert curl to guzzle for spreedly API将 curl 转换为 guzzle 以获取快速 API
【发布时间】:2015-03-17 17:13:41
【问题描述】:

我正在尝试将此 curl 调用转换为 guzzle:

curl https://core.spreedly.com/v1/gateways/CAL6uXHtGfDsxV2kW6apTP5JhG/purchase.xml \
-u 'Ll6fAtoVY5hTGlJEmtpo5YTS:RKOCG5D8jhgfdDSg524u5iF22XD4Io5VXmyzdCptrvHFTTSy' \
-H 'Content-Type: application/xml' \
-d '<transaction>
      <payment_method_token>ZgPNHes541EMlBN86glRDKRexzq</payment_method_token>
      <amount>100</amount>
      <currency_code>USD</currency_code>
    </transaction>'

我知道使用它这么多,所以任何帮助将不胜感激

这是我尝试过的,但我总是收到此错误“客户端错误响应 【状态码】422 [原因短语] 无法处理的实体”

$xml =  '<transaction>\n';
$xml .=     '<payment_method_token>$payment_method_token</payment_method_token>\n';
$xml .=     '<amount>100</amount>\n';
$xml .=     '<currency_code>USD</currency_code>\n'
$xml .= '<transaction>\n';
$headers = ['Content-Type' => 'application/xml', 'auth' => ['Ll6fAtoVY5hTGlJEmtpo5YTS', 'RKOCG5D8jhgfdDSg524u5iF22XD4Io5VXmyzdCptrvHFTTSy']];
$client = new Client('https://core.spreedly.com/v1/gateways/CAL6uXHtGfDsxV2kW6apTP5JhG/purchase.xml');
$requestCurl = $client->post('', $headers, $xml,[]);
$response = $requestCurl->send()->xml();
dd($response);

谢谢!

【问题讨论】:

  • 好吧,一方面$payment_method_token 不会被评估,因为它在单引号内而不是双引号内。也许在发送之前尝试吐出你的 $xml 变量,以确保它看起来不错?
  • 是的,我进行了更改并且 $xml 看起来不错...现在我有此错误“客户端错误响应 [状态代码] 401 [原因短语] 未经授权”我确定凭据是正确的。 ..也许我错过了一些sintax

标签: php laravel curl guzzle spreedly


【解决方案1】:

它应该看起来像这样:

$client = new Client('https://core.spreedly.com/v1/gateways/merchant_id');

$xml = '<...>';
$options = [
    'headers'   => [ 'Content-Type' => 'application/xml' ],
    'auth'      => ['username', 'password'],
    'body'      => $xml,
];

$response = $client->post('/purchase.xml', $options);

您可能想再看看您的代码,并确定您是否不小心公开了您的 API 凭据。

【讨论】:

  • 在不公开发布 api 凭据的情况下发布帖子的正确方法是什么?
  • @AndrésBaquerizoNúñez 你误会了。您已在您的原始帖子中公开发布了您的凭据在此站点上
  • 不,别担心,我在发布之前更改了它们。
【解决方案2】:

如果您参考 Guzzle Docs 以使用 Clients,您将看到您可以为客户端发出的所有请求设置 base_url、标头和身份验证。

下面的示例与上面的 Sammitch 示例之间的区别在于,我已将标头和身份验证作为默认值添加到客户端。这将允许对您的 api 进行后续调用,而无需将这些作为选项添加到每个请求中。

出于故障排除的目的,我只是附加了 LogSubscriber,以便随时可以使用 http 请求和响应。

$client = new GuzzleHttp\Client([
    'base_url' => ['https://core.spreedly.com/{version}/gateways/{merchant_id}/', [
        'version' => 'v1',
        'merchant_id' => $merchant_id
    ]],
    'defaults' => [
        'headers'       => ['Content-Type' => 'application/xml'],
        'auth'          => [$username, $pw],
]]);
/**
* Attach a log subscriber is configured to log the full request and response message using echo() calls.
**/
$client->getEmitter()->attach(new GuzzleHttp\Subscriber\Log\LogSubscriber(null, GuzzleHttp\Subscriber\Log\Formatter::DEBUG));

$response = $client->post('purchase.xml', [
    'body' => $xml
]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-30
    • 2016-03-21
    • 1970-01-01
    • 1970-01-01
    • 2014-09-17
    • 2015-11-02
    • 2021-09-08
    • 2021-02-19
    相关资源
    最近更新 更多