PHP Soap wsdl response Issue - php

I am working on php soap to implement an insurance policy issuing application.Everything i set and i get a response number from web service.But i dont know how to fetch the response data from web service (xml).Below i am providing my web service request and response.
Link to web service
https://es.adpolice.gov.ae/TrafficInsurance/TrafficInsuranceServicesNew.asmx?op=CreateVehicleInsurancePolicy
this is the code i am trying..please guide me.
class SOAPStruct
{
function __construct($user, $pass)
{
$this->userName = $user;
$this->Password = $pass;
}
}
$service = new SoapClient("https://es.adpolice.gov.ae/TrafficInsurance/TrafficInsuranceServicesNew.asmx?wsdl", array('trace' => 1));
$auth = new SOAPStruct('*****','****');
$header = new SoapHeader("http://adpolice.gov.ae/TrafficInsurance/TrafficInsuranceServices.asmx",'SoapHeaderIn',$auth,false);
$service->__setSoapHeaders(array($header));
$param = array('lngInsuranceCompanyCode'=> '1','intInsuranceKindCode'=>'1','lngTcf'=>'1','strPolicyNo'=>'1','dtExpiryDate'=>'2016-04-30','dtStartDate'=>'2015-03-31','strChassisNo'=>'6T1BE4DFDFDFDFD','strRemarks'=>'dfdf','strUserCreated'=>'dfdfd');
$response = $service->CreateVehicleInsurancePolicy($param);
print_r($response);

All you have to do is
$xml = $service->__getLastResponse();
print_r($xml);

Related

Are all existing endpoints listed in documentation really still working for v4.9? (i.e. those not replaced by v1 so far)

I have tried using old v4.9 endpoints that haven't been replaced by v1 so far such as:
https://developers.google.com/my-business/reference/rest/v4/accounts.locations/reportInsights
https://developers.google.com/my-business/reference/rest/v4/accounts.locations.reviews
However, none of these endpoints work anymore.
I am using PHP client that had these endpoints missing, but using the official v4.9 library listed here: https://developers.google.com/my-business/samples/previousVersions I have been able to reach some of the old endpoints such as reviews.
However they no longer return any data or data object is empty.
Anyone has experienced similar issues?
The v4.9 (not yet deprecated) endpoints such as reviews, insights etc. are working, but the official library is broken and botched.
I had to code a replacement using Guzzle client reaching to the endpoints directly instead. So you need to code the API library yourself from scratch for these v4.9 endpoints as the official library does not work.
How to fetch reviews:
public static function listReviews($client, $params, $account, $location)
{
$response = $client->authorize()->get('https://mybusiness.googleapis.com/v4/' . $account . '/' . $location . '/reviews', ['query' => $params]);
return json_decode((string) $response->getBody(), false);
}
How to fetch insights:
/** v4.9 working 02/2022 **/
public static function reportInsights($client, $params, $account)
{
try {
$response = $client->authorize()->post('https://mybusiness.googleapis.com/v4/' . $account . '/locations:reportInsights', [
\GuzzleHttp\RequestOptions::JSON => $params,
]);
} catch (\GuzzleHttp\Exception\RequestException $ex) {
return $ex->getResponse()->getBody()->getContents();
}
return json_decode((string) $response->getBody(), false);
}
How to prepare payload for insights:
$params = new \stdClass();
$params->locationNames = $account->name . '/' . $location->name;
$time_range = new \stdClass();
$time_range->startTime = Carbon::parse('3 days ago 00:00:00')->toISOString();
$time_range->endTime = Carbon::parse('2 days ago 00:00:00')->toISOString();
if ($force == 'complete') {
$time_range->startTime = Carbon::parse('17 months ago 00:00:00')->toIso8601ZuluString();
$time_range->endTime = Carbon::parse('3 days ago 00:00:00')->toIso8601ZuluString();
}
$params->basicRequest = new \stdClass();
$params->basicRequest->timeRange = $time_range;
$params->basicRequest->metricRequests = new \stdClass();
$metric_request = new \stdClass();
$metric_request->metric = 'ALL';
$metric_request->options = ['AGGREGATED_DAILY'];
$params->basicRequest->metricRequests = [
$metric_request,
];
Note: if you are getting empty insights response, you have to check verification using new v1 API call such as:
$verifications = \Google_Service_MyBusinessVerifications($client)->locations_verifications->listLocationsVerifications($location->getName());
$verification = '0';
if ($verifications->getVerifications()) {
$verification = $verifications->getVerifications()[0]->getState();
}
Using official API client with an existing token (needs to be fetched via OAuth2):
$provider = new GoogleClientServiceProvider(true);
$client = $provider->initializeClient($known_token, ['https://www.googleapis.com/auth/plus.business.manage', 'https://www.googleapis.com/auth/drive']);

