e邮宝 php demo api 接口解决 - 通过订单信息获取货运号

5 篇文章 0 订阅

注:本文解决的是线下的e邮宝

1.首先生成xml,生成xml可以借助 Array2XML这个类来实现转换

<?php
/**
 * Array2XML: A class to convert array in PHP to XML
 * It also takes into account attributes names unlike SimpleXML in PHP
 * It returns the XML in form of DOMDocument class for further manipulation.
 * It throws exception if the tag name or attribute name has illegal chars.
 *
 * Author : Lalit Patel
 * Website: http://www.lalit.org/lab/convert-php-array-to-xml-with-attributes
 * License: Apache License 2.0
 *          http://www.apache.org/licenses/LICENSE-2.0
 * Version: 0.1 (10 July 2011)
 * Version: 0.2 (16 August 2011)
 *          - replaced htmlentities() with htmlspecialchars() (Thanks to Liel Dulev)
 *          - fixed a edge case where root node has a false/null/0 value. (Thanks to Liel Dulev)
 * Version: 0.3 (22 August 2011)
 *          - fixed tag sanitize regex which didn't allow tagnames with single character.
 * Version: 0.4 (18 September 2011)
 *          - Added support for CDATA section using @cdata instead of @value.
 * Version: 0.5 (07 December 2011)
 *          - Changed logic to check numeric array indices not starting from 0.
 * Version: 0.6 (04 March 2012)
 *          - Code now doesn't @cdata to be placed in an empty array
 * Version: 0.7 (24 March 2012)
 *          - Reverted to version 0.5
 * Version: 0.8 (02 May 2012)
 *          - Removed htmlspecialchars() before adding to text node or attributes.
 *
 * Usage:
 *       $xml = Array2XML::createXML('root_node_name', $php_array);
 *       echo $xml->saveXML();
 */
namespace backend\models\core;
use Yii; 

class Array2XML {

    private static $xml = null;
	private static $encoding = 'UTF-8';

    /**
     * Initialize the root XML node [optional]
     * @param $version
     * @param $encoding
     * @param $format_output
     */
    public static function init($version = '1.0', $encoding = 'UTF-8', $format_output = true) {
        self::$xml = new \DomDocument($version, $encoding);
        self::$xml->formatOutput = $format_output;
		self::$encoding = $encoding;
    }

    /**
     * Convert an Array to XML
     * @param string $node_name - name of the root node to be converted
     * @param array $arr - aray to be converterd
     * @return DomDocument
     */
    public static function &createXML($node_name, $arr=array()) {
        $xml = self::getXMLRoot();
        $xml->appendChild(self::convert($node_name, $arr));

        self::$xml = null;    // clear the xml node in the class for 2nd time use.
        return $xml;
    }

    /**
     * Convert an Array to XML
     * @param string $node_name - name of the root node to be converted
     * @param array $arr - aray to be converterd
     * @return DOMNode
     */
    private static function &convert($node_name, $arr=array()) {

        //print_arr($node_name);
        $xml = self::getXMLRoot();
        $node = $xml->createElement($node_name);

        if(is_array($arr)){
            // get the attributes first.;
            if(isset($arr['@attributes'])) {
                foreach($arr['@attributes'] as $key => $value) {
                    if(!self::isValidTagName($key)) {
                        throw new \Exception('[Array2XML] Illegal character in attribute name. attribute: '.$key.' in node: '.$node_name);
                    }
                    $node->setAttribute($key, self::bool2str($value));
                }
                unset($arr['@attributes']); //remove the key from the array once done.
            }

            // check if it has a value stored in @value, if yes store the value and return
            // else check if its directly stored as string
            if(isset($arr['@value'])) {
                $node->appendChild($xml->createTextNode(self::bool2str($arr['@value'])));
                unset($arr['@value']);    //remove the key from the array once done.
                //return from recursion, as a note with value cannot have child nodes.
                return $node;
            } else if(isset($arr['@cdata'])) {
                $node->appendChild($xml->createCDATASection(self::bool2str($arr['@cdata'])));
                unset($arr['@cdata']);    //remove the key from the array once done.
                //return from recursion, as a note with cdata cannot have child nodes.
                return $node;
            }
        }

        //create subnodes using recursion
        if(is_array($arr)){
            // recurse to get the node for that key
            foreach($arr as $key=>$value){
                if(!self::isValidTagName($key)) {
                    throw new \Exception('[Array2XML] Illegal character in tag name. tag: '.$key.' in node: '.$node_name);
                }
                if(is_array($value) && is_numeric(key($value))) {
                    // MORE THAN ONE NODE OF ITS KIND;
                    // if the new array is numeric index, means it is array of nodes of the same kind
                    // it should follow the parent key name
                    foreach($value as $k=>$v){
                        $node->appendChild(self::convert($key, $v));
                    }
                } else {
                    // ONLY ONE NODE OF ITS KIND
                    $node->appendChild(self::convert($key, $value));
                }
                unset($arr[$key]); //remove the key from the array once done.
            }
        }

        // after we are done with all the keys in the array (if it is one)
        // we check if it has any text value, if yes, append it.
        if(!is_array($arr)) {
            $node->appendChild($xml->createTextNode(self::bool2str($arr)));
        }

        return $node;
    }

