PHP->肥皂-> Magento Webservice:获取 Magento 设置的 Cookie

发布于 2024-10-31 03:34:34 字数 2630 浏览 0 评论 0原文

我是 Magento Web 服务的新手,必须扩展它。 Webservice shell 能够登录客户,给我返回会话 cookie,以便我可以重定向到再次设置 cookie 的文件,重定向我,然后我可以看到我的购物车并继续在 Magento 商店结账。

问题: Magento 创建一个 cookie(包含会话 id 或其他内容,我尝试手动设置此 cookie 并且他们已登录),而不是在客户登录时设置会话。 我已经尝试了几个小时来获取由 magento 在我的 magento 网络服务中设置的 cookie。当我调用 Heres 我的完整代码时,似乎未设置 cookie

$session = Mage::getSingleton('customer/session');
return $session->getCookie()->get('frontend');

: Magento Webservice Api:

<?php 
class Customapi_Model_Core_Api
{

public function __construct()
{
}

public function checkout($user, $cart)
{
    $ret['cookie'] = $this->login($user);

    //$coreCookie = Mage::getSingleton('core/cookie');
    //$ret['cookie'] = $_COOKIE['frontend'];
    return $ret;
}

function login($user)
{
    Mage::getSingleton('core/session', array('name'=>'frontend'));
    $session = Mage::getSingleton('customer/session');
    try
    {
        $session->loginById($user['id']);
    }
    catch (Exception $e)
    {
    }
    return $session->getCookie()->get('frontend');
}

}
?>

这是我在 Php 中的 Api 调用:

<?php
$teambook_path = 'http://localhost/magento/';

$soap = new SoapClient('http://localhost/magento/api/?wsdl');
$soap->startSession();
$sessionId = $soap->login('ApiUser', 'ApiKey');

$userSession = $soap->call(
    $sessionId,
    'customapi.checkout',
    array(
        array(
            'id' => 1,
            'username' => '[email protected]',
            'password' => '***'
        ),
        array(
        )
    )
);

echo '<pre>';
var_dump($userSession)."\n";
if(isset($userSession['sid']))
    echo '<a href="'.$teambook_path.'session.php?sid='.$userSession['sid'].'" target="_blank">'.$userSession['sid'].'</a>'."\n";
echo '</pre>';

$soap->endSession($sessionId);
?>

感谢您的每一个帮助! MRu


抱歉,我正在写答案,但评论框拒绝我写超过...的信件。

我已经尝试过您发布的两个代码,但我得到的只是一个空数组或 Bool false。 我写了一个静态函数:

private static $cookie = array();
public static function cookie($key, $value)
{
    if($key == 'frontend') {
        self::$cookie['key']   = $key;
        self::$cookie['value'] = $value;
    }
}

在 Mage_Core_Model_Session_Abstract_Varien::start 中调用,我得到了前端 cookie 值:

Customapi_Model_Core_Api::cookie($sessionName, $this->getSessionId());

在第 125 行。

但这并没有解决我的基本问题: 在 Api 调用中创建的 Session 无法恢复,尽管它设置为正确的值。

感谢您的帮助!

I am new to Magento Web-Service and have to expand it.
The Webservice shell be able to login an customer, give me the session cookie back so that I can redirect to a file that sets the cookie again, redirects me and I can see my cart and proceed to checkout on the Magento Store.

The Problem:
Magento creates a cookie (that contains the session id or whatever, ive tried to set this cookie manual and them im logged in) instead of setting a session when the customer logs in.
I've tried now for several hours to get this cookie that is set by magento in my magento web-service. It seems the cookie isn't set when i call

$session = Mage::getSingleton('customer/session');
return $session->getCookie()->get('frontend');

Heres my complete Code:
Magento Webservice Api:

<?php 
class Customapi_Model_Core_Api
{

public function __construct()
{
}

public function checkout($user, $cart)
{
    $ret['cookie'] = $this->login($user);

    //$coreCookie = Mage::getSingleton('core/cookie');
    //$ret['cookie'] = $_COOKIE['frontend'];
    return $ret;
}

function login($user)
{
    Mage::getSingleton('core/session', array('name'=>'frontend'));
    $session = Mage::getSingleton('customer/session');
    try
    {
        $session->loginById($user['id']);
    }
    catch (Exception $e)
    {
    }
    return $session->getCookie()->get('frontend');
}

}
?>

Heres my Api Call in Php:

<?php
$teambook_path = 'http://localhost/magento/';

$soap = new SoapClient('http://localhost/magento/api/?wsdl');
$soap->startSession();
$sessionId = $soap->login('ApiUser', 'ApiKey');

$userSession = $soap->call(
    $sessionId,
    'customapi.checkout',
    array(
        array(
            'id' => 1,
            'username' => '[email protected]',
            'password' => '***'
        ),
        array(
        )
    )
);

echo '<pre>';
var_dump($userSession)."\n";
if(isset($userSession['sid']))
    echo '<a href="'.$teambook_path.'session.php?sid='.$userSession['sid'].'" target="_blank">'.$userSession['sid'].'</a>'."\n";
echo '</pre>';

$soap->endSession($sessionId);
?>

Thanks for every help!
MRu


Sorry i am writing an answer but the comment box denied me to write more than ... letters.

I've tried both codes you posted and all I get is an empty Array or Bool false.
I wrote a static function:

private static $cookie = array();
public static function cookie($key, $value)
{
    if($key == 'frontend') {
        self::$cookie['key']   = $key;
        self::$cookie['value'] = $value;
    }
}

that is called in Mage_Core_Model_Session_Abstract_Varien::start and I got the frontend cookie value:

Customapi_Model_Core_Api::cookie($sessionName, $this->getSessionId());

