OAuth-based Web API calls

Once we have obtained OAuth access token, from the preceding steps, we can start making Web API calls to other methods. Even though the Web API coverage is the same for both REST and SOAP, there is a significant difference when making method calls.

For the purpose of giving a more robust example, we will be targeting the customer group save method, (partially) defined in the vendor/magento/module-customer/etc/webapi.xml file as follows:

<route url="/V1/customerGroups" method="POST">
    <service class="MagentoCustomerApiGroupRepositoryInterface" method="save"/>
    <resources>
        <resource ref="Magento_Customer::group"/>
    </resources>
</route>

To use the access token to make Web API calls, like POST /V1/customerGroups, we need to include these request parameters in the authorization request header in the call:

  • oauth_consumer_key, available from the Magento admin area, under the integration edit screen.
  • oauth_nonce, random value, uniquely generated by the application for each request.
  • oauth_signature_method, name of the signature method used to sign the request. Valid values are: HMAC-SHA1, RSA-SHA1, and PLAINTEXT.
  • Even though the Outh protocol supports PLAINTEXT, Magento does not. We will be using HMAC-SHA1.
  • oauth_timestamp, integer value, Unix-like timestamp.
  • oauth_token, available from the Magento admin area, under the integration edit screen.
  • oauth_version, Magento supports Oauth 1.0a, thus we use 1.0.
  • oauth_signature, generated signature value, omitted from the signature generation process.

To generate an OAuth 1.0a HMAC-SHA1 signature for a HTTP request takes focused effort, if done manually.

We need to determine the HTTP method and URL of the request, which equals to POST http://magento2-merchant.loc/rest/V1/customerGroups. It is important to use the correct protocol here, so make sure that the https:// or http:// portion of the URL matches the actual request sent to the API.

We then gather all of the parameters included in the request. There are two such locations for these additional parameters: the URL (as part of the query string) and the request body.

In the HTTP request, the parameters are URL encoded, but we need to collect the raw values. In addition to the request parameters, every oauth_* parameter needs to be included in the signature, except the oauth_signature itself.

The parameters are normalized into a single string as follows:

  • Parameters are sorted by name, using lexicographical byte value ordering. If two or more parameters share the same name, they are sorted by their value.
  • Parameters are concatenated in their sorted order into a single string. For each parameter, the name is separated from the corresponding value by an = character (ASCII code 61), even if the value is empty. Each name-value pair is separated by an & character (ASCII code 38).

Further, we define the signing key as a value of {Consumer Key}+{&}+{Access Token Secret}.

Once we apply the string normalization rules to parameters and determine the signing key, we call hash_hmac('sha1', $data, {Signing Key}, true) to get the final oauth_signature value.

This should get us the oauth_signature as a random 28-characters-long string, similar to this one – Pi/mGfA0SOlIxO9W30sEch6bjGE=.

Understanding how to generate the signature string is important, but getting it right every time is tedious and time consuming. We can help ourselves by instantiating the objects of the built-in OAuthCommonConsumerCredentials and OAuthOAuth1SignatureSignature classes, like (partially) shown as follows:

$credentials = new OAuthCommonConsumerCredentials($consumerKey, $consumerSecret, $magentoBaseUrl);
$signature = new OAuthOAuth1SignatureSignature($credentials);
$signature->setTokenSecret($accessTokenSecret);
$signature->setHashingAlgorithm('HMAC-SHA1');

echo $signature->getSignature($uri, array(
    'oauth_consumer_key' => $consumerKey,
    'oauth_nonce' => 'per-request-unique-token',
    'oauth_signature_method' => 'HMAC-SHA1',
    'oauth_timestamp' => '1437319569',
    'oauth_token' => $accessToken,
    'oauth_version' => '1.0',
), 'POST');

Now that we have the oauth_signature value, we are ready to do our console curl REST example. It comes down to running the following on a console:

curl -X POST http://magento2.ce/rest/V1/customerGroups
-H 'Content-Type: application/json'
-H 'Authorization: OAuth
oauth_consumer_key="vw2xi6kaq0o3f7ay60owdpg2f8nt66g6",
oauth_nonce="per-request-token-by-app-1",
oauth_signature_method="HMAC-SHA1",
oauth_timestamp="1437319569",
oauth_token="cney3fmk9p5282bm1khb83q846l7dner",
oauth_version="1.0",
oauth_signature="Pi/mGfA0SOlIxO9W30sEch6bjGE="'
-d '{"group": {"code": "The Book Writer", "tax_class_id": "3"}}'

Note that the preceding command is merely visually broken into new lines. It should all be single line on a console. Once executed, the API call will create a new customer group called The Book Writer. A logical question one might ask looking at the curl command is how come we did not normalize the POST data passed as JSON via the –d flag switch. This is because parameters in the HTTP POST request body are only taken into consideration for signature generation if content-type is application/x-www-form-urlencoded.

The console cURL SOAP requests do not require usage of the OAuth signature. We can execute a SOAP request passing Authorization: Bearer { Access Token value } into the request header, like shown in the following example:

curl -X POST http://magento2.ce/index.php/soap/default?services= customerGroupRepositoryV1 -H 'Content-Type: application/soap+xml; charset=utf-8; action="customerGroupRepositoryV1Save"' -H 'Authorization: Bearer cney3fmk9p5282bm1khb83q846l7dner' -d @request.xml

Where request.xml contains content as follows:

<?xml version="1.0" encoding="UTF-8"?>
<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope" xmlns:ns1="http://magento2.ce/index.php/soap/default? services=customerGroupRepositoryV1">
    <env:Body>
        <ns1:customerGroupRepositoryV1SaveRequest>
            <group>
                <code>The Book Writer</code>
                <taxClassId>3</taxClassId>
            </group>
        </ns1:customerGroupRepositoryV1SaveRequest>
    </env:Body>
</env:Envelope>

The following code example demonstrates the PHP cURL SOAP-like request for the customer group save method call:

$request = new SoapClient(
    'http://magento2.ce/index.php/soap/?wsdl&services= customerGroupRepositoryV1',
    array(
        'soap_version' => SOAP_1_2,
        'stream_context' => stream_context_create(array(
            'http' => array(
                'header' => 'Authorization: Bearer cney3fmk9p5282bm1khb83q846l7dner')
            )
        )
    )
);

$response = $request->customerGroupRepositoryV1Save(array(
    'group' => array(
        'code' => 'The Book Writer',
        'taxClassId' => 3
    )
));

Notice how the method name customerGroupRepositoryV1Save actually comprises service name customerGroupRepositoryV1, plus the Save name of the actual method within the service.

We can get a list of all services defined by opening a URL like http://magento2.ce/soap/default?wsdl_list in the browser (depending on our Magento installation).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.214.230