Code Monkey home page Code Monkey logo

dhl-express's Introduction

DHL Express SOAP API client

A generated SOAP API client for the DHL Express Global Webservice.

Installation

To install the package, you can use composer:

composer require dreipunktnull/dhl-express

Usage without composer is currently not possible and needs some adjustments in the provided autoloader.

Shipment Requests

A shipment request is usually created through the webservice and in order to mutate (f.e. cancel) it, we need some parameters. You should therefore create your own ShipmentRequest data class and persist the ShipmentDetail data points.

As of now, no such class is included.

class ShipmentRequestService
{
    /**
     * @var string
     */
    private $user;

    /**
     * @var string
     */
    private $password;

    /**
     * @var string
     */
    private $accountNumber;

    /**
     * @param string $user
     * @param string $password
     * @param string $accountNumber
     */
    public function __construct(string $user, string $password, string $accountNumber)
    {
        $this->user = $user;
        $this->password = $password;
        $this->accountNumber = $accountNumber;
    }
    
    /**
     * @param \DateTimeInterface $shipTimestamp
     * @param ContactInfoType    $sender
     * @param ContactInfoType    $recipient
     * @param ShipmentRequest    $shipmentRequest
     * @param string|null        $restrictToServiceType
     *
     * @return \DHL\Express\Webservice\ShipmentDetailType
     */
    public function createShipping(\DateTimeInterface $shipTimestamp, ContactInfoType $sender, ContactInfoType $recipient, ShipmentRequest $shipmentRequest, $restrictToServiceType = null)
    {
        $webservice = $this->prepareWebservice();

        $shipmentInfo = new ShipmentInfoType(
            DropOffType::REQUEST_COURIER,
            $this->calculateShippingType($shipmentRequest),
            ShipmentInfoType::CURRENCY_EUR,
            UnitOfMeasurement::SI
        );

        $shipmentInfo->setAccount($this->accountNumber);

        $internationalDetail = new InternationDetailType(new CommoditiesType('Keine Angabe'));
        $internationalDetail->setContent(Content::DOCUMENTS);

        $requestedShipment = new RequestedShipmentType(
            $shipmentInfo,
            sprintf('%sT%s GMT+01:00', $shipTimestamp->format('Y-m-d'), $shipTimestamp->format('H:i:s')),
            PaymentInfo::DDP,
            $internationalDetail,
            new ShipType($sender, $recipient),
            new docTypeRef_PackagesType(
                new docTypeRef_RequestedPackagesType(
                    self::PACKAGE_WEIGHT,
                    new docTypeRef_DimensionsType(self::PACKAGE_LENGTH, self::PACKAGE_WIDTH, self::PACKAGE_HEIGHT),
                    '1',
                    1,
                    'No Description'
                )
            )
        );

        if (null !== $shipmentRequest->getSpecialPickupInstruction()) {
            $requestedShipment->setSpecialPickupInstruction($shipmentRequest->getSpecialPickupInstruction());
        }

        if (null !== $shipmentRequest->getPickupLocation()) {
            $requestedShipment->setPickupLocation($shipmentRequest->getPickupLocation());
        }

        if ($shipTimestamp instanceof \DateTimeImmutable) {
            $pickupLocationCloseTime = $shipTimestamp->modify('+91 minutes');
        } else {
            $pickupLocationCloseTime = \DateTimeImmutable::createFromMutable($shipTimestamp)->modify('+91 minutes');
        }

        $requestedShipment->setPickupLocationCloseTime($pickupLocationCloseTime->format('H:i'));

        $request = new ProcessShipmentRequestType($requestedShipment);

        $shipmentDetailType = $webservice->createShipmentRequest($request);

        return $shipmentDetailType;
    }
    
    /**
     * This should only be done if the pickup type is something other than PickupType::Regular.
     *
     * @param ShipmentRequest $shipmentRequest
     * @param string $requester This parameter is required but won't be evaluated.
     * @param string $reason    This parameter is optional but may be useful.
     * @return DeleteResponseType
     */
    public function cancel(ShipmentRequest $shipmentRequest, $requester = 'ERNIE_OR_BERT', $reason = DeleteRequestType::REASON_REASON_NOT_GIVEN): DeleteResponseType
    {
        $webservice = $this->prepareWebservice();

        $deleteRequest = new DeleteRequestType(
            $shipmentRequest->getShipmentTime()->format('Y-m-d'),
            $shipmentRequest->getPickupCountry(),
            $shipmentRequest->getDispatchConfirmationNumber(),
            $requester
        );

        $deleteRequest->setReason($reason);

        return $webservice->deleteShipmentRequest($deleteRequest);
    }

    /**
     * @return GblDHLExpressTrack
     */
    private function prepareWebservice(): GblDHLExpressTrack
    {
        $track = new GblDHLExpressTrack(['trace' => 1]);

        $wsse_header = WssWsuAuthHeader::soapClientWSSecurityHeader($this->user, $this->password, $this->accountNumber);
        $track->__setSoapHeaders([$wsse_header]);

        return $track;
    }
}

Tracking

Example Tracking Service that is able to authenticate and track a package:

use DHL\Express\Webservice\Soap\WssWsuAuthHeader;
use DHL\Express\Webservice\Tracking\ArrayOfAWBNumber;
use DHL\Express\Webservice\Tracking\GblDHLExpressTrack;
use DHL\Express\Webservice\Tracking\LevelOfDetails;
use DHL\Express\Webservice\Tracking\PublicTrackingRequest;
use DHL\Express\Webservice\Tracking\Request;
use DHL\Express\Webservice\Tracking\ServiceHeader;
use DHL\Express\Webservice\Tracking\TrackingRequest;
use DHL\Express\Webservice\Tracking\TrackShipmentRequest;
use Ramsey\Uuid\Uuid;