    /*
     * Get the root XML node, if there isn't one, create it.
     */
    private static function getXMLRoot(){
        if(empty(self::$xml)) {
            self::init();
        }
        return self::$xml;
    }

    /*
     * Get string representation of boolean value
     */
    private static function bool2str($v){
        //convert boolean to text value.
        $v = $v === true ? 'true' : $v;
        $v = $v === false ? 'false' : $v;
        return $v;
    }

    /*
     * Check if the tag name or attribute name contains illegal characters
     * Ref: http://www.w3.org/TR/xml/#sec-common-syn
     */
    private static function isValidTagName($tag){
        $pattern = '/^[a-z_]+[a-z0-9\:\-\.\_]*[^:]*$/i';
        return preg_match($pattern, $tag, $matches) && $matches[0] == $tag;
    }
}
?>

先通过order生成数组,然后通过数组生成xml文件

 public static function generalEyoubaoGetXmlByOrder($order){
        $increment_id = $order['increment_id'];

        $order_id = $order['order_id'];
        $itmes = Salesorderitem::find()->asArray()
            ->where(['order_id'=>$order_id])
            ->all()
        ;
        $Cargo = [];
        if(is_array($itmes) && !empty($itmes)){
            foreach($itmes as $item){
                $Cargo[] = [

                       'cnname'=>'衣服',
                       'enname'=>substr($item['name'],0,49),
                       'count'=>$item['qty'],
                       'weight'=>$item['weight']

                ];
            }
        }

        $xmlArray = array(

            "@attributes" =>[
                "xmlns:xsi"=>"http://www.w3.org/2001/XMLSchema",
            ],
            "order" => [
                'orderid'=>$increment_id,
                'volweight'=>0.3,
                'untread'=>'Abandoned',
                'clcttype'=>1,
                'receiver'=>[
                    'name'=>$order['customer_firstname'].' '.$order['customer_lastname'],
                    'postcode'=>$order['customer_address_zip'],
                    'mobile'=>$order['customer_telephone'],
                    'county'=>$order['customer_address_country'],
                    'province'=>$order['customer_address_state'],
                    'city'=>$order['customer_address_city'],
                    'street'=>$order['customer_address_street1'].' '.$order['customer_address_street2'],
                ],
                'itmes'=>[
                    'item'=>$Cargo
                ]

            ]

        );
        $xml = Array2XML::createXML('orders', $xmlArray);
        return $xml->saveXML();

3 通过xml 访问接口,返回货运号:

public static function EncryptionData($xmlArray,$checkword=''){
        echo $xmlArray;
        if(!$checkword){
            $checkword = self::CHECK_PASS;
        }
        $headers = array(
            "Content-type: text/xml;charset=\"utf-8\"",
            "Accept: text/xml",
            "Cache-Control: no-cache",
            "Pragma: no-cache",
            "Content-length: ".strlen($xmlArray),
            "version:international_eub_us_1.1",
            "authenticate:您的验证码",
        );
       // echo $xmlArray;exit;
        $url = "http://www.ems.com.cn/partner/api/public/p/order/";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xmlArray);

        $data = curl_exec($ch);
        echo $data;exit;
       // $array = XML2Array::createArray($result);
        //return $array;
    }

即可得到返回xml,然后通过xml2array返回数组

xml2array的类如下:

<?php  
# http://justcoding.iteye.com/blog/1666217
/** 
 * XML2Array: A class to convert XML to array in PHP 
 * It returns the array which can be converted back to XML using the Array2XML script 
 * It takes an XML string or a DOMDocument object as an input. 
 * 
 * See Array2XML: http://www.lalit.org/lab/convert-php-array-to-xml-with-attributes 
 * 
 * Author : Lalit Patel 
 * Website: http://www.lalit.org/lab/convert-xml-to-array-in-php-xml2array 
 * License: Apache License 2.0 
 *          http://www.apache.org/licenses/LICENSE-2.0 
 * Version: 0.1 (07 Dec 2011) 
 * Version: 0.2 (04 Mar 2012) 
 *          Fixed typo 'DomDocument' to 'DOMDocument' 
 * 
 * Usage: 
 *       $array = XML2Array::createArray($xml); 
 */ 
namespace backend\models\core;
use Yii; 
  
class XML2Array {  
  
    private static $xml = null;  
    private static $encoding = 'UTF-8';  
  
    /** 
     * Initialize the root XML node [optional] 
     * @param $version 
     * @param $encoding 
     * @param $format_output 
     */  
    public static function init($version = '1.0', $encoding = 'UTF-8', $format_output = true) {  
        self::$xml = new \DOMDocument($version, $encoding);  
        self::$xml->formatOutput = $format_output;  
        self::$encoding = $encoding;  
    }  
  
    /** 
     * Convert an XML to Array 
     * @param string $node_name - name of the root node to be converted 
     * @param array $arr - aray to be converterd 
     * @return DOMDocument 
     */  
    public static function &createArray($input_xml) {  
        $xml = self::getXMLRoot();  
        if(is_string($input_xml)) {  
            $parsed = $xml->loadXML($input_xml);  
            if(!$parsed) {  
                throw new \Exception('[XML2Array] Error parsing the XML string.');  
            }  
        } else {  
            if(get_class($input_xml) != 'DOMDocument') {  
                throw new \Exception('[XML2Array] The input XML object should be of type: DOMDocument.');  
            }  
            $xml = self::$xml = $input_xml;  
        }  
        $array[$xml->documentElement->tagName] = self::convert($xml->documentElement);  
        self::$xml = null;    // clear the xml node in the class for 2nd time use.  
        return $array;  
    }  
  
    /** 
     * Convert an Array to XML 
     * @param mixed $node - XML as a string or as an object of DOMDocument 
     * @return mixed 
     */  
    private static function &convert($node) {  
        $output = array();  
  
        switch ($node->nodeType) {  
            case XML_CDATA_SECTION_NODE:  
                $output['@cdata'] = trim($node->textContent);  
                break;  
  
            case XML_TEXT_NODE:  
                $output = trim($node->textContent);  
                break;  
  
            case XML_ELEMENT_NODE:  
  
                // for each child node, call the covert function recursively  
                for ($i=0, $m=$node->childNodes->length; $i<$m; $i++) {  
                    $child = $node->childNodes->item($i);  
                    $v = self::convert($child);  
                    if(isset($child->tagName)) {  
                        $t = $child->tagName;  
  
                        // assume more nodes of same kind are coming  
                        if(!isset($output[$t])) {  
                            $output[$t] = array();  
                        }  
                        $output[$t][] = $v;  
                    } else {  
                        //check if it is not an empty text node  
                        if($v !== '') {  
                            $output = $v;  
                        }  
                    }  
                }  
  
                if(is_array($output)) {  
                    // if only one node of its kind, assign it directly instead if array($value);  
                    foreach ($output as $t => $v) {  
                        if(is_array($v) && count($v)==1) {  
                            $output[$t] = $v[0];  
                        }  
                    }  
                    if(empty($output)) {  
                        //for empty nodes  
                        $output = '';  
                    }  
                }  
  
                // loop through the attributes and collect them  
                if($node->attributes->length) {  
                    $a = array();  
                    foreach($node->attributes as $attrName => $attrNode) {  
                        $a[$attrName] = (string) $attrNode->value;  
                    }  
                    // if its an leaf node, store the value in @value instead of directly storing it.  
                    if(!is_array($output)) {  
                        $output = array('@value' => $output);  
                    }  
                    $output['@attributes'] = $a;  
                }  
                break;  
        }  
        return $output;  
    }  
  
    /* 
     * Get the root XML node, if there isn't one, create it. 
     */  
    private static function getXMLRoot(){  
        if(empty(self::$xml)) {  
            self::init();  
        }  
        return self::$xml;  
    }  
}  
?>  



  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值