Swiss post tracking web service implementation using php soap - api

I'm working on a E-commerce site on which orders are placed. i want to track that delivery status of order and I need to give a status of order to user over mail.
I have to use Swiss Post Tracking Web Service API. Can anyone show me how to do so? I am new to SOAP WSDL.
From my understanding i did this now how to go further? My code below its just basic client i need to:
I need to track the delivery status
Below is my code
$wsdl = "https://webservices.post.ch:17005/IN_MYPBxTT/services/TrackAndTraceDFU.ws?WSDL
$username = 'username';
$password = 'password';
$trace = True;
$soapConfig = array(
'login'=>$username,
'password'=>$password,
'trace'=>$trace,
'keep_alive'=>TRUE,
'encoding'=>'utf8',
'connection_timeout'=>90,
);
$soapClient = new SoapClient($wsdl, $soapConfig);
try {
$xml = '<soapenv:Envelope xmlns:soapenv=“http://schemas.xmlsoap.org/soap/envelope/“
xmlns:req=“http://www.post.ch/npp/trackandtracews/v02/shipmentssearch/req“>
<soapenv:Header/>
<soapenv:Body>
<req:ShipmentsSearch>
<language>de</language>
<ShipmentNumbers>
<ShipmentNumber>99.60.122566.27198756</ShipmentNumber>
</ShipmentNumbers>
<Identity>?</Identity>
<Version>2.4</Version>
</req:ShipmentsSearch>
</soapenv:Body>
</soapenv:Envelope>';
$args = array(new SoapVar($xml, XSD_ANYXML));
$res = $this->_soapClient->__soapCall('ShipmentsSearch', $args);
return $res;
} catch (SoapFault $e) {
echo "Error: {$e}";
}
echo "<hr>Last Response";
echo "<pre>", htmlspecialchars($this->_soapClient->__getLastResponse()), "</pre>";
die;
I am using this code but getting below error
Error: SoapFault exception: [env:Client] Internal Error in /directory-name/ConsignmentWebService.php:114
Stack trace: #0 /directory-name/ConsignmentWebService.php(114): SoapClient->__soapCall('ShipmentsSearch', Array)
and get the response like this
Last Request
<?xml version='1.0' ?>
<env:Envelope xmlns:env='http://schemas.xmlsoap.org/soap/envelope/'>
<env:Body>
<env:Fault>
<faultcode>env:Client</faultcode>
<faultstring>Internal Error</faultstring>
</env:Fault>
</env:Body>
</env:Envelope>
I referred this tutorial
https://www.post.ch/en/business-solutions/digital-commerce/notification-services/sendungsinformationen
please help me I am new in soap
Updated Code who are looking for solution
$wsdl = "https://webservices.post.ch:17005/IN_MYPBxTT/services/TrackAndTraceDFU.ws?WSDL
$username = 'username';
$password = 'password';
$trace = True;
$soapConfig = array(
'login'=>$username,
'password'=>$password,
'trace'=>$trace,
'keep_alive'=>TRUE,
'encoding'=>'utf8',
'connection_timeout'=>90,
);
$soapClient = new SoapClient($wsdl, $soapConfig);
$response = null;
$generateRequest = array(
'language'=>'de',
'ShipmentNumbers'=>array(
'ShipmentNumber'=>$tracking_code, //your track code
),
'Identity'=>'?',
'Version'=>2.4
);
try {
$response = $this->_soapClient->ShipmentsSearch($generateRequest);
return $response;
} catch (SoapFault $fault) {
echo('Error in Getting Delivery Status: '. $fault->__toString() .'<br />');
echo '<pre>';
var_dump($this->_soapClient->__getLastResponse());
echo '</pre>';
die();
}

Related

Unable to get past the 400 Error

