如何使用 Laravel 上的 Guzzle 传递 Header 中的 Zoho-oauthtoken?

How to pass the Zoho-oauthtoken in the Header using Guzzle on Laravel?

我有这个 cURL,我想为 Guzzle

转换
curl_setopt_array($curl, array(
  CURLOPT_URL => "https://subscriptions.zoho.com/api/v1/hostedpages/newsubscription",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS =>"{\n    \"plan\": {\n        \"plan_code\": \"AM-001\",\n        \"price\": " . $gPrice . ",\n        \"tax_id\": \"1786305000000842230\",\n    },\n    \"addons\": [\n        {\n            \"addon_code\": \"AB-001\",\n            \"addon_description\": \"Ads Budget\",\n            \"price\": " . $bPrice . ",\n\n        }\n    ],\n    \"coupon_code\": \"150-credit\"\n    \n}",
  CURLOPT_HTTPHEADER => array(
    "X-com-zoho-subscriptions-organizationid: " . $org_id,
    "Authorization: Zoho-oauthtoken " . $accessToken,
    "Content-Type: application/x-www-form-urlencoded"
  ),
));


目前,我已将其转换为:


$headers = [
            'Authorization' => 'Zoho-oauthtoken ' . $access_token,
            'X-com-zoho-subscriptions-organizationid' => $org_id,
        ];

        $res = $client->request('POST', 'https://subscriptions.zoho.com/api/v1/hostedpages/newsubscription', $headers, [
            'plan' => [
                'plan_code' => 'AM-001',
                'price' => $data['finaltotal'],
                'tax_id' => '1786305000000842230',
            ],
            'addons' =>[
                'addon_code' => 'AB-001',
                'addon_description' => 'Ads Budget',
                'price' => $data['finalads']
            ],
            'coupon_code' => '150-credit'
        ]);


但是我有

“客户端错误:POST https://subscriptions.zoho.com/api/v1/hostedpages/newsubscription 导致 401 Unauthorized 响应: {"code":14,"message":"Invalid value passed for authtoken."}"

我是否正确定义了 header?

感谢您的帮助。

第三个选项是options请求,所以如果你需要传递headers你需要指定key headers.

因此您的代码应如下所示

$options = [
    'headers' => [ // <- here :)
            'Authorization' => 'Zoho-oauthtoken ' . $access_token,
            'X-com-zoho-subscriptions-organizationid' => $org_id,
    ];
]

$res = $client->request(
    'POST',
    'https://subscriptions.zoho.com/api/v1/hostedpages/newsubscription', 
    $options, // <- options
    [
            'plan' => [
                    'plan_code' => 'AM-001',
                    'price' => $data['finaltotal'],
                    'tax_id' => '1786305000000842230',
            ],
            'addons' =>[
                    'addon_code' => 'AB-001',
                    'addon_description' => 'Ads Budget',
                    'price' => $data['finalads']
            ],
            'coupon_code' => '150-credit'
    ]
);

尝试一下应该可以。

如有疑问请评论。