How to send custom HTTP header in response? - php

I want to send json data in my HTTP Header.
I am using Codeigniter PHP, so I did this in my controller:
header('Content-Type: application/json');'
This is my code:
$request = array(
'request' => $_GET['request'],
'device_id' => $_GET['device_id'],
'launch_date'=> $_GET['launch_date'],
'allowed_hours'=>$_GET['allowed_hours'],
'site_id'=>$_GET['site_id'],
'product'=>$_GET['product'],
'software_version'=>$_GET['software_version'],
'platform_os'=>$_GET['platform_os'],
'platform'=>$_GET['platform'],
'platform_model'=>$_GET['platform_model']
);
$response = array(
'response_code' =>200 ,
'device_id'=>$_GET['device_id'],
'allowed_hours'=>$_GET['allowed_hours'],
'product'=>'mlc',
'prov_ur'=>NULL
);
header('Content-Type: application/json');
echo json_encode( $response );
But when I print my header I get
A PHP Error was encountered
Severity: Notice Message: Undefined index: request
Filename: admin/license.php Line Number: 22
A PHP Error was encountered
Severity: Notice Message: Undefined index:
allowed_hours Filename: admin/license.php Line Number:
25
A PHP Error was encountered
Severity: Notice Message: Undefined index:
allowed_hours Filename: admin/license.php Line Number:
40
{"response_code":200,"device_id":"70D0D01FBAD2","allowed_hours":null,"product":"mlc","prov_ur":null}array(10)
{ ["Host"]=> string(14) "192.168.50.123" ["Connection"]=>
string(10) "keep-alive" ["Cache-Control"]=> string(9) "max-age=0"
["Accept"]=> string(74)
"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,/;q=0.8"
["Upgrade-Insecure-Requests"]=> string(1) "1" ["User-Agent"]=>
string(110) "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36"
["Accept-Encoding"]=> string(19) "gzip, deflate, sdch"
["Accept-Language"]=> string(14) "en-US,en;q=0.8" ["Cookie"]=>
string(518)
"cisession=OhhBBhVodwwf7Tb55AVsU32ClMS5cgmxBl15WHA%2BrGnvo1kiK%2B67BWeAuJVSV2MY25zZd0riHC9cyx9fiigiBuqkPMT%2FKE9d6et%2FXaE3F7I59P9%2FEzy5byQ5nEkJq5xwXoH1I7%2B7v62cQL21%2Bjfnk3AwIy4luM7N51IUuTqg7TxunoZFD1gJO84r8degY1imNpmDk2W%2FjsQPn9bQpkWJ9KVMxxViFDaELEU0rIfYmif%2BdvXjK9W%2Fj7iWQxZYE9ZGazgBTKlLO%2BJZHNdPrdmGPFTzTUROZdffpF%2Bb25bRMPEJsZ9CE2mdVuSn%2FEu678utd0lcd9bh%2BDbTDikrHP4jBFOLbZfWKT%2F9r5GkMBrLBl%2BlvPx9RbAq%2FIsjeA1V7c6JYf41TO1bG2XKT14QFHm8m0qY8HCal%2B%2BR8tZe9i3zy24%3Dcfc459942e4ef82a5554257216a19d621f446a25"
["If-Modified-Since"]=> string(29) "Thu, 01 Jan 1970 00:00:00 GMT" }
{"response_code":200,"device_id":"70D0D01FBAD2","allowed_hours":null,"product":"mlc","prov_ur":null}
in my response. I don't want to send other data in my HTTP header response.
Upadted Code as per CI
public function index()
{
$request = array(
'request' => $this->get('request'),
'device_id' => $this->get('device_id'),
'launch_date'=> $this->get('launch_date'),
'allowed_hours'=>$this->get('allowed_hours'),
'site_id'=> $this->get('site_id'),
'product'=>$this->get('product'),
'software_version'=> $this->get('software_version'),
'platform_os'=> $this->get('platform_os'),
'platform'=> $this->get('platform'),
'platform_model'=> $this->get('platform_model')
);
$response = array(
'response_code' =>200 ,
'device_id'=> $this->get('device_id'),
'allowed_hours'=> $this->get('allowed_hours'),
'product'=>'mlc',
'prov_ur'=>NULL
);
$this->output->set_content_type('Content-Type: application/json');
return $this->output
->set_content_type('Content-Type: application/json')
->set_output(json_encode($response));
echo $response;
}

The problem is that some of your $_GET variables aren't set, this will throw an error (the extra output text you have) and can be prevent by checking if they are empty first before using them.
$request = array(
'request' => !empty($_GET['request']) ? $_GET['request'] : '',
'device_id' => !empty($_GET['device_id']) ? $_GET['device_id'] : '',
'launch_date'=> !empty($_GET['launch_date']) ? $_GET['launch_date'] : '',
'allowed_hours'=> !empty($_GET['allowed_hours']) ? $_GET['allowed_hours'] : '',
'site_id'=> !empty($_GET['site_id']) ? $_GET['site_id'] : '',
'product'=> !empty($_GET['product']) ? $_GET['product'] : '',
'software_version'=> !empty($_GET['software_version']) ? $_GET['software_version'] : '',
'platform_os'=> !empty($_GET['platform_os']) ? $_GET['platform_os'] : '',
'platform'=> !empty($_GET['platform']) ? $_GET['platform'] : '',
'platform_model'=> !empty($_GET['platform_model']) ? $_GET['platform_model'] : ''
);
$response = array(
'response_code' =>200 ,
'device_id'=> !empty($_GET['device_id']) ? $_GET['device_id'] : '',
'allowed_hours'=> !empty($_GET['allowed_hours']) ? $_GET['allowed_hours'] : '',
'product'=>'mlc',
'prov_ur'=>NULL
);
header('Content-Type: application/json');
echo json_encode( $response );

Using the normal php get like below will sometimes throw some errors
$_GET['allowed_hours'];
I would recommend change to codeIgniter input class methods.
$this->input->get('allowed_hours');
Codeigniter Input Class will save you putting lot of code.
As said in user guide: With CodeIgniter’s built in methods you can simply do this:
Updated:
$request = array(
'request' => $this->input->get('request'),
'device_id' => $this->input->get('device_id'),
'launch_date'=> $this->input->get('launch_date'),
'allowed_hours'=> $this->input->get('allowed_hours'),
'site_id'=> $this->input->get('site_id'),
'product'=>$this->input->get('product'),
'software_version'=> $this->input->get('software_version'),
'platform_os'=> $this->input->get('platform_os'),
'platform'=> $this->input->get('platform'),
'platform_model'=> $this->input->get('platform_model')
);
Codeigniter has own Output Class
And
$response = array(
'response_code' => 200,
'device_id'=> $this->input->get('device_id'),
'allowed_hours'=> $this->input->get('allowed_hours'),
'product'=> 'mlc',
'prov_ur'=> NULL
);
return $this->output
->set_content_type('Content-Type: application/json')
->set_output(json_encode($response));

Related

WooCommerce 3.5.4 and WordPress 5.0.3 REST API: Image upload broken (woocommerce_product_invalid_image_id)

