IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Langage PHP Discussion :

difficultés avec l'utilisation d'un web service colissimo


Sujet :

Langage PHP

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre confirmé
    Femme Profil pro
    Étudiant
    Inscrit en
    Avril 2017
    Messages
    126
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : France, Ille et Vilaine (Bretagne)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Avril 2017
    Messages : 126
    Par défaut difficultés avec l'utilisation d'un web service colissimo
    Bonjour à tous,

    Dans le cadre de mon stage de fin de première année de BTS, je tente de mettre en place un des web Service de Colissimo pour automatiser la création d'étiquette.

    Après avoir suivi la documentation à ce sujet, j'ai simplement lancé mon script pour voir si je n'avais pas d'erreur, et malheureusement j'en ai une que je n'arrive pas à résoudre. Voici mon code :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    <?php
    /**** This sample code comes with the shipping web service of La Poste Colissimo
    	* The example builds a request, send it to the web service, then parse its response 
    	* and save the generated label to the specified location
    	* @author :
    ****/
     
    define("SERVER_NAME", 'https://ws.colissimo.fr'); //TODO : Change server name
    define("LABEL_FOLDER",'../etiquettes/'); //TODO : Change OutPut Folder: this is where the label will be saved
    //Build the input request : adapt parameters according to your parcel info and options
    $requestParameter = array(
    	'contractNumber' => '******', //TODO : Change contractNumber
    	'password' => '******', //TODO : Change password
    	'outputFormat' => array(
    		'outputPrintingType' => 'PDF_A4_300dpi'
    	),
    	'letter' => array(
    		'service' => array(
    			'productCode' => 'DOM',
    			'depositDate' => '2018-06-12' //TODO : Change depositDate (must be at least equal to current date)
    			),
    		'parcel' => array(
    			'weight' => '3',
    		),
    		'sender' => array(
    			'address' => array(
    				'companyName' => 'Toner de Breizh',
    				'line2' => '7 rue des Tisserands',
    				'countryCode' => 'FR',
    				'city' => 'Betton',
    				'zipCode' => '35830'
    			)
    		),
    		'addressee' => array(
    			'address' => array(
    				'lastName' => 'Doe',
    				'firstName' => 'John',
    				'line2' => '34 Rue des Tests',
    				'countryCode' => 'FR',
    				'city' => 'VilleTest',
    				'zipCode' => '75017',
    				'email' => 'email@test.fr'
     
    			)
    		)
    	)
    );
    //+ Generate SOAPRequest
    $xml = new SimpleXMLElement('<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"  />');
    $xml->addChild("soapenv:Header");
    $children = $xml->addChild("soapenv:Body");
    $children = $children->addChild("sls:generateLabel", null, 'http://sls.ws.coliposte.fr');
    $children = $children->addChild("generateLabelRequest", null, "");
    array_to_xml($requestParameter,$children);
    $requestSoap = $xml->asXML();
    //- Generate SOAPRequest
     
    //+ Call Web Service
    $resp = new SoapClient ( "http://ws.colissimo.fr/sls-ws/SlsServiceWS?wsdl" );
    $response = $resp->__doRequest ( $requestSoap, 'http://ws.colissimo.fr/sls-ws/SlsServiceWS', 'generateLabel', '2.0', 0 );
    //-Call Web Service
     
    //+ Parse Web Service Response
    $parseResponse = new MTOM_ResponseReader($response);
    $resultat_tmp = $parseResponse->soapResponse;
    $soap_result = $resultat_tmp["data"];
    $error_code = explode("<id>", $soap_result);
    $error_code = explode("</id>", $error_code[1]);
    //-Parse Web Service Response
     
    //+ Error handling and label saving
    if ($error_code[0]=="0") {
    	//+ Write result to file <parcel number>.extension in defined folder (ex: ./labels/6A12091920617.zpl)
    	$resultat_tmp = $parseResponse->soapResponse;
    	$soap_result = $resultat_tmp["data"];
    	$resultat_tmp = $parseResponse->attachments;
    	$label_content = $resultat_tmp[0];
    	$my_datas = $label_content["data"];
    	//Save the label
    	$my_extension_tmp = $requestParameter["outputFormat"]["outputPrintingType"];
    	$my_extension = strtolower(substr($my_extension_tmp,0,3));
    	$pieces = explode("<parcelNumber>", $soap_result); 
    	$pieces = explode("</parcelNumber>", $pieces[1]);
    	$parcelNumber=$pieces[0]; //Extract the parcel number
    	$my_file_name=LABEL_FOLDER.$parcelNumber.".".$my_extension;
    	$my_file = fopen($my_file_name, 'a');
     
    	if (fputs($my_file, $my_datas)){ //Save the label in defined folderfclose($my_file);
    		echo "fichier ".$my_file_name." ok <br>";
    	} else {
    		echo "erreur ecriture etiquette <br>";
    	}
    } else { //Display errors if exist
    	$error_message = explode("<messageContent>", $soap_result);
    	$error_message = explode("</messageContent>", $error_message[1]);
    	echo 'error code : '.$error_code[0]."\n";
    	echo 'error message : '.$error_message[0]."\n";
    }
     
     
    class MTOM_ResponseReader {
     
    	const CONTENT_TYPE = 'Content-Type: application/xop+xml;';
    	const UUID = '/--uuid:/'; //This is the separator of each part of the response
    	const CONTENT = 'Content-';
    	public $attachments = array ();
    	public $soapResponse = array ();
    	public $uuid = null;
    	public function 
     
    	__construct($response) {
    		if (strpos ( $response, self::CONTENT_TYPE ) !== FALSE) {
    			$this->parseResponse( $response );
    		} else {
    			throw new Exception ( 'This response is not : ' . CONTENT_TYPE );
    		}
    	}
     
    	private function parseResponse($response) {
    		$content = array ();
    		$matches = array ();
    		preg_match_all ( self::UUID, $response, $matches, PREG_OFFSET_CAPTURE );
     
    		for($i = 0; $i < count ( $matches [0] ) -1; $i ++) {
    			if ($i + 1 < count ( $matches [0] )) {
    				$content [$i] = substr ( $response,
    				$matches [0] [$i] [1], 
    				$matches [0] [$i + 1] [1] -$matches [0] [$i] [1] );
    			} else {
    				$content [$i] = substr ( $response, $matches [0] [$i] [1], strlen ( $response ) );
    			}
    		}
     
    		foreach ( $content as $part ) {
    			if($this->uuid == null){
    				$uuidStart = 0;
    				$uuidEnd = 0;
    				$uuidStart = strpos($part, self::UUID, 0)+strlen(self::UUID);
    				$uuidEnd = strpos($part, "\r\n", $uuidStart);
    				$this->uuid = substr($part, $uuidStart, $uuidEnd-$uuidStart);
    			}
    			$header = $this->extractHeader($part);
     
    			if(count($header) > 0){
    				if(strpos($header['Content-Type'], 'type="text/xml"')!==FALSE){
    					$this->soapResponse['header'] = $header;
    					$this->soapResponse['data'] = trim(substr($part, 
    					$header['offsetEnd']));
    				} else {
    					$attachment['header'] = $header;
    					$attachment['data'] = trim(substr($part, $header['offsetEnd']));
    					array_push($this->attachments, $attachment);
    				}
    			}
    		}
    	}
    	/**
    	* Exclude the header from the Web Service response 
    	* @param string $part
    	* @return array $header
    	*/
     
    	private function extractHeader($part){
    		$header = array();
    		$headerLineStart = strpos($part, self::CONTENT, 0);
    		$endLine = 0;
    		while($headerLineStart !== FALSE){
    			$header['offsetStart'] = $headerLineStart;
    			$endLine = strpos($part, "\r\n", $headerLineStart);
    			$headerLine = explode(': ', substr($part, $headerLineStart, 
    			$endLine-$headerLineStart));
    			$header[$headerLine[0]] = $headerLine[1];
    			$headerLineStart = strpos($part, self::CONTENT, $endLine);
    		}
    		$header['offsetEnd'] = $endLine;
    		return $header;
    	}
     
    	/**
    	* Convert array to Xml
    	* @param unknown $soapRequest
    	* @param unknown $soapRequestXml
    	*/
    	function array_to_xml($soapRequest, $soapRequestXml) {
    		foreach($soapRequest as $key => $value) {
    			if(is_array($value)) {
    				if(!is_numeric($key)){
    					$subnode = $soapRequestXml->addChild("$key");
    					array_to_xml($value, $subnode);
    				}
    				else{
    					$subnode = $soapRequestXml->addChild("item$key");
    					array_to_xml($value, $subnode);
    				}
    			}
    		else {
    			$soapRequestXml->addChild("$key",htmlspecialchars("$value"));
    		}
    	}
    }
    ?>
    L'erreur est :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    Parse error: syntax error, unexpected 'private' (T_PRIVATE) in C:\wamp64\www\TestEtiquette\php\etiquette.php on line 163
    J'ai vérifié et je ne pense pas avoir oublié de } ou de ;

    Pouvez-vous m'aider svp ?

    Merci d'avance

  2. #2
    Modérateur

    Avatar de MaitrePylos
    Homme Profil pro
    DBA
    Inscrit en
    Juin 2005
    Messages
    5 506
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 52
    Localisation : Belgique

    Informations professionnelles :
    Activité : DBA
    Secteur : Service public

    Informations forums :
    Inscription : Juin 2005
    Messages : 5 506
    Par défaut
    Bonjour, il manque une accolade à la fin de la classe

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
     
    <?php
    /**** This sample code comes with the shipping web service of La Poste Colissimo
     * The example builds a request, send it to the web service, then parse its response
     * and save the generated label to the specified location
     * @author :
     ****/
     
    define("SERVER_NAME", 'https://ws.colissimo.fr'); //TODO : Change server name
    define("LABEL_FOLDER", '../etiquettes/'); //TODO : Change OutPut Folder: this is where the label will be saved
    //Build the input request : adapt parameters according to your parcel info and options
    $requestParameter = array(
        'contractNumber' => '******', //TODO : Change contractNumber
        'password' => '******', //TODO : Change password
        'outputFormat' => array(
            'outputPrintingType' => 'PDF_A4_300dpi'
        ),
        'letter' => array(
            'service' => array(
                'productCode' => 'DOM',
                'depositDate' => '2018-06-12' //TODO : Change depositDate (must be at least equal to current date)
            ),
            'parcel' => array(
                'weight' => '3',
            ),
            'sender' => array(
                'address' => array(
                    'companyName' => 'Toner de Breizh',
                    'line2' => '7 rue des Tisserands',
                    'countryCode' => 'FR',
                    'city' => 'Betton',
                    'zipCode' => '35830'
                )
            ),
            'addressee' => array(
                'address' => array(
                    'lastName' => 'Doe',
                    'firstName' => 'John',
                    'line2' => '34 Rue des Tests',
                    'countryCode' => 'FR',
                    'city' => 'VilleTest',
                    'zipCode' => '75017',
                    'email' => 'email@test.fr'
     
                )
            )
        )
    );
    //+ Generate SOAPRequest
    $xml = new SimpleXMLElement('<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"  />');
    $xml->addChild("soapenv:Header");
    $children = $xml->addChild("soapenv:Body");
    $children = $children->addChild("sls:generateLabel", null, 'http://sls.ws.coliposte.fr');
    $children = $children->addChild("generateLabelRequest", null, "");
    array_to_xml($requestParameter, $children);
    $requestSoap = $xml->asXML();
    //- Generate SOAPRequest
     
    //+ Call Web Service
    $resp = new SoapClient ("http://ws.colissimo.fr/sls-ws/SlsServiceWS?wsdl");
    $response = $resp->__doRequest($requestSoap, 'http://ws.colissimo.fr/sls-ws/SlsServiceWS', 'generateLabel', '2.0', 0);
    //-Call Web Service
     
    //+ Parse Web Service Response
    $parseResponse = new MTOM_ResponseReader($response);
    $resultat_tmp = $parseResponse->soapResponse;
    $soap_result = $resultat_tmp["data"];
    $error_code = explode("<id>", $soap_result);
    $error_code = explode("</id>", $error_code[1]);
    //-Parse Web Service Response
     
    //+ Error handling and label saving
    if ($error_code[0] == "0") {
        //+ Write result to file <parcel number>.extension in defined folder (ex: ./labels/6A12091920617.zpl)
        $resultat_tmp = $parseResponse->soapResponse;
        $soap_result = $resultat_tmp["data"];
        $resultat_tmp = $parseResponse->attachments;
        $label_content = $resultat_tmp[0];
        $my_datas = $label_content["data"];
        //Save the label
        $my_extension_tmp = $requestParameter["outputFormat"]["outputPrintingType"];
        $my_extension = strtolower(substr($my_extension_tmp, 0, 3));
        $pieces = explode("<parcelNumber>", $soap_result);
        $pieces = explode("</parcelNumber>", $pieces[1]);
        $parcelNumber = $pieces[0]; //Extract the parcel number
        $my_file_name = LABEL_FOLDER . $parcelNumber . "." . $my_extension;
        $my_file = fopen($my_file_name, 'a');
     
        if (fputs($my_file, $my_datas)) { //Save the label in defined folderfclose($my_file);
            echo "fichier " . $my_file_name . " ok <br>";
        } else {
            echo "erreur ecriture etiquette <br>";
        }
    } else { //Display errors if exist
        $error_message = explode("<messageContent>", $soap_result);
        $error_message = explode("</messageContent>", $error_message[1]);
        echo 'error code : ' . $error_code[0] . "\n";
        echo 'error message : ' . $error_message[0] . "\n";
    }
     
     
    class MTOM_ResponseReader
    {
     
        const CONTENT_TYPE = 'Content-Type: application/xop+xml;';
        const UUID = '/--uuid:/'; //This is the separator of each part of the response
        const CONTENT = 'Content-';
        public $attachments = array();
        public $soapResponse = array();
        public $uuid = null;
     
        public function
     
        __construct($response)
        {
            if (strpos($response, self::CONTENT_TYPE) !== FALSE) {
                $this->parseResponse($response);
            } else {
                throw new Exception ('This response is not : ' . CONTENT_TYPE);
            }
        }
     
        private function parseResponse($response)
        {
            $content = array();
            $matches = array();
            preg_match_all(self::UUID, $response, $matches, PREG_OFFSET_CAPTURE);
     
            for ($i = 0; $i < count($matches [0]) - 1; $i++) {
                if ($i + 1 < count($matches [0])) {
                    $content [$i] = substr($response,
                        $matches [0] [$i] [1],
                        $matches [0] [$i + 1] [1] - $matches [0] [$i] [1]);
                } else {
                    $content [$i] = substr($response, $matches [0] [$i] [1], strlen($response));
                }
            }
     
            foreach ($content as $part) {
                if ($this->uuid == null) {
                    $uuidStart = 0;
                    $uuidEnd = 0;
                    $uuidStart = strpos($part, self::UUID, 0) + strlen(self::UUID);
                    $uuidEnd = strpos($part, "\r\n", $uuidStart);
                    $this->uuid = substr($part, $uuidStart, $uuidEnd - $uuidStart);
                }
                $header = $this->extractHeader($part);
     
                if (count($header) > 0) {
                    if (strpos($header['Content-Type'], 'type="text/xml"') !== FALSE) {
                        $this->soapResponse['header'] = $header;
                        $this->soapResponse['data'] = trim(substr($part,
                            $header['offsetEnd']));
                    } else {
                        $attachment['header'] = $header;
                        $attachment['data'] = trim(substr($part, $header['offsetEnd']));
                        array_push($this->attachments, $attachment);
                    }
                }
            }
        }
     
        /**
         * Exclude the header from the Web Service response
         * @param string $part
         * @return array $header
         */
     
        private function extractHeader($part)
        {
            $header = array();
            $headerLineStart = strpos($part, self::CONTENT, 0);
            $endLine = 0;
            while ($headerLineStart !== FALSE) {
                $header['offsetStart'] = $headerLineStart;
                $endLine = strpos($part, "\r\n", $headerLineStart);
                $headerLine = explode(': ', substr($part, $headerLineStart,
                    $endLine - $headerLineStart));
                $header[$headerLine[0]] = $headerLine[1];
                $headerLineStart = strpos($part, self::CONTENT, $endLine);
            }
            $header['offsetEnd'] = $endLine;
            return $header;
        }
     
        /**
         * Convert array to Xml
         * @param unknown $soapRequest
         * @param unknown $soapRequestXml
         */
        function array_to_xml($soapRequest, $soapRequestXml)
        {
            foreach ($soapRequest as $key => $value) {
                if (is_array($value)) {
                    if (!is_numeric($key)) {
                        $subnode = $soapRequestXml->addChild("$key");
                        array_to_xml($value, $subnode);
                    } else {
                        $subnode = $soapRequestXml->addChild("item$key");
                        array_to_xml($value, $subnode);
                    }
                } else {
                    $soapRequestXml->addChild("$key", htmlspecialchars("$value"));
                }
            }
        }
    }

  3. #3
    Membre confirmé
    Femme Profil pro
    Étudiant
    Inscrit en
    Avril 2017
    Messages
    126
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : France, Ille et Vilaine (Bretagne)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Avril 2017
    Messages : 126
    Par défaut
    Salut, merci pour ta réponse,

    J'ai ajouté l'accolade, j'ai toujours la même erreur à la même ligne...

  4. #4
    Membre confirmé
    Femme Profil pro
    Étudiant
    Inscrit en
    Avril 2017
    Messages
    126
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : France, Ille et Vilaine (Bretagne)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Avril 2017
    Messages : 126
    Par défaut
    Re,

    Quelqu'un pourrait m'aider ? Je ne vois vraiment pas d'où vient le problème et je suis bloquée, je ne peux plus avancer...

    Merci d'avance,

    Bonne soirée

  5. #5
    Modérateur
    Avatar de sabotage
    Homme Profil pro
    Inscrit en
    Juillet 2005
    Messages
    29 208
    Détails du profil
    Informations personnelles :
    Sexe : Homme

    Informations forums :
    Inscription : Juillet 2005
    Messages : 29 208
    Par défaut
    Tu as bien fermé la classe à la ligne 178 ?
    N'oubliez pas de consulter les FAQ PHP et les cours et tutoriels PHP

  6. #6
    Membre confirmé
    Femme Profil pro
    Étudiant
    Inscrit en
    Avril 2017
    Messages
    126
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : France, Ille et Vilaine (Bretagne)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Avril 2017
    Messages : 126
    Par défaut
    Voici mon code actuel :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    <?php
    /**** This sample code comes with the shipping web service of La Poste Colissimo
     * The example builds a request, send it to the web service, then parse its response
     * and save the generated label to the specified location
     * @author :
     ****/
     
    define("SERVER_NAME", 'https://ws.colissimo.fr'); //TODO : Change server name
    define("LABEL_FOLDER", '../etiquettes/'); //TODO : Change OutPut Folder: this is where the label will be saved
    //Build the input request : adapt parameters according to your parcel info and options
    $requestParameter = array(
        'contractNumber'=> '******', //TODO : Change contractNumber
        'password' => '******', //TODO : Change password
        'outputFormat' => array(
            'outputPrintingType' => 'PDF_A4_300dpi'
        ),
        'letter' => array(
            'service' => array(
                'productCode' => 'DOM',
                'depositDate' => '2018-06-12' //TODO : Change depositDate (must be at least equal to current date)
            ),
            'parcel' => array(
                'weight' => '3',
            ),
            'sender' => array(
                'address' => array(
                    'companyName' => 'Toner de Breizh',
                    'line2' => '7 rue des Tisserands',
                    'countryCode' => 'FR',
                    'city' => 'Betton',
                    'zipCode' => '35830'
                )
            ),
            'addressee' => array(
                'address' => array(
                    'lastName' => 'Doe',
                    'firstName' => 'John',
                    'line2' => '34 Rue des Tests',
                    'countryCode' => 'FR',
                    'city' => 'VilleTest',
                    'zipCode' => '75017',
                    'email' => 'email@test.fr'
     
                )
            )
        )
    );
    //+ Generate SOAPRequest
    $xml = new SimpleXMLElement('<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"  />');
    $xml->addChild("soapenv:Header");
    $children = $xml->addChild("soapenv:Body");
    $children = $children->addChild("sls:generateLabel", null, 'http://sls.ws.coliposte.fr');
    $children = $children->addChild("generateLabelRequest", null, "");
    array_to_xml($requestParameter, $children);
    $requestSoap = $xml->asXML();
    //- Generate SOAPRequest
     
    //+ Call Web Service
    $resp = new SoapClient ("http://ws.colissimo.fr/sls-ws/SlsServiceWS?wsdl");
    $response = $resp->__doRequest($requestSoap, 'http://ws.colissimo.fr/sls-ws/SlsServiceWS', 'generateLabel', '2.0', 0);
    //-Call Web Service
     
    //+ Parse Web Service Response
    $parseResponse = new MTOM_ResponseReader($response);
    $resultat_tmp = $parseResponse->soapResponse;
    $soap_result = $resultat_tmp["data"];
    $error_code = explode("<id>", $soap_result);
    $error_code = explode("</id>", $error_code[1]);
    //-Parse Web Service Response
     
    //+ Error handling and label saving
    if ($error_code[0] == "0") {
        //+ Write result to file <parcel number>.extension in defined folder (ex: ./labels/6A12091920617.zpl)
        $resultat_tmp = $parseResponse->soapResponse;
        $soap_result = $resultat_tmp["data"];
        $resultat_tmp = $parseResponse->attachments;
        $label_content = $resultat_tmp[0];
        $my_datas = $label_content["data"];
        //Save the label
        $my_extension_tmp = $requestParameter["outputFormat"]["outputPrintingType"];
        $my_extension = strtolower(substr($my_extension_tmp, 0, 3));
        $pieces = explode("<parcelNumber>", $soap_result);
        $pieces = explode("</parcelNumber>", $pieces[1]);
        $parcelNumber = $pieces[0]; //Extract the parcel number
        $my_file_name = LABEL_FOLDER . $parcelNumber . "." . $my_extension;
        $my_file = fopen($my_file_name, 'a');
     
        if (fputs($my_file, $my_datas)) { //Save the label in defined folderfclose($my_file);
            echo "fichier " . $my_file_name . " ok <br>";
        } else {
            echo "erreur ecriture etiquette <br>";
        }
    } else { //Display errors if exist
        $error_message = explode("<messageContent>", $soap_result);
        $error_message = explode("</messageContent>", $error_message[1]);
        echo 'error code : ' . $error_code[0] . "\n";
        echo 'error message : ' . $error_message[0] . "\n";
    }
     
     
    class MTOM_ResponseReader{
     
        const CONTENT_TYPE = 'Content-Type: application/xop+xml;';
        const UUID = '/--uuid:/'; //This is the separator of each part of the response
        const CONTENT = 'Content-';
        public $attachments = array();
        public $soapResponse = array();
        public $uuid = null;
     
        public function__construct($response){
     
            if (strpos($response, self::CONTENT_TYPE) !== FALSE) {
                $this->parseResponse($response);
            } else {
                throw new Exception ('This response is not : ' . CONTENT_TYPE);
            }
        }
     
        private function parseResponse($response)
        {
            $content = array();
            $matches = array();
            preg_match_all(self::UUID, $response, $matches, PREG_OFFSET_CAPTURE);
     
            for ($i = 0; $i < count($matches [0]) - 1; $i++) {
                if ($i + 1 < count($matches [0])) {
                    $content [$i] = substr($response,
                        $matches [0] [$i] [1],
                        $matches [0] [$i + 1] [1] - $matches [0] [$i] [1]);
                } else {
                    $content [$i] = substr($response, $matches [0] [$i] [1], strlen($response));
                }
            }
     
            foreach ($content as $part) {
                if ($this->uuid == null) {
                    $uuidStart = 0;
                    $uuidEnd = 0;
                    $uuidStart = strpos($part, self::UUID, 0) + strlen(self::UUID);
                    $uuidEnd = strpos($part, "\r\n", $uuidStart);
                    $this->uuid = substr($part, $uuidStart, $uuidEnd - $uuidStart);
                }
                $header = $this->extractHeader($part);
     
                if (count($header) > 0) {
                    if (strpos($header['Content-Type'], 'type="text/xml"') !== FALSE) {
                        $this->soapResponse['header'] = $header;
                        $this->soapResponse['data'] = trim(substr($part,
                            $header['offsetEnd']));
                    } else {
                        $attachment['header'] = $header;
                        $attachment['data'] = trim(substr($part, $header['offsetEnd']));
                        array_push($this->attachments, $attachment);
                    }
                }
            }
        }
     
        /**
         * Exclude the header from the Web Service response
         * @param string $part
         * @return array $header
         */
     
        private function extractHeader($part)
        {
            $header = array();
            $headerLineStart = strpos($part, self::CONTENT, 0);
            $endLine = 0;
            while ($headerLineStart !== FALSE) {
                $header['offsetStart'] = $headerLineStart;
                $endLine = strpos($part, "\r\n", $headerLineStart);
                $headerLine = explode(': ', substr($part, $headerLineStart, $endLine - $headerLineStart));
                $header[$headerLine[0]] = $headerLine[1];
                $headerLineStart = strpos($part, self::CONTENT, $endLine);
            }
            $header['offsetEnd'] = $endLine;
            return $header;
        }
     
        /**
         * Convert array to Xml
         * @param unknown $soapRequest
         * @param unknown $soapRequestXml
         */
        function array_to_xml($soapRequest, $soapRequestXml)
        {
            foreach ($soapRequest as $key => $value) {
                if (is_array($value)) {
                    if (!is_numeric($key)) {
                        $subnode = $soapRequestXml->addChild("$key");
                        array_to_xml($value, $subnode);
                    } else {
                        $subnode = $soapRequestXml->addChild("item$key");
                        array_to_xml($value, $subnode);
                    }
                } else {
                    $soapRequestXml->addChild("$key", htmlspecialchars("$value"));
                }
            }
        }
    }
    EDIT :

    En fait c'est bon, mes modifications n'étais pas prises en compte.
    Mais maintenant j'ai cette erreur là :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    Parse error: syntax error, unexpected 'function__construct' (T_STRING), expecting variable (T_VARIABLE) in C:\wamp64\www\TestEtiquette\php\etiquette.php on line 110
    J'ai l'impression que je ne m'en sortirai jamais... Et encore là c'est pas du tout dynamique, les données sont brutes, après il faudra que j'arrive à adapter ça à Dolibarr... Je fais un stage de première année sans tuteur, personne ne peux m'aider et on me demande quelque chose qui dépasse mes compétences... Alors certes, si j'y arrive, je monterai en compétences mais pour le moment, c'est vraiment la loose...

Discussions similaires

  1. [Débutant] Error using ==> mpower que je n'arrive pas à résoudre
    Par danaee dans le forum MATLAB
    Réponses: 2
    Dernier message: 28/05/2010, 11h44
  2. Petit bug IE // FF que je n'arrive pas à résoudre
    Par Denti-fritz dans le forum Mise en page CSS
    Réponses: 2
    Dernier message: 04/05/2008, 23h34
  3. Réponses: 4
    Dernier message: 14/09/2007, 17h14
  4. Réponses: 7
    Dernier message: 07/01/2007, 12h16
  5. problème que je n'arrive pas à résoudre de façon récursive
    Par miam dans le forum Algorithmes et structures de données
    Réponses: 9
    Dernier message: 31/07/2004, 11h21

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo