用户注册



邮箱:

密码:

用户登录


邮箱:

密码:
记住登录一个月忘记密码?

发表随想


还能输入:200字
云代码 - php代码库

利用CRUL访问soap服务器并自动将XML转换为数组,带调式日志功能

2014-06-11 作者: 青剑举报

[php]代码库

<?php

class oxylaneSoap
{

    var $gwUrl = 'http://preprodid.oxylane.com/wsdispatcher/wsgiftcard.ws';//网关地址
	var $CFG=array(("LOGIN","KEY","LOGIN","WSGiftCard","GIFTCA","2.1.0","CASH");
	var $debug = false;
	var $logdir = '';
	public function soapService($body){
	   $xml=$this->xml($body);
	   if($this->debug) echo __FILE__.':'.__LINE__.' '.__FUNCTION__.' '.date('Y-m-d H:i:s').'<br>';
	   if($this->debug) echo '<textarea cols="50" style="width:100%">'.htmlspecialchars($xml).'</textarea>';
	   
       $result = $this->vcurlsoap($this->gwUrl,$xml,'');
      // $result = $this->req($this->gwUrl, $data, $func);
	   
	   if($this->debug) echo __FILE__.':'.__LINE__.' '.__FUNCTION__.' '.date('Y-m-d H:i:s').'<br>';
	   if($this->debug)
		echo '<textarea cols="50" style="width:100%">'.htmlspecialchars($result).'</textarea><hr>';
		
	 	if($this->logdir){
		   $logfile = $this->logdir.'/log_api_'.date('Y-m-d_H_i_s').'_post.xml';
		   file_put_contents($logfile,$xml);
		   file_put_contents(str_replace('_post','_result',$logfile),$result);
		}
	   return $this->xml2array($result);
    }
	
	public function xml($body){
		$SIGNATURE=$this->ComputeSignature($this->CFG);
		$xml ='<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" 
xmlns:com="com.decathlon.wsdispatch.uddi" 
xmlns:com1="com.decathlon.wsdispatch.security" 
xmlns:urn="urn:giftcard.decathlon.com"
xmlns:data="http://data.webservices.giftcard.decathlon.com">
   <soapenv:Header>
      <com1:LOGIN>'.$this->CFG[0].'</com1:LOGIN>
      <com1:SIGNATURE>'.$SIGNATURE.'</com1:SIGNATURE>
      <com:CLIENT_APP>'.$this->CFG[2].'</com:CLIENT_APP>
      <com:WS_NAME>'.$this->CFG[3].'</com:WS_NAME>
      <com:WS_APP>'.$this->CFG[4].'</com:WS_APP>
      <com:WS_VERSION>'.$this->CFG[5].'</com:WS_VERSION>
      <com:WS_DOMAIN>'.$this->CFG[6].'</com:WS_DOMAIN>

   </soapenv:Header>
   <soapenv:Body>
      '.$body.'
   </soapenv:Body>
</soapenv:Envelope>';
		return $xml;
	}
	
	public function vcurl($url, $post = '', $cookie = '', $cookiejar = '', $referer = ''){ 
  $tmpInfo = ''; 
  //用来存放cookie的文件
  $cookiepath = getcwd().'./'.$cookiejar; 
  //初始化curl
  $curl = curl_init(); 
  //设定目标网址
  curl_setopt($curl, CURLOPT_URL, $url); 
  //使用目前所用的浏览器代理
  curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); 
  //curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");		 
  //如果有Ref参数,则设置Referer头,否则自动设置Referer头
  if($referer) { 
    curl_setopt($curl, CURLOPT_REFERER, $referer); 
  } else { 
    curl_setopt($curl, CURLOPT_AUTOREFERER, 1); 
  } 
  //如果有post数据参数,则方法为POST,并且设置数据,否则为GET
  if($post) { 
    //发送一个常规的POST请求,默认类型为:application/x-www-form-urlencoded,表单提交
    curl_setopt($curl, CURLOPT_POST, 1); 
    curl_setopt($curl, CURLOPT_POSTFIELDS, $post); 
  } 
  //如果有cookie参数,则设置
  if($cookie) { 
    curl_setopt($curl, CURLOPT_COOKIE, $cookie); 
  } 
  //如果有cookie文件参数,则设置存取Cookie文件名
  if($cookiejar) { 
  curl_setopt($curl, CURLOPT_COOKIEJAR, $cookiepath); 
  curl_setopt($curl, CURLOPT_COOKIEFILE, $cookiepath); 
  } 
  //如果是302转移,则返回转移后的网址及内容
  curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); 
  //设置执行的最大秒数
  curl_setopt($curl, CURLOPT_TIMEOUT, 100); 
  //返回内容中是否包含头信息
  curl_setopt($curl, CURLOPT_HEADER, 0); 
  //把返回的结果存在文件或者变量中,而不是直接显示在浏览器
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); 
  //执行函数后的返回结果
  $tmpInfo = curl_exec($curl); 
  //如果出错,显示错误信息
  if (curl_errno($curl)) { 
    $tmpInfo = '<pre><b>错误:</b><br />'.curl_error($curl); 
  } 
  //关闭curl对象
  curl_close($curl);
  //返回结果
  return $tmpInfo; 
	} 
	
	public function vcurlsoap($url, $SoapRequest, $SoapAction) {
		$ch = curl_init (); //initiate the curl session
		curl_setopt ( $ch, CURLOPT_URL, $url ); //set to url to post to
		curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 ); // return data in a variable
		curl_setopt ( $ch, CURLOPT_HEADER, 0 );
		curl_setopt ( $ch, CURLOPT_POST, 1 );
		curl_setopt ( $ch, CURLOPT_POSTFIELDS, $SoapRequest ); // post the xml
		curl_setopt ( $ch, CURLOPT_TIMEOUT, 200 ); // set timeout in seconds
		curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, 0 );
		$header = array ("Content-Type: text/xml" );
		$header [] = "Content-Length: ".strlen($SoapRequest);
		
		if (! is_null ( $SoapAction ))
			$header [] = 'SOAPAction: "' . $SoapAction . '"';
		curl_setopt ( $ch, CURLOPT_HTTPHEADER, $header );
		
		$xmlResponse = curl_exec ( $ch );
		curl_close ( $ch );
		
		return $xmlResponse;
	}
	
 	/**
	 * xml转换成数组
	 * @param type $contents
	 * @param type $get_attributes
	 * @param type $priority
	 * @return type 
	 */
	public function xml2array($contents, $get_attributes=1, $priority = 'tag') {
		if (!$contents)
			return array();
	
		if (!function_exists('xml_parser_create')) {
			//print "'xml_parser_create()' function not found!"; 
			return array();
		}
	
		//Get the XML parser of PHP - PHP must have this module for the parser to work 
		$parser = xml_parser_create('');
		xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8"); # http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss 
		xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
		xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
		xml_parse_into_struct($parser, trim($contents), $xml_values);
		xml_parser_free($parser);
	
		if (!$xml_values)
			return; //Hmm 
	
	
	
	
	
			
	//Initializations 
		$xml_array = array();
		$parents = array();
		$opened_tags = array();
		$arr = array();
	
		$current = &$xml_array; //Refference 
		//Go through the tags. 
		$repeated_tag_index = array(); //Multiple tags with same name will be turned into an array 
		foreach ($xml_values as $data) {
			unset($attributes, $value); //Remove existing values, or there will be trouble 
			//This command will extract these variables into the foreach scope 
			// tag(string), type(string), level(int), attributes(array). 
			extract($data); //We could use the array by itself, but this cooler. 
	
			$result = array();
			$attributes_data = array();
	
			if (isset($value)) {
				if ($priority == 'tag')
					$result = $value;
				else
					$result['value'] = $value; //Put the value in a assoc array if we are in the 'Attribute' mode 
			}
	
			//Set the attributes too. 
			if (isset($attributes) and $get_attributes) {
				foreach ($attributes as $attr => $val) {
					if ($priority == 'tag')
						$attributes_data[$attr] = $val;
					else
						$result['attr'][$attr] = $val; //Set all the attributes in a array called 'attr' 
				}
			}
	
			//See tag status and do the needed. 
			if ($type == "open") {//The starting of the tag '<tag>' 
				$parent[$level - 1] = &$current;
				if (!is_array($current) or (!in_array($tag, array_keys($current)))) { //Insert New tag 
					$current[$tag] = $result;
					if ($attributes_data)
						$current[$tag . '_attr'] = $attributes_data;
					$repeated_tag_index[$tag . '_' . $level] = 1;
	
					$current = &$current[$tag];
				} else { //There was another element with the same tag name 
					if (isset($current[$tag][0])) {//If there is a 0th element it is already an array 
						$current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
						$repeated_tag_index[$tag . '_' . $level]++;
					} else {//This section will make the value an array if multiple tags with the same name appear together 
						$current[$tag] = array($current[$tag], $result); //This will combine the existing item and the new item together to make an array 
						$repeated_tag_index[$tag . '_' . $level] = 2;
	
						if (isset($current[$tag . '_attr'])) { //The attribute of the last(0th) tag must be moved as well 
							$current[$tag]['0_attr'] = $current[$tag . '_attr'];
							unset($current[$tag . '_attr']);
						}
					}
					$last_item_index = $repeated_tag_index[$tag . '_' . $level] - 1;
					$current = &$current[$tag][$last_item_index];
				}
			} elseif ($type == "complete") { //Tags that ends in 1 line '<tag />' 
				//See if the key is already taken. 
				if (!isset($current[$tag])) { //New Key 
					$current[$tag] = $result;
					$repeated_tag_index[$tag . '_' . $level] = 1;
					if ($priority == 'tag' and $attributes_data)
						$current[$tag . '_attr'] = $attributes_data;
				} else { //If taken, put all things inside a list(array) 
					if (isset($current[$tag][0]) and is_array($current[$tag])) {//If it is already an array 
						// push the new element into that array. 
						$current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
	
						if ($priority == 'tag' and $get_attributes and $attributes_data) {
							$current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
						}
						$repeated_tag_index[$tag . '_' . $level]++;
					} else { //If it is not an array 
						$current[$tag] = array($current[$tag], $result); //Make it an array using using the existing value and the new value 
						$repeated_tag_index[$tag . '_' . $level] = 1;
						if ($priority == 'tag' and $get_attributes) {
							if (isset($current[$tag . '_attr'])) { //The attribute of the last(0th) tag must be moved as well 
								$current[$tag]['0_attr'] = $current[$tag . '_attr'];
								unset($current[$tag . '_attr']);
							}
	
							if ($attributes_data) {
								$current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
							}
						}
						$repeated_tag_index[$tag . '_' . $level]++; //0 and 1 index is already taken 
					}
				}
			} elseif ($type == 'close') { //End of tag '</tag>' 
				$current = &$parent[$level - 1];
			}
		}
	
		return($xml_array);
	}
	
	public function ComputeSignature($args)
    {
		//var_dump($args);
        $login =		$args[0]; // Login du compte WS Dispatcher fourni par support OxIDString  $key = 		$args[1]; // Clé du compte WSDispatcher
        $key   =        $args[1];
        $clientApp =	$args[2]; // Nom de l'application cliente déclaré dans LDAP partner puis géré dans PERMIT
        $wsName =		$args[3]; // WS Cible déclaré dans UDDI
        $wsApp =		(count($args) > 4)?$args[4]:"BUXY";	// l'application Serveur dans UDDI
        $wsVersion =	(count($args) > 5)?$args[5]:"1.0";	// version du WS dans UDDI
        $wsDomain =	    (count($args) > 6)?$args[6]:"CASH";	// domaine du WS dans UDDI
        $sb=array();
        $sb['login']    = $login;
        $sb['clientApp']= $clientApp;
        $sb['wsName']   = $wsName;
        $sb['wsApp']    = $wsApp;
        $sb['wsVersion']= $wsVersion;
        $sb['wsDomain'] = $wsDomain;
        $sb['key']      = $key;
        $sb['time']     = $this->getUTCTimeStamp();

		$str=implode("",$sb);
		$signature=md5($str);
//		echo("<br>LOGIN> .............. " . $login);
//		echo("<br>WSDISPATCHER_KEY> ... " . $key);
//		echo("<br>CLIENT_APP> ......... " . $clientApp);
//		echo("<br>WS_NAME> ............ " . $wsName);
//		echo("<br>WS_APP> ............. " . $wsApp);
//		echo("<br>WS_VERSION> ......... " . $wsVersion);
//		echo("<br>WS_DOMAIN> .......... " . $wsDomain);
//		echo("<br>-----------------------");
//		echo("<br>SIGNATURE> .......... " . $signature);
        return $signature;


    }
    public function getUTCTimeStamp()
    {
		//date_default_timezone_set('Asia/Shanghai');
		date_default_timezone_set('UTC');
		$NB_DAY_IN_YEAR = 365.25;
		$NB_MONTH_IN_YEAR = 12;
		$NB_HOUR_IN_DAY = 24;
		$NB_MINUTES_IN_HOUR = 60;
		$year = date('Y');
		$month = date('m');
		$day = date('d');
		$hour = date('H');
		$min = date('i');
		// Compute time stamp (minutes)
		$timestamp = $year * $NB_DAY_IN_YEAR * $NB_HOUR_IN_DAY * $NB_MINUTES_IN_HOUR
		+ $month * ($NB_DAY_IN_YEAR/$NB_MONTH_IN_YEAR) * $NB_HOUR_IN_DAY *
		$NB_MINUTES_IN_HOUR
		+ $day * $NB_HOUR_IN_DAY *$NB_MINUTES_IN_HOUR
		+ $hour * $NB_MINUTES_IN_HOUR
		+ $min;
		return $timestamp;

    }
	
	
	public function pingOperation($data=array('operation'=>'test')){
		$body = '<urn:pingOperation>
         <urn:operation>'.$data['operation'].'</urn:operation>
      </urn:pingOperation>';
		return $this->soapService($body);
	}
	public function getGiftCardInfo($data){
		$body = '<urn:getGiftCardInfo>
         <urn:voGiftCardInfoRequest>
            <data:cardNumber>'.$data['cardNumber'].'</data:cardNumber>
            <data:currency>'.$data['currency'].'</data:currency>
            <data:language>'.$data['language'].'</data:language>
            <data:merchantId>'.$data['merchantId'].'</data:merchantId>
            <data:subThirdNumber>'.$data['subThirdNumber'].'</data:subThirdNumber>
            <data:thirdNumber>'.$data['thirdNumber'].'</data:thirdNumber>
            <data:thirdTypeNumber>'.$data['thirdTypeNumber'].'</data:thirdTypeNumber>
            <data:eanCode>'.$data['eanCode'].'</data:eanCode>
         </urn:voGiftCardInfoRequest>
      </urn:getGiftCardInfo>';
		return $this->soapService($body);
	}
	public function getGiftcardHistory($data){
		$body = '<urn:getGiftcardHistory>
         <urn:voGiftCardHistoryRequest>
            <data:cardNumber>'.$data['cardNumber'].'</data:cardNumber>
            <data:currency>'.$data['currency'].'</data:currency>
            <data:language>'.$data['language'].'</data:language>
            <data:merchantId>'.$data['merchantId'].'</data:merchantId>
         </urn:voGiftCardHistoryRequest>
      </urn:getGiftcardHistory>';
		return $this->soapService($body);
	}
	public function getInfoPromo($data){
		$body='<urn:getInfoPromo>
         <urn:infoPromoRequest>
            <data:amountMax>?</data:amountMax>
            <data:amountMin>?</data:amountMin>
            <data:cardType>?</data:cardType>
            <data:code>?</data:code>
            <data:consortiumId>?</data:consortiumId>
            <data:consortiumName>?</data:consortiumName>
            <data:creationDate>?</data:creationDate>
            <data:currencyCode>?</data:currencyCode>
            <data:email1>?</data:email1>
            <data:email2>?</data:email2>
            <data:expirationDate>?</data:expirationDate>
            <data:itemCode>?</data:itemCode>
            <data:maxActivationsNumber>?</data:maxActivationsNumber>
            <data:name>?</data:name>
            <data:supportPaiementCode>?</data:supportPaiementCode>
            <data:useTank>?</data:useTank>
            <data:validityPeriod>?</data:validityPeriod>
         </urn:infoPromoRequest>
      </urn:getInfoPromo>';
		return $this->soapService($body);
	}
	public function getBatchStatus($data){
		$body='<urn:getBatchStatus>
         <urn:batchStatus>
            <data:requestNumber>?</data:requestNumber>
            <data:merchantId>?</data:merchantId>
            <data:merchantType>?</data:merchantType>
            <data:requestCode>?</data:requestCode>
            <data:requestDate>?</data:requestDate>
            <data:appCode>?</data:appCode>
            <data:login>?</data:login>
            <data:answerDate>?</data:answerDate>
            <data:sendingDate>?</data:sendingDate>
            <data:reference>?</data:reference>
            <data:freeLabelRefer>?</data:freeLabelRefer>
            <data:batchStatus>?</data:batchStatus>
            <data:batchType>?</data:batchType>
            <data:batchStatusDetails>
               <!--Zero or more repetitions:-->
               <urn:item>
                  <data:requestNumber>?</data:requestNumber>
                  <data:cardNumber>?</data:cardNumber>
                  <data:responseCode>?</data:responseCode>
               </urn:item>
            </data:batchStatusDetails>
         </urn:batchStatus>
      </urn:getBatchStatus>';
		return $this->soapService($body);
	}
	public function requestBatch($data){
		$body='';
		return $this->soapService($body);
	}
	public function actionOnGiftCard($data){
		$body='
      <urn:actionOnGiftCard>
         <urn:actionOnGiftCard>
            <data:amount>1500</data:amount>
            <data:cardNumber>7777005561694543</data:cardNumber>
            <data:cardType>36</data:cardType>
            <data:cashierNumber>321</data:cashierNumber>
            <data:currency>978</data:currency>
            <data:language>FR</data:language>
            <data:merchantId>97140000001</data:merchantId>
            <data:requestCode>0802</data:requestCode>
            <data:subThirdNumber>118</data:subThirdNumber>
            <data:thirdNumber>118</data:thirdNumber>
            <data:thirdTypeNumber>7</data:thirdTypeNumber>
            <data:tillNumber>5</data:tillNumber>
            <data:transactionNumber>12</data:transactionNumber>
         </urn:actionOnGiftCard>
      </urn:actionOnGiftCard>';
		return $this->soapService($body);

	}
	
	public function requestGiftCards($data){
		$body='<urn:requestGiftCards>
         <urn:requestGiftCards>
            <data:author>?</data:author>
            <data:freeLabelReference>?</data:freeLabelReference>
            <data:promoCode>?</data:promoCode>
            <data:quantity>?</data:quantity>
            <data:reference>?</data:reference>
         </urn:requestGiftCards>
      </urn:requestGiftCards>';
		return $this->soapService($body);

	}
	//....其他方法
	

}


