To call third-party web service in CakePHP 3.0. You can use Http client available in CakePHP core lib (CakeNetworkHttpClient).
Include CakeNetworkHttpClient in your controller.
use CakeNetworkHttpClient;
Here is the method to call third-party web service. You can use this method on any controller. Data should be in JSON format:
$http = new Client(); $response = $http->post( 'http://example.com/loginRequest', json_encode($data), ['type' => 'json'] );
You will get json data in $response object. To get json from $respons, we can call:
echo $response->json;
If no json returned from above code, you can use:
echo $response->body; // If json is coming as a part of body in response.
Now as per cakephp convention, it would be better to create a component and use it in each controller. As we want to use same code everywhere. And also in this way we can manage our service calls at one place.
1. Create component: Create a component in src/Component folder:
<?php namespace AppControllerComponent; use CakeControllerComponent; use CakeNetworkHttpClient; class ServiceComponent extends Component { public $SERVICE_BASE_URL = 'https://exmaple.com/'; public $components = ['Auth']; // in case you need to get value from auth component, like token or username. public function getCustomerToken($data=null) { $http = new Client(); $response = $http->post( $this->SERVICE_BASE_URL.'/loginRequest/', json_encode($data), ['type' => 'json']); return $response; } }
2. Now you have to initialize this component in the controller where you want to use this or we can initialize this component in App Controller.
In AppController, add this line in initialize method:
public function initialize() { parent::initialize(); ............ $this->loadComponent('Service'); ............. }
In custom controller, you can add this line:
public $components = array('Security', 'RequestHandler','Service');
3. To call service method from controller action, use this line:
$response = $this->Service->getCustomerToken($data);
You will get service response $response variable. Now do whatever you want to do with this response. 🙂
One comment