class TrackingService
{
    /**
     * @var string
     */
    private $user;

    /**
     * @var string
     */
    private $password;

    /**
     * @var string
     */
    private $accountNumber;

    /**
     * @param string $user
     * @param string $password
     * @param string $accountNumber
     */
    public function __construct(string $user, string $password, string $accountNumber)
    {
        $this->user = $user;
        $this->password = $password;
        $this->accountNumber = $accountNumber;
    }

    /**
     * Tracks a package.
     *
     * @param string $trackingNumber
     * @param string $levelOfDetails
     * @return \DHL\Express\Webservice\Tracking\trackShipmentRequestResponse
     */
    public function track($trackingNumber, $levelOfDetails = LevelOfDetails::LAST_CHECK_POINT_ONLY)
    {
        $webservice = $this->prepareWebservice();
        $parameters = new TrackShipmentRequest();

        $trackingRequest = new TrackingRequest(new Request(new ServiceHeader(new \DateTime(), implode('', explode('-', Uuid::uuid4())))), $levelOfDetails);
        $trackingRequest->setAWBNumber(new ArrayOfAWBNumber([$trackingNumber]));

        $parameters->setTrackingRequest(new PublicTrackingRequest($trackingRequest));

        return $webservice->trackShipmentRequest($parameters);
    }

    /**
     * @return GblDHLExpressTrack
     */
    private function prepareWebservice(): GblDHLExpressTrack
    {
        $track = new GblDHLExpressTrack(['trace' => 1]);

        $wsse_header = WssWsuAuthHeader::soapClientWSSecurityHeader($this->user, $this->password, $this->accountNumber);
        $track->__setSoapHeaders([$wsse_header]);

        return $track;
    }
}

Acknowledgements

The base version of this library was generated with wsdl2phpgenerator.

Support

Please use the GitHub issue tracker. For commercial support for your project contact dreipunktnull.

License

MIT

dhl-express's People

Contributors

cedricziel avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

dhl-express's Issues

WssWsuAuthHeader

Hello,
Thank you for the nice library! I have two questions for you, if you have the time:

The WssWsuAuthHeader defines a constructor and a static method. Both "seems" to do the same thing, but only the static method is used in your examples. Also, while the constructor "digests" the $nonce, $pass and $ts variables into a base64-encoded sha1 hash, the static method just adds them to a SimpleXMLElement (there is actually a variable - $passdigest - holding the digested value, but it is never used).
So, the questions are:

  1. Do both work, or is the constructor version a leftover from previous versions?
  2. If both work, is there any case where I should use one instead of the other?

Thank you for your time! Have a nice day! :)

(BTW, it could be nice to mention in the documentation that you used the wsdl2phpgenerator library to create the base code... :) )

Example

Hey liebes DreiPunktNull-Team,

ich habe auf Github ihre DHL Express php API gefunden. Das ist echt eine gute Sache. Ich konnte sie auch per Composer erstellen.
Könnt ihr mir das so zur Verfügung stellen, das ich einen Sender, Empfänger, die Zugangsdaten (ggf. Labeltype) eintrage und ein Label zurück bekomme.
Ich blicke da noch nicht ganz durch. Oder gibt es dafür ein Example?

Multiple RequestedPackages

Thanks for sharing this good piece of work.
I was wondering how can you request multiple packages when requesting a shipment? Every time I try like this
new PackagesType([new RequestedPackagesType($weight, $dimensions, $customerReferences, $number), new RequestedPackagesType($weight, $dimensions, $customerReferences, $number)])

SOAP returns the error:

SOAP-ERROR: Encoding: object has no 'Weight' property

If I print the ProcessShipmentRequestType Object the 'Packages' properties as an example would be something like:

[Packages:protected] => DHL\Express\Webservice\docTypeRef_PackagesType Object
                (
                    [RequestedPackages:protected] => Array
                        (
                            [0] => DHL\Express\Webservice\docTypeRef_RequestedPackagesType Object
                                (
                                    [InsuredValue:protected] => 
                                    [Weight:protected] => 2.0000
                                    [Dimensions:protected] => DHL\Express\Webservice\docTypeRef_DimensionsType Object
                                        (
                                            [Length:protected] => 37.5
                                            [Width:protected] => 21.5
                                            [Height:protected] => 13.2
                                        )

                                    [CustomerReferences:protected] => 41938
                                    [number:protected] => 4
                                    [PackageContentDescription:protected] => 
                                )

                            [1] => DHL\Express\Webservice\docTypeRef_RequestedPackagesType Object
                                (
                                    [InsuredValue:protected] => 
                                    [Weight:protected] => 2.0000
                                    [Dimensions:protected] => DHL\Express\Webservice\docTypeRef_DimensionsType Object
                                        (
                                            [Length:protected] => 37.5
                                            [Width:protected] => 21.5
                                            [Height:protected] => 13.2
                                        )

                                    [CustomerReferences:protected] => 41938
                                    [number:protected] => 4
                                    [PackageContentDescription:protected] => 
                                )

                        )

                )

I'm using PHP 7.0.17-2+deb.sury.org~trusty+1

Example

Hey liebes DreiPunktNull-Team,

ich habe auf Github ihre DHL Express php API gefunden. Das ist echt eine gute Sache. Ich konnte sie auch per Composer erstellen.
Könnt ihr mir das so zur Verfügung stellen, das ich einen Sender, Empfänger, die Zugangsdaten (ggf. Labeltype) eintrage und ein Label zurück bekomme.
Ich blicke da noch nicht ganz durch. Oder gibt es dafür ein Example?

Problem with tracking

Hi,
I have a problem with tracking because it doesn’t find any results (No shipment found). How can I resolve?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.