2015-07-16 7 views
2

Я пытаюсь подключиться к API WooCommerce с помощью Guzzle 5 (у Guzzle 6, похоже, нет опций oAuth o.O). Woocommerce requires the oAuth authentication method работать.Как использовать oAuth с Guzzle 5 (или, лучше, с Guzzle 6)

Это код, я использую:

<?php 

/** 
* Example of usage of Guzzle 5 to get information 
* from a WooCommerce Store. 
*/ 

require('../vendor/autoload.php'); 

use GuzzleHttp\Client; 
use GuzzleHttp\Subscriber\Oauth\Oauth1; 
use GuzzleHttp\Exception\RequestException; 

$consumer_key = 'my_consumer_key'; // Add your own Consumer Key here 
$consumer_secret = 'my_consumer_secret'; // Add your own Consumer Secret here 
$store_url = 'http://example.com'; // Add the home URL to the store you want to connect to here 
$api_path = '/wc-api/v2/'; 
$api_end_point = [ 
    'root' => '', 
    'orders' => 'orders' 
    ]; 

$base_uri = $store_url . $api_path; 

$client = new Client([ 
    'base_url' => $base_uri, 
    'defaults' => ['auth' => 'oauth'] 
    ]); 

$oauth = new Oauth1([ 
    'consumer_key' => $consumer_key, 
    'consumer_secret' => $consumer_secret, 
    'request_method' => 'query' 
]); 

$client->getEmitter()->attach($oauth); 

try 
{ 
    $res = $client->get($api_end_point['orders']); 
} 
catch (RequestException $e) 
{ 
    $res = $e; 

    if ($e->hasResponse()) 
    { 
     $res = $e->getResponse(); 
    } 
} 

print_r($res); 

echo $res->getStatusCode(); 
// "200" 
echo $res->getHeader('content-type'); 
// 'application/json; charset=utf8' 
echo $res->getBody(); 
// {"type":"User"...' 

Этот код возвращает

woocommerce_api_authentication_error: Invalid Signature - provided signature does not match

Использование чистых функций завиток (с использованием this package, в котором я положил некоторые функции, которые я нашел here) , вместо этого он работает, и я получаю все заказы и другие данные, которые я хочу.

некоторые другие детали

Чтобы использовать жрать 5 и OAuth Я использую те композиторские пакеты:

"require": { 
    "guzzlehttp/guzzle": "~5.0" 
}, 
"require-dev": { 
    "guzzlehttp/oauth-subscriber": "~0.2", 
}, 

Кажется, есть некоторые вещи, которые отличаются в создании подписи: одна создана по the library I've used until now работает, но созданный плагином oAuth (using the method getSignature()) для Guzzle этого не делает, и я не так привык использовать oAuth, чтобы найти ошибку. Есть ли кто-нибудь, кто может помочь мне определить проблему?

ответ

3

Обновление @Aerendir ответить

По его просьбе тянуть, @Aerendir писал:

In my case, I did the editing as I were trying to connect to the WooCommerce API version 2 but that version of the API didn't implement correctly the OAuth Core 1.0a spec. In fact, they fixed this issue in the version 3 of the API. See Differences between V3 and older versions.

source: https://github.com/guzzle/oauth-subscriber/pull/42#issuecomment-185631670

Таким образом, чтобы сделать его ответ работать должным образом, мы должны использовать туалет-апи/v3/ вместо wc-api/v2/.

Следующий код, работает с использованием жрать 6, OAuth и WooCommerce апи v3:

use GuzzleHttp\Client, 
    GuzzleHttp\HandlerStack, 
    GuzzleHttp\Handler\CurlHandler, 
    GuzzleHttp\Subscriber\Oauth\Oauth1; 

$url = 'http://localhost/WooCommerce/'; 
$api = 'wc-api/v3/'; 
$endpoint = 'orders'; 
$consumer_key = 'ck_999ffa6b1be3f38058ed83e5786ac133e8c0bc60'; 
$consumer_secret = 'cs_8f6c96c56a7281203c2ff35d71e5c4f9b70e9704'; 

$handler = new CurlHandler(); 
$stack = HandlerStack::create($handler); 

$middleware = new Oauth1([ 
    'consumer_key' => $consumer_key, 
    'consumer_secret' => $consumer_secret, 
    'token_secret' => '', 
    'token'   => '', 
    'request_method' => Oauth1::REQUEST_METHOD_QUERY, 
    'signature_method' => Oauth1::SIGNATURE_METHOD_HMAC 
]); 
$stack->push($middleware); 

$client = new Client([ 
    'base_uri' => $url . $api, 
    'handler' => $stack 
]); 

$response = $client->get($endpoint, [ 'auth' => 'oauth' ]); 
echo $response->getStatusCode() . '<br>'; 
echo $response->getHeaderLine('content-type') . '<br>'; 
echo $response->getBody(); 
1

Теперь плагин OauthSubscriber доступен только для жрать 6. тестирований вокруг снова, я нашел ошибку: он находится в методе signUsingHmacSha1(), что в любом случае добавляет umpersand (&) в строку, чтобы подписать, и это приводит к тому, ошибка от WooCommerce.

У меня есть opened a issue на GitHub и sent a pull request, чтобы исправить ошибку.

Правильный способ подключения к WooCommerce API V2 с использованием жрать 6 (! Как только ошибка будет исправлена ​​Позаботьтесь о версии WooCommerce API подключения: АНИ v3 до сих пор не работает) это:

use GuzzleHttp\Client; 
use GuzzleHttp\HandlerStack; 
use GuzzleHttp\Handler\CurlHandler; 
use GuzzleHttp\Subscriber\Oauth\Oauth1; 

$options = array(
    // Add the home URL to the store you want to connect to here (without the end /) 
    'remoteUrl'   => 'http://example.com/', 
    // Add your own Consumer Key here 
    'remoteConsumerKey' => 'ck_4rdyourConsumerKey8ik', 
    // Add your own Secret Key here 
    'remoteSecretKey' => 'cs_738youconsumersecret94i', 
    // Add the endpoint base path 
    'remoteApiPath' => 'wc-api/v2/', 
); 

$remoteApiUrl = $options['remoteUrl'] . $options['remoteApiPath']; 
$endpoint = 'orders'; 

$handler = new CurlHandler(); 
$stack = HandlerStack::create($handler); 

$middleware = new Oauth1([ 
    'consumer_key' => $options['remoteConsumerKey'], 
    'consumer_secret' => $options['remoteSecretKey'], 
    'token_secret' => '', 
    'token'   => '', 
    'request_method' => Oauth1::REQUEST_METHOD_QUERY, 
    'signature_method' => Oauth1::SIGNATURE_METHOD_HMAC 
]); 
$stack->push($middleware); 

$client = new Client([ 
    'base_uri' => $remoteApiUrl, 
    'handler' => $stack 
]); 

$res = $client->get($endpoint, ['auth' => 'oauth'); 

Как сказано, эта связь работает только с версией 2 API WooCommerce.

Я расследую, чтобы понять, почему V3 не работает.