in line 125.

But that didnt solve my basic Problem:
The Session created in the Api call can't be restored, although it is set to the correct value.

Thanks for your help!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

深爱不及久伴 2024-11-07 03:34:34

您可以使用以下命令获取所有 cookie 的数组:

Mage::getModel('core/cookie')->get();

可以像这样检索前端 cookie:

Mage::getModel('core/cookie')->get('frontend');

从您注释的代码中我可以看到您已经知道这一点。

据我所知,当您登录用户时,Magento 不仅仅创建一个新的会话 ID,它还使用活动连接的会话 ID(由 PHP 本身生成)。您正在登录用户并将其关联到 API 客户端刚刚使用 Magento 创建的会话。因此,您注释的代码似乎对于您想要实现的目标是正确的。

现在您应该只需要获取返回的会话 ID 并在新请求中将其用作“前端”cookie。

编辑(第二次)

Magento 在单个 PHP 会话内有不同的会话,用于不同的范围。例如,有核心范围、客户范围等。但是,客户范围也是特定于给定网站的。因此,您可以拥有 customer_website_one 和 customer_website_two 范围。

如果你想登录你的用户,你必须告诉 Magento 在哪个网站。以下面的代码为例

// This code goes inside your Magento API class method

// These two lines get your website code for the website with id 1
// You can obviously simply hardcode the $code variable if you prefer
// It must obviously be the website code to which your users will be redirected in the end
$webSites = Mage::app()->getWebsites();
$code = $webSites[1]->getCode();

$session = Mage::getSingleton("customer/session"); // This initiates the PHP session
// The following line is the trick here. You simulate that you 
// entered Magento through a website (instead of the API) so if you log in your user
// his info will be stored in the customer_your_website scope
$session->init('customer_' . $code);
$session->loginById(4);  // Just logging in some example user
return session_id();     // this holds your session id

如果我理解正确的话,您现在想让用户在您的服务器中打开一个 PHP 脚本,将 Magento Cookie 设置为您刚刚在 API 方法中返回的内容。我编写了以下示例,您可以像这样访问它: example.com/set_cookie.php?session=THE_RETURNED_SESSION_ID

<?php
// Make sure you match the cookie path magento is setting
setcookie('frontend', $_GET['session'], 0, '/your/magento/cookie/path');
header('Location: http://example.com');
?>

应该可以。您的用户现在已登录(至少我让它在我的测试环境中工作)。您应该记住的一件事是 Magento 有一个会话验证机制,如果启用该机制将会失败。这是因为您的会话存储有关您正在使用的浏览器、您连接的 IP 等信息。这些数据在以后通过 API 方法和浏览器进行的调用之间将不匹配。以下是在 API 方法中设置会话后命令 print_r($session->getData()) 的示例输出

[_session_validator_data] => Array
(
    [remote_addr] => 172.20.1.1
    [http_via] => 
    [http_x_forwarded_for] => 
    [http_user_agent] => PHP-SOAP/5.3.5
)

确保您在 Magento 管理中的“设置”>“设置”中关闭了验证。配置>一般>网页>会话验证设置

You can get an array of all your cookies with the following command:

Mage::getModel('core/cookie')->get();

The frontend cookie can be retrieved like this:

Mage::getModel('core/cookie')->get('frontend');

From your commented code I can see that you already knew that.

As far as I know, when you log in a user, Magento doesn't just create a new session id, it uses the session id of the active connection (which is generated by PHP itself). You are logging in the user and associating him to the session that your API client just created with Magento. Thus, the code that you have commented seems to be correct for what you are trying to achieve.

Now you should just need to get the returned session id and use it in your new request as the 'frontend' cookie.

Edit (a second time)

Magento has different sessions inside a single PHP session which it uses for different scopes. For instance, there is the core scope, the customer scope, etc. However, the customer scope is also specific to a given website. So, you can have a customer_website_one and a customer_website_two scope.

If you want to log in your user, you have to tell Magento in which website that is. Take the following code as an example

// This code goes inside your Magento API class method

// These two lines get your website code for the website with id 1
// You can obviously simply hardcode the $code variable if you prefer
// It must obviously be the website code to which your users will be redirected in the end
$webSites = Mage::app()->getWebsites();
$code = $webSites[1]->getCode();

$session = Mage::getSingleton("customer/session"); // This initiates the PHP session
// The following line is the trick here. You simulate that you 
// entered Magento through a website (instead of the API) so if you log in your user
// his info will be stored in the customer_your_website scope
$session->init('customer_' . $code);
$session->loginById(4);  // Just logging in some example user
return session_id();     // this holds your session id

If I understand you correctly, you now want to let the user open a PHP script in your server that sets the Magento Cookie to what you just returned in your API method. I wrote the following example which you would access like this: example.com/set_cookie.php?session=THE_RETURNED_SESSION_ID

<?php
// Make sure you match the cookie path magento is setting
setcookie('frontend', $_GET['session'], 0, '/your/magento/cookie/path');
header('Location: http://example.com');
?>

That should do it. Your user is now logged in (at least I got it to work in my test environment). One thing you should keep in mind is that Magento has a Session Validation Mechanism which will fail if enabled. That's because your session stores info about which browser you are using, the IP from which you are connecting, etc. These data will not match between calls through the API methods and the browser later. Here is an example output of the command print_r($session->getData()) after setting the session in the API method

[_session_validator_data] => Array
(
    [remote_addr] => 172.20.1.1
    [http_via] => 
    [http_x_forwarded_for] => 
    [http_user_agent] => PHP-SOAP/5.3.5
)

Make sure you turn of the validation in the Magento Admin in Settings > Configuration > General > Web > Session Validation Settings

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文