Code to create a new user:
function New-DropBoxUser {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true, ValueFromPipeline=$true, Position=0)]
[string]$FullName
)
# Split name into username #
$FirstName, $LastName = $FullName.split(' ')
$UserName = ($FirstName[0]+$LastName).toLower()
$email = "$UserName#mycomp.com"
$Body = #{
"new_members" = #(#{
"member_email" = $email;
"member_given_name" = $FirstName;
"member_surname" = $LastName;
"send_welcome_email" = "true";
"role" = #{
".tag" = "member_only"
}
})
}
Write-Host ''
Write-Host 'Creating DropBox User...' -ForegroundColor 'Yellow' -BackgroundColor 'Black'
$AuthToken = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
$token = "Bearer $AuthToken"
$response = Invoke-RestMethod `
-Method Post `
-Uri "https://api.dropboxapi.com/2/team/members/add" `
-Headers #{ Authorization = $token } `
-ContentType "application/json; charset=utf-8" `
-Body (ConvertTo-Json $Body)
}
Output:
Invoke-RestMethod : The remote server returned an error: (400) Bad Request.
Anyone, please tell me the fix. I tried the Endpoint "team/members/list" to fetch user list using the same $token and it works.
I am totally new to Dropbox API so my code is borrowed from Google, while being good with PowerShell I tried to patch up using many different codes but none worked.
When all else fails, RTFM, whose parameters say:
{
"new_members": [
{
"member_email": "tom.s#company.com",
"member_given_name": "Tom",
"member_surname": "Silverstone",
"member_external_id": "company_id:342432",
"send_welcome_email": true,
"role": "member_only"
}
],
"force_async": false
}
Try removing .tag from the role definition and replace "true" with $true
$Body = #{
"new_members" = #(#{
"member_email" = $email
"member_given_name" = $FirstName
"member_surname" = $LastName
"send_welcome_email" = $true
"role" = "member_only"
})
}

Creating Java Client to access WSHTTPBINDING API Service

I need to consume a web service from UltiPro in Java. All the examples from UltiPro are for C# (see below) and I cannot see how to translate the into Java.
My research indicates that the key is WSHttpBinding.
UltiPro's documentation includes an XML file that they say...
The following code is an XML example of authenticating to your UltiPro data. You can copy the entire contents and update the values in the request. The response example shows how a successful response will be formatted.
I have written many Web Services and RESTful programs before, but I am stuck on this one.
<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://www.w3.org/2005/08/addressing">
<s:Header>
<a:Action s:mustUnderstand="1">http://www.ultipro.com/services/loginservice/ILoginService/Authenticate</a:Action>
<h:ClientAccessKey xmlns:h="http://www.ultipro.com/services/loginservice">CAK</h:ClientAccessKey>
<h:Password xmlns:h="http://www.ultipro.com/services/loginservice">PASSWORD</h:Password>
<h:UserAccessKey xmlns:h="http://www.ultipro.com/services/loginservice">USER API KEY</h:UserAccessKey>
<h:UserName xmlns:h="http://www.ultipro.com/services/loginservice">USERNAME</h:UserName>
</s:Header>
<s:Body>
<TokenRequest xmlns="http://www.ultipro.com/contracts" />
</s:Body>
</s:Envelope>
C# code:
namespace ConsoleSample
{
using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
using ConsoleSample.LoginService;
public class Program
{
internal static void Main(string[] args)
{
// Setup your user credentials:
const string UserName = "";
const string Password = "";
const string UserApiKey = "";
const string CustomerApiKey = "";
// Create a proxy to the login service:
var loginClient = new LoginServiceClient("WSHttpBinding_ILoginService");
try
{
// Submit the login request to authenticate the user:
string message;
string authenticationToken;
AuthenticationStatus loginRequest =
loginClient
.Authenticate(
CustomerApiKey,
Password,
UserApiKey,
UserName,
out message,
out authenticationToken);
if (loginRequest == AuthenticationStatus.Ok)
{
// User is authenticated and the authentication token is provided.
Console.WriteLine("User authentication successful.");
}
else
{
// User authentication has failed. Review the message for details.
Console.WriteLine("User authentication failed: " + message);
}
loginClient.Close();
Console.WriteLine("Press a key to exit...");
Console.ReadKey(true);
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex);
loginClient.Abort();
throw;
}
}
I understand you are looking to write it in JAVA but maybe something from my code will help.
I was able to successfully authenticate using the following code:
<?php
$url = 'https://rental5.ultipro.com/services/LoginService';
$action = 'http://www.ultipro.com/services/loginservice/ILoginService/Authenticate';
$username = 'MY_USERNAME';
$password = 'MY_PASSWORD';
$userAccessKey = 'MY_USER_ACCESS_KEY';
$clientAccessKey = 'MY_CLIENT_ACCESS_KEY';
$loginPayload =<<<EOD
<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://www.w3.org/2005/08/addressing">
<s:Header>
<a:Action s:mustUnderstand="1">{$action}</a:Action>
<h:ClientAccessKey xmlns:h="http://www.ultipro.com/services/loginservice">{$clientAccessKey}</h:ClientAccessKey>
<h:Password xmlns:h="http://www.ultipro.com/services/loginservice">{$password}</h:Password>
<h:UserAccessKey xmlns:h="http://www.ultipro.com/services/loginservice">{$userAccessKey}</h:UserAccessKey>
<h:UserName xmlns:h="http://www.ultipro.com/services/loginservice">{$username}</h:UserName>
</s:Header>
<s:Body>
<TokenRequest xmlns="http://www.ultipro.com/contracts" />
</s:Body>
</s:Envelope>
EOD;
$client = new SoapClient(
null,
array(
'location' => $url,
'uri' => '',
'trace' => 1,
'encoding' => 'UTF-8',
'use' => SOAP_LITERAL,
'soap_version' => SOAP_1_2
)
);
try {
$order_return = $client->__doRequest($loginPayload, $url, $action, SOAP_1_2, 0);
$getLastRequestHeaders = $client->__getLastRequestHeaders();
$getLastRequest = $client->__getLastRequest();
$getLastResponseHeaders = $client->__getLastResponseHeaders();
$getLastResponse = $client->__getLastResponse();
echo "<pre>";
echo $getLastRequestHeaders;
echo '<br>';
echo $getLastResponseHeaders;
echo '<br>';
print_r($order_return);
echo "</pre>";
} catch (SoapFault $exception) {
var_dump(get_class($exception));
var_dump($exception);
}
?>

Google oAuth not working after 3600 seconds

I'm using google oAuth for getting youtube latest streaming. It works for 3600 seconds. But then it stopped working. After some researching at stackoverflow, many people wrote to use "SetAccessType": "offline" .
I did it but same result.
Here is my snippet.
<?php
/**
* Library Requirements
*
* 1. Install composer (https://getcomposer.org)
* 2. On the command line, change to this directory (api-samples/php)
* 3. Require the google/apiclient library
* $ composer require google/apiclient:~2.0
*/
$stream_id = "";
if (!file_exists(__DIR__ . '/vendor/autoload.php')) {
throw new \Exception('please run "composer require google/apiclient:~2.0" in "' . __DIR__ .'"');
}
require_once __DIR__ . '/vendor/autoload.php';
session_start();
$OAUTH2_CLIENT_ID = '972289696318-q037nr25oti8gs5h7hcj5lfkl7erklh6.apps.googleusercontent.com';
$OAUTH2_CLIENT_SECRET = 'cbmQyfeXWGb93RkN7KSHLQKB';
$client = new Google_Client();
$client->setAccessType('online');
$client->setClientId($OAUTH2_CLIENT_ID);
//$client->setExpires_in('10000000');
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$client->setScopes('https://www.googleapis.com/auth/youtube');
$redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'],
FILTER_SANITIZE_URL);
$client->setRedirectUri($redirect);
// Define an object that will be used to make all API requests.
$youtube = new Google_Service_YouTube($client);
//print_r($youtube);
// Check if an auth token exists for the required scopes
$tokenSessionKey = 'token-' . $client->prepareScopes();
if (isset($_GET['code'])) {
if (strval($_SESSION['state']) !== strval($_GET['state'])) {
die('The session state did not match.');
}
$client->authenticate($_GET['code']);
$_SESSION[$tokenSessionKey] = $client->getAccessToken();
header('Location: ' . $redirect);
}
if (isset($_SESSION[$tokenSessionKey])) {
$client->setAccessToken($_SESSION[$tokenSessionKey]);
}
/*
if ($client->isAccessTokenExpired()) {
$refreshToken = $client->getRefreshToken();
//print_r($refreshToken);
// $client->refreshToken($refreshToken);
$newAccessToken = $client->getAccessToken();
$newAccessToken['refresh_token'] = $refreshToken;
file_put_contents($credentialsPath, json_encode($newAccessToken));
}
*/
// Check to ensure that the access token was successfully acquired.
if ($client->getAccessToken()) {
try {
// Execute an API request that lists broadcasts owned by the user who
// authorized the request.
//print_r($youtube);
$broadcastsResponse = $youtube->liveBroadcasts->listLiveBroadcasts(
'id,snippet',
array(
'mine' => 'true',
));
//print_r($broadcastsResponse);
$htmlBody .= "<h3>Live Broadcasts</h3><ul>";
$count = 0;
foreach ($broadcastsResponse['items'] as $broadcastItem) {
// print_r($count+1);
$count = $count+1;
if($count == 1) {
$htmlBody .= sprintf('<li>%s (%s)</li>', $broadcastItem['snippet']['title'],
$broadcastItem['id']);
$stream_id = $broadcastItem['id'];
}
// print_r($broadcastItem);
}
$htmlBody .= '</ul>';
} catch (Google_Service_Exception $e) {
$htmlBody = sprintf('<p>A service error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
} catch (Google_Exception $e) {
$htmlBody = sprintf('<p>An client error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
}
$_SESSION[$tokenSessionKey] = $client->getAccessToken();
} elseif ($OAUTH2_CLIENT_ID == 'Replace_me') {
$htmlBody = <<<END
<h3>Client Credentials Required</h3>
<p>
You need to set <code>\$OAUTH2_CLIENT_ID</code> and
<code>\$OAUTH2_CLIENT_ID</code> before proceeding.
<p>
END;
} else {
// If the user hasn't authorized the app, initiate the OAuth flow
$state = mt_rand();
$client->setState($state);
$_SESSION['state'] = $state;
$authUrl = $client->createAuthUrl();
$htmlBody = <<<END
<h3>Authorization Required</h3>
<p>You need to authorize access before proceeding.<p>
END;
}
?>
<!doctype html>
<html>
<head>
<title>My Live Broadcasts</title>
</head>
<body>
<?php echo $stream_id; ?>
</body>
</html>
Any idea what can i do?
NB: My purpose is, any one can authenticate here and can get latest youtube streaming id. But I'm struct with oAuth after 3600 seconds.
:(
Your Access Token has an expiry time. The expiry usually is half an hour (1800 seconds), although this can vary. The value is set by the Authentication Server. The expiry time is sent to you along with the Access Token.
After the Access Token expires, the server will no longer accept it. You must request a new one using your Refresh Token. You should have gotten it along with the first Access Token.
If you do not have a Refresh Token, you'll have to log in again.

On Tomcat Server Using Yii Framework HTTP_X_USERNAME locally recognized but not online

I prepared an api using yii framework. The api contains an authentication method which checks the HTTP_X_USERNAME and HTTP_X_PASSWORD parameters and compares them with some data in the database.
While testing everything locally on the test dev (WAMP + Eclipse + Tomcat) it worked normally. I tested everything with the Postman. I have put those two parameters (HTTP_X_...) into the header.
After I uploaded the api to the production server (Tomcat) the api always returns authentication FALSE although the authorization data locally and online is the same. The code stops at the part where it checks if those parameters are even set "You must be authorized to access the api. No USERNAME and PASSWORD set.".
Does any one have an idea where the problem is? Why does it work locally and not online???
private function _checkAuth() {
$headers = apache_request_headers ();
if (! (isset ( $headers ['HTTP_X_USERNAME'] ) and isset ( $headers ['HTTP_X_PASSWORD'] ))) {
// Error: Unauthorized
$this->badResponse ( 401, 'You must be authorized to access the api. No USERNAME and PASSWORD set.');
}
$username = $headers ['HTTP_X_USERNAME'];
$password = $headers ['HTTP_X_PASSWORD'];
// Find the user
$criteria = new CDbCriteria ();
$criteria->addCondition ( 'email = :email');
$criteria->addCondition( 'api_access_token = :pass');
$criteria->params = array(':email' => $username, ":pass" => $password);
$school = AutoSchool::model ()->find ( $criteria );
if ($school === null) {
$this->badResponse ( 401, 'Error: You must be authorized to access the api.' );
}
return $school->id;
}
Finally found the problem!
After debuging found that the problem was the method apache_request_headers() since it did not return anything useful which i set in the header.
I implemented my own method
private function apache_request_headers2() {
foreach($_SERVER as $key=>$value) {
if (substr($key,0,5)=="HTTP_") {
$key=str_replace(" ","-",ucwords(strtolower(str_replace("_"," ",substr($key,5)))));
$out[$key]=$value;
}else{
$out[$key]=$value;
}
}
return $out;
}
But this is not all. I had to change the header parameters i was requesting. I had to use $headers ['PHP_AUTH_USER'] and $headers ['PHP_AUTH_PW'] instead of HTTP_X_USERNAME and HTTP_X_PASSWORD.
And finally while issuing the POST request I had to use Basic Authentication and not setting the Header parameters
And the complete code of the edited method:
private function _checkAuth() {
$headers = $this->apache_request_headers2();
if (! (isset ( $headers ['PHP_AUTH_USER'] ) and isset ( $headers ['PHP_AUTH_PW'] ))) {
// Error: Unauthorized
$this->badResponse ( 401, 'You must be authorized to access the api. No USERNAME and PASSWORD set.');
}
$username = $headers ['PHP_AUTH_USER'];
$password = $headers ['PHP_AUTH_PW'];
// Find the user
$criteria = new CDbCriteria ();
$criteria->addCondition ( 'email = :email');
$criteria->addCondition( 'api_access_token = :pass');
$criteria->params = array(':email' => $username, ":pass" => $password);
$school = AutoSchool::model ()->find ( $criteria );
if ($school === null) {
$this->badResponse ( 401, 'Error: You must be authorized to access the api.' );
}
return $school->id;
}

Google Plus Login API not working on production server

I have implemented the google plus api on development server and it works fine. I used the same code on production server. But after requesting the permission it takes a long time to return to my site and login.
Can anyone please let me know what might be the cause. I have used oauth2.
Below is the code I am using
<?php
session_start();
require_once 'googleplus/src/Google_Client.php';
require_once 'googleplus/src/contrib/Google_Oauth2Service.php';
class Webpage_UserGPlusLogin extends Webpage
{
public function __construct()
{
$temp_redirect = $_SESSION['RETURN_URL_AFTERLOGIN'];
$this->title = 'User Account';
$client = new Google_Client();
$client->setApplicationName(WEBSITE_NAME);
$client->setClientId(GOOGLE_PLUS_CLIENT_ID); // Client Id
$client->setClientSecret(GOOGLE_PLUS_CLIENT_SECRET); // Client Secret
$client->setRedirectUri(GOOGLE_PLUS_REDIRECT_URI); // Redirect Uri set while creating API account
$client->setDeveloperKey(GOOGLE_PLUS_DEVELOPER_KEY); // Developer Key
$oauth2 = new Google_Oauth2Service($client);
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
$redirect = GOOGLE_PLUS_REDIRECT_URI;
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL)); // Redirects to same page
return;
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if (isset($_REQUEST['logout'])) {
unset($_SESSION['token']);
$client->revokeToken();
}
if(!isset($_SESSION['email_address_user_account'])) // Check if user is already logged in or not
{
if ($client->getAccessToken()) {
$user = $oauth2->userinfo->get(); // Google API call to get current user information
$email = filter_var($user['email'], FILTER_SANITIZE_EMAIL);
$img = filter_var($user['picture'], FILTER_VALIDATE_URL);
$googleuserid = $user['id'];
$given_name = $user['given_name'];
$family_name = $user['family_name'];
// The access token may have been updated lazily.
$_SESSION['token'] = $client->getAccessToken();
// If email address is present in DB return user data else insert user info in DB
$this->result = UserAccount::gplus_sign_up($email, $googleuserid, $given_name, $family_name);
// Create new user object.
$this->user_account = new UserAccount($this->result['id'],$this->result['email_address'],$this->result['password'],$this->result['confirmation_code'],$this->result['is_confirmed'], $this->result['first_name'], $this->result['last_name']);
$_SESSION['gplus_email_address'] = $email;
$_SESSION['gplus_first_name'] = $given_name;
$_SESSION['gplus_last_name'] = $family_name;
$_SESSION['gplus_id'] = $googleuserid;
$_SESSION['gplus_profile_pic'] = $img;
$_SESSION['email_address_user_account'] = $email;
} else {
$authUrl = $client->createAuthUrl();
}
}
if(isset($temp_redirect))
header("Location:".$temp_redirect);
else
header("Location:/");
}
}
Thanks in advance
Try this
use following code
$temp = json_decode($_SESSION['token']);
$request = "https://www.googleapis.com/oauth2/v1/userinfo?alt=json";
$curl = curl_init();
curl_setopt($curl,CURLOPT_URL,$request);
curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
curl_setopt($curl,CURLOPT_TIMEOUT,30);
curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($curl, CURLINFO_HEADER_OUT, true);
curl_setopt($curl,CURLOPT_HTTPHEADER,array('Authorization: OAuth '.$temp->access_token));
$response = trim(curl_exec($curl));
$info = curl_getinfo($curl);
$request_header_info = curl_getinfo($curl, CURLINFO_HEADER_OUT);
//var_dump($info);
//var_dump($request_header_info);
curl_close($curl);
echo "<pre>";
print_r(json_decode($response));
instade of
$user = $oauth2->userinfo->get(); // Google API call to get current user information`enter code here`
Hope this will help you .. :)