How to pass through credentials to PHP SOAP Request

I need to create a PHP SOAP client based on this specification:
https://exdev.server.propctrl.com/v5.4/Basic/AgencyIntegration.svc?wsdl
I am able to create my soap client, and when I try to call a function it returns saying access denied:
Message: Access is denied.
Based on documentation, there is no verification/auth method that I first need to call, but it seems I have to use a type called Credentials.
struct Credentials { string Password; string Username; }
I then tried created a Credentials object:
class Credentials {
public function __construct($username, $password)
{
$this->username = $username;
$this->password = $password;
}
}
And assigned new values to it and used it in my SoapHeaders:
$credentials = new Credentials($username, $password);
$header = new SoapHeader('http://localhost','Credentials',$credentials,false);
$client->__setSoapHeaders($header);
When I then use a function I still get the same error:
echo "<pre>";
try {
$response = $client->__soapCall("EchoAuthenticated", array("EchoAuthenticated" => "asdfasdf"));
var_dump($response);
}
//catch exception
catch(Exception $e) {
echo 'Message: ' .$e->getMessage();
}
Message: Access is denied.
I guess my question is that I don't know where/how to pass through the credentials in order for the API to authorise my request.
Any ideas/suggestions?
update1:
The authentication method should be explained in some documentation, anyway there are Soap services that use HTTP Header for authentication, for example
$soapClient->setHttpHeaders([
'clientId' => $username,
'clientSecret' => $password
]);
But please consider that keys ( in my example clientId and clientSecret ) depend by the service implementation.
Do you have a service documentation?

LastRequest is empty, POST is empty. How to get the XML request from Zend Soap Server?

I've implemented a zend soap server with the code below. For my purposes i need to be able to access the full XML message or at the very least its headers. However, the getLastRequest method on SoapServer returns empty, and all the super globals, such as $_GET, $_POST and whatnot, are also empty. Anyone has any ideas?
class SoapTest
{
protected $server;
public function __construct(\Zend\Soap\Server $server)
{
$this->server = $server;
}
/***
* #param string $requestIn
* #return string
*/
public function test($requestIn)
{
// access XML here
}
}
$serverUrl = "http://localhost/SoapTest.php";
$options = [
'uri' => $serverUrl,
];
$server = new Zend\Soap\Server(null, $options);
if (isset($_GET['wsdl'])) {
$soapAutoDiscover = new \Zend\Soap\AutoDiscover(new \Zend\Soap\Wsdl\ComplexTypeStrategy\ArrayOfTypeSequence());
$soapAutoDiscover->setBindingStyle(array('style' => 'document'));
$soapAutoDiscover->setOperationBodyStyle(array('use' => 'literal'));
$soapAutoDiscover->setClass(SoapTest::class);
$soapAutoDiscover->setUri($serverUrl);
header("Content-Type: text/xml");
echo $soapAutoDiscover->generate()->toXml();
} else {
$soap = new \Zend\Soap\Server($serverUrl . '?wsdl', array('cache_wsdl' => WSDL_CACHE_NONE));
$soap->setObject(new \Zend\Soap\Server\DocumentLiteralWrapper(new SoapTest($soap)));
$soap->handle();
}
Apparently, Zend Soap Server fills the $request property (which is returned in getLastRequest) AFTER the handle, so i cant access it in my method.
I can however access the XML by calling the following:
$request = file_get_contents('php://input');

Google always returns false verifying id token

