0

我正在做一个项目,我正在使用 api 与单独站点上的电子商务商店进行交互。我可以通过 api 将项目添加到购物篮,并使用 cURLS CookieJar 来保存状态。要结帐,我只想链接到主要电子商务网站上的实际结帐流程。但是,我需要能够将存储在 CookieJar 中的 cookie 与重定向请求一起发送。

我尝试使用 cURL 来获取 cookie,然后进行重定向,但我误解了它的工作原理。它不是重定向浏览器,而是基于 302 重定向发出一个新的 cURL 请求。

$curlopt = array(
    CURLOPT_COOKIEJAR => xxx, // this is the path to the cookie file
    CURLOPT_COOKIEFILE => xxx, // this is the path to the cookie file
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_AUTOREFERER => true,
    CURLOPT_URL => 'http://mydomain.com/redirect_to_ecommerce_checkout.php'
);

$ch = curl_init(); // run curl
curl_setopt_array($ch, $curlopt);
curl_exec($ch);
curl_close($ch);

这似乎确实将正确的 cookie 发送到电子商务页面,问题是浏览器没有重定向,而是从我的域上的主要电子商务站点呈现 HTML。

如何设置请求 cookie 并实际执行重定向?

提前致谢。

4

1 回答 1

0

我认为你只需要告诉 CURL 给你标题而不是遵循重定向。然后,您可以解析“位置:”标题。像这样的东西:

$curlopt = array(
    CURLOPT_COOKIEJAR => xxx, // this is the path to the cookie file
    CURLOPT_COOKIEFILE => xxx, // this is the path to the cookie file
    CURLOPT_FOLLOWLOCATION => false, // <--- change to false so curl does not follow redirect
    CURLOPT_AUTOREFERER => true,
    CURLOPT_URL => 'http://mydomain.com/redirect_to_ecommerce_checkout.php',
    CURLOPT_HEADER => true,
    CURLOPT_RETURNTRANSFER => true // Return transfer string instead of outputting directly
);

$ch = curl_init($url);
curl_setopt_array($ch, $curlopt);
$response = curl_exec($ch); // save response to a variable
curl_close($ch);

// try to find Location header in $response
preg_match_all('/^Location:(.*)$/mi', $response, $matches);

if (!empty($matches[1])) {
    header("Location: " . trim($matches[1][0]) );
    exit;
}
else {
    echo 'No redirect found';
}

请注意,我设置了 CURLOPT_FOLLOWLOCATION => false、CURLOPT_HEADER => true 和 CURLOPT_RETURNTRANSFER => true,然后检查了我保存在 $response 中的 curl_exec() 响应。

你也可以试试:

header("Location: " . curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
于 2013-10-15T21:44:15.637 回答