问题
I am trying to create a product in drupal commerce using guzzle and restful webservices.
When i am trying to create a new product i use the following process: 1) Login as a user who has the rights to create a product (succes) 2) Request CSRF token (succes) 3) Create product : Uh oh!: Client error response [status code] 401 [reason phrase] Unauthorized: Access to this operation not granted
Now when i am doing this process trough poster (Firfox add-on). I can succesfully create a product, but it guzzle i always fail to acces this operation.
require 'guzzle.phar';
use Guzzle\Http\Client;
//EDIT:
use Guzzle\Plugin\Cookie\CookiePlugin;
use Guzzle\Plugin\Cookie\CookieJar\ArrayCookieJar;
$client = new Client('http://localhost:8888/drupal-test/');
//EDIT:
$cookiePlugin = new CookiePlugin(new FileCookieJar($cookie_file_name));
$client->addSubscriber($cookiePlugin);
//User login
$request = $client->post('my_services/user/login.json', null,
array(
'username' => 'its',
'password' => '****'
));
$response_json = $response->getBody();
$session = $response_var->session_name . '=' . $response_var->sessid;
//Services CSRF token
$request = $client->get('services/session/token');
$response = $request->send();
$token = $response->getBody(TRUE);
//Create Product
$request = $client->post('my_services/product.json',
array(
'X-CSRF-Token' => $token,
),
array(
'sku' => 'guzzleproductadd10',
'title' => 'guzzleproductadd10',
'type' => 'product',
'commerce_price_amount' => '200',
'commerce_price_currency_code' => 'EUR'
)
);
//$request->addHeader('X-CSRF-Token', $token);
try {
$response = $request->send();
}
catch (Guzzle\Http\Exception\BadResponseException $e) {
echo 'Uh oh!: ' . $e->getMessage();
}
I don't really see what i am doing wrong. I logged in, added the required variables to the header.
Ty!
Edit: solution see comments. I adjusted the code.
来源:https://stackoverflow.com/questions/22756009/guzzle-add-csrf-token