I have the next code, got directly from google reference (https://developers.google.com/identity/sign-in/web/backend-auth)
public function verifyFromAndroid($idToken=null) {
if(empty($idToken)) {
$idToken = self::SAMPLE_ID_TOKEN;
}
$client = new Google_Client(['client_id' => self::CLIENT_ID]);
$payload = $client->verifyIdToken($idToken);
if ($payload) {
print_r($payload);
$userid = $payload['sub'];
// If request specified a G Suite domain:
//$domain = $payload['hd'];
} else {
var_dump($payload);
$this->lastError = "Invalid ID token";
return false;
}
}
But this method always returns false, even using a valid id token that is created and working using the oauthplayground online tool.
The next code works fine, using directly the GoogleAccessToken_Verify class. Can someone tell me why the official Google code doesn't work and yes my own code using the official Google-clien-php sdk?
try {
$verify = new Google_AccessToken_Verify();
$result = $verify->verifyIdToken($this->idToken);
if($result) {
print_r($result);
$friendlyData = $this->translateData($result, true);
if(!$friendlyData) {
return false;
}
return $friendlyData;
}
else {
$this->lastError = "Invalid token verification, no error code";
return false;
}
}
catch(UnexpectedValueException $ex) {
$this->lastError = "UnVaEx (Code {$ex->getCode()}): {$ex->getMessage()}";
return false;
}
try adding complete client ID
xxxxxxxxxxxxxx-xxxxx-yy-zz.apps.googleusercontent.com
while initiating the
$client = new Google_Client(['client_id' => self::CLIENT_ID]);
It should work i was also facing the same issue ...
Had a similar issue.Deleted my android app on firebase console and created a fresh app wirh debug key sha1.Then downloaded and replaced my google.json into my app.This fixed my issue.This has happened to me twice now. At times you just need to recreate the android app on firebase console.
Before you begin register your backend URL at https://developers.google.com/identity/sign-in/web/sign-in with Configure your project button and don't use any credidentials or api key in your code. After doing them your code should look like to this.
public function verifyFromAndroid($idToken=null) {
if(empty($idToken)) {
$idToken = self::SAMPLE_ID_TOKEN;
}
//As you notice we don't use any key as a parameters in Google_Client() API function
$client = new Google_Client();
$payload = $client->verifyIdToken($idToken);
if ($payload) {
print_r($payload);
$userid = $payload['sub'];
// If request specified a G Suite domain:
//$domain = $payload['hd'];
} else {
var_dump($payload);
$this->lastError = "Invalid ID token";
return false;
}
}
I hope it helps.
I faced the same issue. After checking different PHP versions, I found that the google client library is working in PHP7.4 but not with PHP8.0.
Please try the below code after downgrading the version of PHP to 7.4
require_once 'vendor/autoload.php';
$id_token = $_POST['credential'];
$client = new Google_Client(['client_id' => $CLIENT_ID]); // Specify the CLIENT_ID of the app that accesses the backend
$payload = $client->verifyIdToken($id_token);
if ($payload) {
$userid = $payload['sub'];
// If request specified a G Suite domain:
//$domain = $payload['hd'];
} else {
// Invalid ID token
}
Or For development and debugging, you can call google oauth2 tokeninfo validation endpoint.
https://oauth2.googleapis.com/tokeninfo?id_token=$id_token

Response from soap header

Even though i am very new to php soap concept, i write a program to communicate a web server using SoapClient.
This is my wsdl link:
https://es.adpolice.gov.ae/TrafficInsurance/TrafficInsuranceServicesNew.asmx?wsdl
Service name : CreateVehicleInsurancePolicy
Link : https://es.adpolice.gov.ae/TrafficInsurance/TrafficInsuranceServicesNew.asmx?op=CreateVehicleInsurancePolicy
I hosted my program in in an ssl certified hosting.When it run it generating a response in soap body response(lngSerial).I wanted to print the response value from soap header (SoapHeaderOut).
that is intResponseCode,strArMsg,strEnMsg.
Please guide me.Below i am providing the script which i am using.
<?php
ini_set("soap.wsdl_cache_enabled", "0");
ini_set("soap.wsdl_cache_ttl", "0");
class SOAPStruct
{
function __construct($user, $pass)
{
$this->userName = $user;
$this->Password = $pass;
}
}
$service = new SoapClient("https://es.adpolice.gov.ae/TrafficInsurance/TrafficInsuranceServicesNew.asmx?wsdl");
$auth = new SOAPStruct('username','password');
$header = new SoapHeader("http://adpolice.gov.ae/TrafficInsurance/TrafficInsuranceServices.asmx","SoapHeaderIn",$auth,true);
$service->__setSoapHeaders($header);
$param = array('lngInsuranceCompanyCode'=> '1','intInsuranceKindCode'=>'1','lngTcf'=>'3070858641','strPolicyNo'=>'1055385883','dtExpiryDate'=>'2016-04-30T00:00:00','dtStartDate'=>'2015-03-31T00:00:00','strChassisNo'=>'6T1BE42RG465465','strRemarks'=>'demo','strUserCreated'=>'demo');
$response = $service->CreateVehicleInsurancePolicy($param)->CreateVehicleInsurancePolicyResult;
foreach ($response as $record) {
print_r($record);
print_r("<br>");
}
?>
As per PHP documentation you should be able to get to the SoapHeader response object by using the low level API instead of the magic method provided by WSDL. In your case it would be
$response = $service->__soapCall("CreateVehicleInsurancePolicy", $param, null, $headers, $response_headers);
Which should store the object that you want into $response_headers variable.
Old response: (pertains to actual HTTP headers of the response)
If you instantiate the SoapClient with trace set like so:
$service = new SoapClient("https://es.adpolice.gov.ae/TrafficInsurance/TrafficInsuranceServicesNew.asmx?wsdl", array("trace" => 1))
you should be able to get the Header response using the SoapClient::__getLastResponseHeaders
$response_headers = $service->__getLastResponseHeaders();

Categories