I am using v2 of the REST API. This code worked fine on an older version of WordPress and WooCommerce. I cannot upload an image to a product.
The first error after the upgrade I got was:
array (
'code' => 'woocommerce_product_image_upload_error',
'message' => 'Invalid image: Sorry, this file type is not permitted for security reasons.',
'data' =>
array (
'status' => 400,
),
Resolved by adding following in wp-config.php to the bottom of the file:
define('ALLOW_UNFILTERED_UPLOADS', true);
The 2nd error I cannot figure out. The image won't upload and leaves a ghost image where it was uploaded.
Code
<?php
require __DIR__ . '/vendor/autoload.php';
use Automattic\WooCommerce\Client;
$woocommerce = new Client(
'http://localhost/wordpress',
'ck_44b92c00ea35e6cc59c89c29051bf67c22e0df3a',
'cs_dd833592a1ef7a00a82c1711fd455db2e4c5bd15',
[
'wp_api' => true,
'version' => 'wc/v2',
]
);
$data['create'][] = array(
'name' => 'TEST',
'regular_price' => '4.50',
'description' => 'TEST DESC',
'type' => 'simple',
'images' => array(
array(
'alt' => '',
'name' => '',
'src' => 'http://demo2.phppointofsale.com/PHP-Point-Of-Sale-Prev/index.php/app_files/view/1',
'position' => 0,
),
)
);
$response = $woocommerce->post('products/batch',$data);
$headers = $woocommerce->http->getResponse()->getHeaders();
var_dump($headers);
var_dump($response);
Response Data
array(13) {
["Date"]=>
string(29) "Thu, 24 Jan 2019 18:22:16 GMT"
["Server"]=>
string(6) "Apache"
["X-Powered-By"]=>
string(9) "PHP/7.2.1"
["X-Robots-Tag"]=>
string(7) "noindex"
["Link"]=>
string(63) "<http://localhost/wordpress/wp-json/>; rel="https://api.w.org/""
["X-Content-Type-Options"]=>
string(7) "nosniff"
["Access-Control-Expose-Headers"]=>
string(27) "X-WP-Total, X-WP-TotalPages"
["Access-Control-Allow-Headers"]=>
string(27) "Authorization, Content-Type"
["Expires"]=>
string(29) "Wed, 11 Jan 1984 05:00:00 GMT"
["Cache-Control"]=>
string(36) "no-cache, must-revalidate, max-age=0"
["Allow"]=>
string(16) "POST, PUT, PATCH"
["Content-Length"]=>
string(3) "139"
["Content-Type"]=>
string(31) "application/json; charset=UTF-8"
}
array(1) {
["create"]=>
array(1) {
[0]=>
array(2) {
["id"]=>
int(0)
["error"]=>
array(3) {
["code"]=>
string(36) "woocommerce_product_invalid_image_id"
["message"]=>
string(27) "#82 is an invalid image ID."
["data"]=>
array(1) {
["status"]=>
int(400)
}
}
}
}
}
Proof https://via.placeholder.com/350x150 is an image
cmuench#cmuench:~$ curl -I "https://via.placeholder.com/350x150";
HTTP/1.1 200 OK
Server: nginx/1.6.2
Date: Mon, 28 Jan 2019 14:07:22 GMT
Content-Type: image/png
Content-Length: 1253
Last-Modified: Sun, 06 Jan 2019 22:00:10 GMT
Connection: keep-alive
ETag: "5c327a6a-4e5"
Expires: Mon, 04 Feb 2019 14:07:22 GMT
Cache-Control: max-age=604800
X-Cache: L1
Accept-Ranges: bytes
http://demo2.phppointofsale.com/PHP-Point-Of-Sale-Prev/index.php/app_files/view/1
headers from actual files (not demo example). Same error as demo example
header("Cache-Control: max-age=2592000");
header('Expires: '.gmdate('D, d M Y H:i:s', strtotime('+1 month')).' GMT');
header('Pragma: cache');
header('Content-Disposition: inline; filename="'.$file_name.'"');
header("Content-type: ".get_mime_by_extension($file->file_name));
Because the url doesn't include a file extension in it's name, Wordpress treats it as a file with no extension thus failing the wp_check_filetype_and_ext test.
You can add a filter to add the correct file extension where non exists in the url
add_filter('wp_handle_sideload_prefilter', 'add_extension_if_none_exists');
function add_extension_if_none_exists($file){
if ( pathinfo( $file['name'], PATHINFO_EXTENSION ) ) {
return $file;
}
$real_mime = wp_get_image_mime( $file['tmp_name'] );
$mime_to_ext = apply_filters(
'getimagesize_mimes_to_exts',
array(
'image/jpeg' => 'jpg',
'image/png' => 'png',
'image/gif' => 'gif',
'image/bmp' => 'bmp',
'image/tiff' => 'tif',
'image/webp' => 'webp',
)
);
if ( ! empty( $mime_to_ext[ $real_mime ] ) ) {
$file['name'] .= '.' . $mime_to_ext[ $real_mime ];
}
return $file;
}
even the remote server returns "Content-Type: image/png", Wordpress's server side retrieval function did not get the file name because lack of the name in your rest request and no filename in the remote server response, which cause the internal wp_attachment_is_image() test failed. Try set the rest request with file name with proper file extension.
refer to the woocommerce source code:
https://github.com/woocommerce/woocommerce/blob/00a93ae8f0b200b4def4aea4462fec9d1d5ea96c/includes/api/v2/class-wc-rest-products-v2-controller.php
and Wordpress code:
https://core.trac.wordpress.org/browser/tags/5.0.3/src/wp-includes/post.php
Just setup a similar environment, your code works, the problem lies with your image link, curl seems to get the url response as html rather than an image (https://via.placeholder.com/350x150). From the docs "src" is a string containing Image URL unfortunately the string you provide is NOT an image url.You'll just need to point to image files directly the code below works fine for me.
<?php
require __DIR__ . '/vendor/autoload.php';
use Automattic\WooCommerce\Client;
$woocommerce = new Client(
'http://localhost/wordpress',
'ck_a3ec02fcd547837c384e43ee6989200cca8f6178',
'cs_f60e9ad5c93c9e3bd4adaabd4bd323edddb58f7b',
[
'wp_api' => true,
'version' => 'wc/v2',
]
);
$data['create'][] = array(
'name' => 'TEST',
'regular_price' => '4.50',
'description' => 'TEST DESC',
'type' => 'simple',
'images' => array(
array(
'src' => 'http://demo.woothemes.com/woocommerce/wp-content/uploads/sites/56/2013/06/T_2_front.jpg',
),
)
);
$response = $woocommerce->post('products/batch',$data);
$headers = $woocommerce->http->getResponse()->getHeaders();
var_dump($headers);
var_dump($response);
Maybe it's a bug on WooCommerce on the version you're using. If it's the case: If you are uploading a new image by using an external URL, you should include id field and set it to "0"
"images": [
{
"src": "http://demo.woothemes.com/woocommerce/wp-content/uploads/sites/56/2013/06/T_2_front.jpg",
"id": "0"
}
]
If you are using an image from your WordPress media, you should set the id of the image along with the link on WP there.

PHP Laravel: SoapClient Issue Fatal Error: call to a member function __soapCall() on null

I'm working on a project using a SOAP interface to another server and am having some serious issues getting this to work. SOAP is not something I am very familiar with and I have been having a really tough time finding help for this anywhere. Even the people who developed the WSDL file have no ability to help me...
I have a WSDL file - https://sdkdev.wagefiler.com/WageFilerWS/wagefiler.asmx?WSDL
For starters, I need to be able to create an account. The code below works but returns an error of "-999" which is undefined according to the developers of the WSDL and the other server side. They told me to make sure I'm passing an instance of an AccountRequest Object... but nothing I do seems to help.
This is my SoapController.php file. My route points to "demo". It literally returns an error -999.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use Artisaninweb\SoapWrapper\SoapWrapper;
use Sentinel;
use App\backendInformation;
use SoapClient;
use SoapHeader;
use SoapParam;
use SoapVar;
class SoapController extends Controller
{
public function demo()
{
$WSDL = 'https://sdkdev.wagefiler.com/WageFilerWS/wagefiler.asmx?WSDL';
$user = Sentinel::getUser();
$backendInfo = backendInformation::where('user_id', $user['id'])->first();
$b = new backendInformation();
$b->user_id = $user['id'];
$b->username = $user['email'];
$b->password = crypt($b['username'], '$5$rounds=5000$anexamplestringforsalt$');
$b->customername = $user['first_name'] . ' ' . $user['last_name'];
$b->useremail = $user['email'];
$b->autoemail = $user['email'];
$options = [
'trace' => true,
'cache_wsdl' => WSDL_CACHE_NONE
];
$credentials = [
'ClientID' => 'XXXX'
];
$data = array(
'sequence' => array(
'UserID' => $user->nelco_user_id,
'Password' => $user->nelco_password,
'Email' => $b->useremail,
'ClientId' => config('global.nelco_client_id'),
'FName' => $user->first_name,
'LName' => $user->last_name,
'EIN' => $user->ein,
'Addr1' => $user->addr1,
'City' => $user->city,
'State' => $user->state,
'Zip' => $user->zip,
'Phone' => $user->phone,
),
);
$client = new SoapClient($WSDL, $options); // null for non-wsdl mode
$param = new SoapParam(new SoapVar($data, SOAP_ENC_OBJECT), 'AccountRequest');
$client->__soapCall('AccountSetup',array($param));
echo "<pre>";
var_dump($client);
echo "</pre>";
}
}
The return value looks like this -
object(SoapClient)#267 (12) {
["trace"]=>
int(1)
["_stream_context"]=>
resource(8) of type (stream-context)
["_soap_version"]=>
int(1)
["sdl"]=>
resource(10) of type (SOAP SDL)
["__last_request"]=>
string(972) "
UserIDbob#bob.comPassword$5$rounds=5000$anexamplestringf$ADNI5REUuQNRHFXv3tId EhLg65jb4Jc0csmuI4ENQu6Emailbob#bob.comClientId8266FNameBobLNameMcBobbersonEI N123123123Addr1123 Bobs PlaceCityBobvilleStateokZip73115Phone123-123-1234
"
["httpsocket"]=>
resource(11) of type (stream)
["_use_proxy"]=>
int(0)
["httpurl"]=>
resource(12) of type (SOAP URL)
["__last_request_headers"]=>
string(259) "POST /WageFilerWS/wagefiler.asmx HTTP/1.1
Host: sdkdev.wagefiler.com
Connection: Keep-Alive
User-Agent: PHP-SOAP/7.1.8-1ubuntu1
Content-Type: text/xml; charset=utf-8
SOAPAction: "http://localhost/WageFiler/WageFiler/AccountSetup"
Content-Length: 972
"
["__last_response_headers"]=>
string(330) "HTTP/1.1 200 OK
Cache-Control: private, max-age=0
Content-Type: text/xml; charset=utf-8
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Wed, 25 Oct 2017 20:37:54 GMT
Content-Length: 382
Set-Cookie: BIGipServerpool_sdkdev.wagefiler.com_443=3389265580.47873.0000; path=/; Httponly; Secure
"
["_cookies"]=>
array(1) {
["BIGipServerpool_sdkdev.wagefiler.com_443"]=>
array(3) {
[0]=>
string(21) "3389265580.47873.0000"
[1]=>
string(1) "/"
[2]=>
string(20) "sdkdev.wagefiler.com"
}
}
["__last_response"]=>
string(382) "-999"
}
It looks like the SOAP documentation for the WSDL was wrong. They were requiring a bunch of fields that we weren't sending during testing. The WSDL file shows them when you closely examine it but the documentation says they are specifically optional.

no such index [index: ] when trying to scroll with elasticsearch

Since I moved from 2.4 to 5.6, I have an error when using a scroll query :
$query = '{
"scroll" : "1m",
"scroll_id" : "'. $scrollId .'"
}';
$path = '/_search/scroll';
$responseArray = $this->sendQuery($index, $path, Request::GET, $query);
error :
CRITICAL - Uncaught PHP Exception Elastica\Exception\ResponseException: "no such index [index: ]" at /code/vendor/ruflin/elastica/lib/Elastica/Transport/Http.php line 179
Here the initial query I'm using :
$path = 'dataIndex/_search?scroll=1m';
$query = sprintf(
'{
"size" : 500,
"stored_fields": "_source"
}'
);
And how I call my scroll function
$hits = $this->getElasticNextScroll($this->dataIndex, $hits['_scroll_id']);
One of the solution I tried was to send the request with POST but I got another error :
CRITICAL - Uncaught PHP Exception Elastica\Exception\ResponseException: "String index out of range: 0" at /code/vendor/ruflin/elastica/lib/Elastica/Transport/Http.php line 179
EDIT SOLUTION :
the path '/_search/scroll' worked in 2.4 but doesn't work anymore in 5.3. You need to remove the first / : '_search/scroll'
specify what value is passed to $index and what is included in the Request :: GET function
Index {#9208
-originalName: null
-typeCache: []
#_name: "index_data"
#_client: Client {#9234
-indexCache: array:1 [
"index_data" => Index {#9208}
]
-stopwatch: Stopwatch {#157
...
And here the stack error I have :
[1] Elastica\Exception\ResponseException: no such index [index: ] at n/a in /code/vendor/ruflin/elastica/lib/Elastica/Transport/Http.php line 179
at Elastica\Transport\Http->exec(object(Request), array('connection' => array('config' => array('headers' => array(), 'curl' => array()), 'host' => '127.0.0.1', 'port' => '9200', 'logger' => false, 'ssl' => false, 'compression' => false, 'retryOnConflict' => '0', 'enabled' => true))) in /code/vendor/ruflin/elastica/lib/Elastica/Request.php line 193
at Elastica\Request->send() in /code/vendor/ruflin/elastica/lib/Elastica/Client.php line 674
at Elastica\Client->request('/_search/scroll', 'GET', '{ "scroll" : "1m", "scroll_id" : "DnF1ZXJ5VGhlbkZldGNoBAAAAAAAAAPfFnF2VnFBRzFWU0RTaTAwVVZLSl9UU2cAAAAAAAAD3RZxdlZxQUcxVlNEU2kwMFVWS0pfVFNnAAAAAAAAA-AWcXZWcUFHMVZTRFNpMDBVVktKX1RTZwAAAAAAAAPeFnF2VnFBRzFWU0RTaTAwVVZLSl9UU2c=" }', array(), 'application/json') in /code/vendor/friendsofsymfony/elastica-bundle/Elastica/Client.php line 50
at FOS\ElasticaBundle\Elastica\Client->request('/_search/scroll', 'GET', '{ "scroll" : "1m", "scroll_id" : "DnF1ZXJ5VGhlbkZldGNoBAAAAAAAAAPfFnF2VnFBRzFWU0RTaTAwVVZLSl9UU2cAAAAAAAAD3RZxdlZxQUcxVlNEU2kwMFVWS0pfVFNnAAAAAAAAA-AWcXZWcUFHMVZTRFNpMDBVVktKX1RTZwAAAAAAAAPeFnF2VnFBRzFWU0RTaTAwVVZLSl9UU2c=" }') in /code/src/AppBundle/Repository/ElasticSearch/BaseElasticSearchRepository.php line 22

Why session is false in Codeigniter?

After success autorization I get array with a information about user:
$authdata = array(
'logged_in' => true,
'id_user' => $checked['idUsers'],
'time_auth' => time(),
'status' => $checked['UsersStatus'],
'type' => $checked['UsersTypeAccount'],
);
Then set this array to session Codeigniter(array $checked is not empty, there is a UsersStatus and UsersTypeAccount):
$this->session->set_userdata($authdata);
After do redirect at controller profile:
redirect('profile');
This controllers checks a user session on empty/true:
if ($this->session->userdata("session_id") && $this->session->userdata("type") && (($this->session->userdata("status")){
// Return Success
}
If make var_dump() session:
var_dump($this->session->userdata("type")).'<br>'; // false
var_dump($this->session->userdata("status")).'<br>'; die(); // false
I get a false value, why type and status fields is not true in session?
Edition:
Also I have done:
var_dump($this->session->all_userdata()); die();
Response:
array(5) { ["session_id"]=> string(32) "85d9e0aa1f738c551b4ba649c36f977c" ["ip_address"]=> string(12) "46.32.174.82" ["user_agent"]=> string(109) "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36" ["last_activity"]=> int(1416142399) ["user_data"]=> string(0) "" }
So, session is created, but without fields status, type
From tutorial:
$newdata = array(
'username' => 'johndoe',
'email' => 'johndoe#some-site.com',
'logged_in' => TRUE
);
$this->session->set_userdata($newdata);
Important:
$this->session->set_userdata($authdata);
var_dump($this->session->all_userdata()); die(); // Here I get full session array.
After some a long attempts to resolve this trouble I had decided:
Update Codeigniter to version 2.2
After the code had worked:
Set session:
$this->session->set_userdata($authdata);
Get session:
$type = $this->session->userdata['type'];
$status = $this->session->userdata['status'];
$session_id = $this->session->userdata['session_id'];
It helped me, maybe someone too

I call a function with cURL and get a response but when i call the exact same function with soapclient i get a fault

What do I need:
I need some help figuring out an error that i receive from calling a function from a WSDL file with soapclient. Or I would like some help extracting data from a cURL response.
What am I trying to reach:
I am trying to reach to call a function from a WSDL, and get a response from the action.
What are my experiences:
I can call the actions storeOrders succesfull with a cURL statement, I do also get a response.
But with the given response i guess a string. I am not able to extract the data out of it.
So I tried to request the same action from the server but then using soapclient, but I keep getting a error.
What I already tried:
I tried to make the cURL response a new SimpleXMLElement, but it always returns a emty object. Also when I try to reach one of the children.
I tried to make the cURL reponse return as an array and loop trough it with a foreach, also here I got an empty object.
I tried to explode the cURL reponse, but also there i had some problems with the wrong data being returned.
I tried to call it with SoapClient, but I keep getting this error.
So I would like some help with extracting data from cURL, or processing the request with SoapClient.
My cURL request (with answer, all the variables are set with the correct data):
function storeOrderAndGetLabel($delisId, $auth_token, $messageLanguage, $printerLanguage, $paperFormat, $identificationNumber,
$sendingDepot, $product, $mpsCompleteDelivery, $send_name, $send_street, $send_country, $send_zipcode, $send_city,
$send_customerNumber, $rec_name, $rec_street, $rec_state, $rec_country, $rec_zipcode, $rec_city, $parcelLabelNumber,
$orderType)
{
$xml = '
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns="http://dpd.com/common/service/types/Authentication/2.0" xmlns:ns1="http://dpd.com/common/service/types/ShipmentService/3.1">
<soapenv:Header>
<ns:authentication>
<delisId>'.$delisId.'</delisId>
<authToken>'.$auth_token.'</authToken>
<messageLanguage>'.$messageLanguage.'</messageLanguage>
</ns:authentication>
</soapenv:Header>
<soapenv:Body>
<ns1:storeOrders>
<printOptions>
<printerLanguage>'.$printerLanguage.'</printerLanguage>
<paperFormat>'.$paperFormat.'</paperFormat>
</printOptions>
<order>
<generalShipmentData>
<identificationNumber>'.$identificationNumber.'</identificationNumber>
<sendingDepot>'.$sendingDepot.'</sendingDepot>
<product>'.$product.'</product>
<mpsCompleteDelivery>'.$mpsCompleteDelivery.'</mpsCompleteDelivery>
<sender>
<name1>'.$send_name.'</name1>
<street>'.$send_street.'</street>
<country>'.$send_country.'</country>
<zipCode>'.$send_zipcode.'</zipCode>
<city>'.$send_city.'</city>
<customerNumber>'.$send_customerNumber.'</customerNumber>
</sender>
<recipient>
<name1>'.$rec_name.'</name1>
<street>'.$rec_street.'</street>
<state>'.$rec_state.'</state>
<country>'.$rec_country.'</country>
<zipCode>'.$rec_zipcode.'</zipCode>
<city>'.$rec_city.'</city>
</recipient>
</generalShipmentData>
<parcels>
<parcelLabelNumber>'.$parcelLabelNumber.'</parcelLabelNumber>
</parcels>
<productAndServiceData>
<orderType>'.$orderType.'</orderType>
</productAndServiceData>
</order>
</ns1:storeOrders>
</soapenv:Body>
</soapenv:Envelope>
';
$headers = array(
"POST HTTP/1.1",
"Content-type: application/soap+xml; charset=\"utf-8\"",
"SOAPAction: \"http://dpd.com/common/service/ShipmentService/3.1/storeOrders\"",
"Content-length: ".strlen($xml)
);
$cl = curl_init('https://public-ws-stage.dpd.com/services/ShipmentService/V3_1/');
curl_setopt($cl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($cl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($cl, CURLOPT_POST, 1);
curl_setopt($cl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($cl, CURLOPT_POSTFIELDS, "$xml");
curl_setopt($cl, CURLOPT_RETURNTRANSFER, 1);
$output_cl = json_decode(trim(json_encode(curl_exec($cl))), TRUE);
return $output_cl;
//return $output_cl;
}
And from this code i get the reponse, i guess it is a string but i don't know for sure:
<soap:envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:body>
<ns2:storeordersresponse xmlns:ns2="http://dpd.com/common/service/types/ShipmentService/3.1">
<orderresult>
<parcellabelspdf>pdfkey</parcellabelspdf>
<shipmentresponses>
<identificationnumber>identificationnumber</identificationnumber>
<mpsid>mpsid</mpsid>
<parcelinformation>
<parcellabelnumber>labelnr</parcellabelnumber>
</parcelinformation>
</shipmentresponses>
</orderresult>
</ns2:storeordersresponse>
</soap:body>
</soap:envelope>
Now my function calling the SoapClient function:
$label = storeOrderAndGetLabel($delisId, $auth_token, $messageLanguage, $printerLanguage, $paperFormat, $identificationNumber,
$sedingDepot, $product, $mpsCompleteDelivery, $send_name, $send_street, $send_country, $send_zipcode, $send_city,
$send_customerNumber, $rec_name, $rec_street, $rec_state, $rec_country, $rec_zipcode, $rec_city, $parcelLabelNumber,
$orderType);
print_r($label);
now the soap call itself:
function storeOrderAndGetLabel($delisId, $auth_token, $messageLanguage, $printerLanguage, $paperFormat, $identificationNumber,
$sendingDepot, $product, $mpsCompleteDelivery, $send_name, $send_street, $send_country, $send_zipcode, $send_city,
$send_customerNumber, $rec_name, $rec_street, $rec_state, $rec_country, $rec_zipcode, $rec_city, $parcelLabelNumber,
$orderType)
{
$client = new SoapClient('https://public-ws-stage.dpd.com/services/ShipmentService/V3_1?WSDL');
$label = $client->storeOrders
(array
(
"printOptions" => array
(
"printerLanguage" => "$printerLanguage",
"paperFormat" => "$paperFormat"
),
"order" => array
(
"generalShipmentData" => array
(
"identificationNumber" => "$identificationNumber",
"sendingDepot" => "$sendingDepot",
"product" => "$product",
"mpsCompleteDelivery" => "$mpsCompleteDelivery",
"sender" => array
(
"name1" => "$send_name",
"street" => "$send_street",
"country" => "$send_country",
"zipCode" => "$send_zipcode",
"city" => "$send_city",
"customerNumber" => "$send_customerNumber"
),
"recipient" => array
(
"name1" => "$rec_name",
"street" => "$rec_street",
"state" => "$rec_state",
"country" => "$rec_country",
"zipCode" => "$rec_zipcode",
"city" => "$rec_city"
)
),
"parcels" => array
(
"parcelLabelNumber" => "$parcelLabelNumber"
),
"productAndServiceData" => array
(
"orderType" => "$orderType"
)
)
)
);
return $label;
}
The error I receive from the soapcall:
Fatal error: Uncaught SoapFault exception: [soap:Server] Fault occurred while processing. in getLabel.php:107 Stack trace: #0 getLabel.php(107): SoapClient->__call('storeOrders', Array) #1 getLabel.php(107): SoapClient->storeOrders(Array) #2 getLabel.php(38): storeOrderAndGetLabel('username', 'password...', 'nl_NL', 'PDF', 'A4', '77777', '0163', 'CL', '0', 'uname', 'straat', 'NL', 'zipcode', 'City', '341546246451...', 'Test-Empfaenger', 'Test-Strasse', 'BY', 'DE', '123451', 'ahahaha', '16231545', 'consignment') #3 {main} thrown in getLabel.php on line 107
I would like to extract the parcellabelspdf key and the mpsid from the response. It would be really nice if someone could take a look at it.
Two possible problems:
You need to authenticate when calling the DPD ShipmentService. See below for a working example.
Make sure, that the parameter mpsCompleteDelivery is passed as an integer (0), not the string "false". Consider changing this line:
"mpsCompleteDelivery" => "$mpsCompleteDelivery"
to:
"mpsCompleteDelivery" => $mpsCompleteDelivery
Here is a full example including the login and output of a DPD-label as PDF:
// Let's log in first...
$c = new SoapClient('https://public-ws-stage.dpd.com/services/LoginService/V2_0?wsdl');
$res = $c->getAuth(array(
'delisId' => 'your-Id',
'password' => 'your-Password',
'messageLanguage' => 'de_DE'
));
// ...and remember the token.
$auth = $res->return;
// ...and then generate a label
$c = new SoapClient('https://public-ws-stage.dpd.com/services/ShipmentService/V3_1?wsdl');
$token = array(
'delisId' => $auth->delisId,
'authToken' => $auth->authToken,
'messageLanguage' => 'de_DE'
);
// Set the header with the authentication token
$header = new SOAPHeader('http://dpd.com/common/service/types/Authentication/2.0', 'authentication', $token);
$c->__setSoapHeaders($header);
try {
$res = $c->storeOrders( array
(
"printOptions" => array(
"paperFormat" => "A4",
"printerLanguage" => "PDF"
),
"order" => array(
"generalShipmentData" => array(
"sendingDepot" => $auth->depot,
"product" => "CL",
"mpsCompleteDelivery" => false,
"sender" => array(
"name1" => "Sender Name",
"street" => "Sender Street 2",
"country" => "DE",
"zipCode" => "65189",
"city" => "Wiesbaden",
"customerNumber" => "123456789"
),
"recipient" => array(
"name1" => "John Malone",
"street" => "Johns Street 34",
"country" => "DE",
"zipCode" => "65201",
"city" => "Wiesbaden"
)
),
"parcels" => array(
"parcelLabelNumber" => "09123829120"
),
"productAndServiceData" => array(
"orderType" => "consignment"
)
)
)
);
} catch (SoapFault $exception) {
echo $exception->getMessage();
die();
}
// Et voilĂ !
header('Content-type: application/pdf');
echo $res->orderResult->parcellabelsPDF;
Check here for more information:
http://labor.99grad.de/2014/10/05/deutscher-paket-dienst-dpd-soap-schnittstelle-mit-php-nutzen-um-versandetikett-als-pdf-zu-generieren/

Categories