$oxylaneSoap = new oxylaneSoap();
$oxylaneSoap->gwUrl  = 'http://preprodid.oxylane.com/wsdispatcher/wsgiftcard.ws';
$oxylaneSoap->CFG    = array("LOGIN","KEY","LOGIN","WSGiftCard","GIFTCA","2.1.0","CASH");
$oxylaneSoap->debug  = true;
$oxylaneSoap->logdir = dirname(__FILE__).'/log/';

//PING操作
$result = $oxylaneSoap->pingOperation();
echo '<br>Result:<textarea style="width:100%;height:300px">';
print_r($result);
echo '</textarea>';


//获取cardInfo
$data=array(
'cardNumber'=>'7777017217539199',
'currency'=>'978',
'language'=>'FR',
'merchantId'=>'97093500007',
'subThirdNumber'=>'118',
'thirdNumber'=>'118',
'thirdTypeNumber'=>'7',
'eanCode'=>'',
);
$result = $oxylaneSoap->getGiftCardInfo($data);
echo '<br>Result:<textarea style="width:100%;height:300px">';
print_r($result);
echo '</textarea>';

//获取GiftcardHistory
$data=array(
'cardNumber'=>'7777017217539199',
'currency'=>'978',
'language'=>'FR',
'merchantId'=>'97093500007',
);
$result = $oxylaneSoap->getGiftcardHistory($data);
echo '<br>Result:<textarea style="width:100%;height:300px">';
print_r($result);
echo '</textarea>';

[代码运行效果截图]


利用CRUL访问soap服务器并自动将XML转换为数组,带调式日志功能


网友评论    (发表评论)


发表评论:

评论须知:

  • 1、评论每次加2分,每天上限为30;
  • 2、请文明用语,共同创建干净的技术交流环境;
  • 3、若被发现提交非法信息,评论将会被删除,并且给予扣分处理,严重者给予封号处理;
  • 4、请勿发布广告信息或其他无关评论,否则将会删除评论并扣分,严重者给予封号处理。


扫码下载

加载中,请稍后...

输入口令后可复制整站源码

加载中,请稍后...