I tried to call SOAP API of Magento 2 but I could not call successfully.
Here is my source code:
require('vendor/zendframework/zend-server/Zend/Server/Client.php');
require('vendor/zendframework/zend-soap/Zend/Soap/Client.php');
require('vendor/zendframework/zend-soap/Zend/Soap/Client/Common.php');
$token = "olourdje47c5c5g66md4gfceyslo9y1p";
$opts = ['http' => ['header' => "Authorization: Bearer " . $token]];
$context = stream_context_create($opts);
$wsdlUrl = "http://mage2.dev/soap?wsdl&services=customerCustomerRepositoryV1";
$serviceArgs = array("customerId" => 1);
$soapClient = new \Zend\Soap\Client($wsdlUrl);
$soapClient->setSoapVersion(SOAP_1_2);
$soapClient->setStreamContext($context);
$soapResponse = $soapClient->customerCustomerRepositoryV1GetById($serviceArgs);
var_dump($soapResponse);
The error message shown on browser is:
Fatal error: Uncaught SoapFault exception: [env:Sender] Consumer is
not authorized to access %resources in
/vagrant/data/magento2/vendor/zendframework/zend-soap/Zend/Soap/Client.php:1118
Stack trace: #0
/vagrant/data/magento2/vendor/zendframework/zend-soap/Zend/Soap/Client.php(1118):
SoapClient->__soapCall('customerCustome…', Array, NULL, NULL, Array)1 /vagrant/data/magento2/test_api.php(28): Zend\Soap\Client->__call('customerCustome…', Array) #2
/vagrant/data/magento2/test_api.php(28):
Zend\Soap\Client->customerCustomerRepositoryV1GetById(Array) #3 {main}
thrown in
/vagrant/data/magento2/vendor/zendframework/zend-soap/Zend/Soap/Client.php
on line 1118
The token in the source code was the access token of the integration with all resource I created on Magento back-end. The integration was active.
I could call the SOAP API without resource need successfully. For example, the Get function in the catalogProductRepositoryV1 service.
I wonder if there are any missing procedures I have to complete first for using SOAP API with resource need.
I will thank you so much for any helps.
Best Answer
I found the root cause. I did not miss any procedures for the API configuration.
The problem is I am using the VM provided by Magento for running the Magento2. The function apache_request_headers does not work in the VM environment so that the php cannot get "Authorization" in the header of the HTTP request.
I spent a whole afternoon for debugging.