magento shell 脚本 通过api获取paypal的订单状态,同步到magento网站的订单,自动纠正不准确的订单状态

<?php
/**
 * Magento
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Open Software License (OSL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/osl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magentocommerce.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magentocommerce.com for more information.
 *
 * @category    Mage
 * @package     Mage_Shell
 * @copyright   Copyright (c) 2009 Irubin Consulting Inc. DBA Varien (http://www.varien.com)
 * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
 */

require_once 'abstract.php';

/**
 * Magento Compiler Shell Script
 *
 * @category    Mage
 * @package     Mage_Shell
 * @author      Magento Core Team <core@magentocommerce.com>
 */
 
class Mage_Shell_SyncPaypalOrderStatus extends Mage_Shell_Abstract
{
    const PAGE_SIZE = 50;
    
    protected function _construct(){
       
    }
    public function run()
    {
        
         if (isset($this->_args['syncpaypalorderstatus'])) {
			//echo $this->getPaypalTimeFormat(Mage::getModel("core/date")->date("Y-m-d H:i:s"));
			//return;
            $this->syncPaypalOrderStatus();
            return;
         
		}else{
			
			return;
		}
        
    }
	public function getPaypalTimeFormat($time){
		$time1 = trim(substr($time,0,10));
		$time2 = trim(substr($time,11));
		
		return $time1."T".$time2."Z";
		
	}
	public function getLastTime($time,$add){
		$b = date('Y-m-d H:i:s',strtotime($add,strtotime($time)));
		return $b;
	}
	public function syncPaypalOrderStatus(){
		$STARTDATE = "";
		$ENDDATE = "";
		//得到开始时间和结束时间(paypal)
		$model_count = Mage::getModel("syncpaypalorderstatus/syncpaypalorderstatus")->getCollection()->count();
		$syncpaypalorderstatus = Mage::getModel("syncpaypalorderstatus/syncpaypalorderstatus");
		$now_date = Mage::getModel("core/date")->date("Y-m-d H:i:s");
		if($model_count<1){
			//在同步记录表中没有数据,则添加初始值。
			$STARTDATE_d = $this->getLastTime($now_date,"+5 hours");
			$ENDDATE_d = $this->getLastTime($STARTDATE_d,"+20 minute");
			$ENDDATE_E = $this->getLastTime($STARTDATE_d,"+10 minute");
			$STARTDATE = $this->getPaypalTimeFormat($STARTDATE_d);
			$ENDDATE = $this->getPaypalTimeFormat($ENDDATE_d);
			$syncpaypalorderstatus->setProcessTime($now_date)
						->setBeginTime($STARTDATE_d)
						->setEndDate($ENDDATE_E)
						->setStatus(1)
						->save()
						;
		}else{
		//在同步表中有同步记录,则获取最后一条记录
			$model_coll = Mage::getModel("syncpaypalorderstatus/syncpaypalorderstatus")->getCollection()->setOrder("id","DESC");
			$model  = $model_coll->getFirstItem();
			$status = $model->getStatus();
			//如果状态是完成,则进行抓取下一个十分钟的数据。
			if($status+0 == 2){
				$STARTDATE_d = $model->getEndDate();
				$ENDDATE_d = $this->getLastTime($STARTDATE_d,"+20 minutes");
				$ENDDATE_E = $this->getLastTime($STARTDATE_d,"+10 minutes");
				$STARTDATE = $this->getPaypalTimeFormat($STARTDATE_d);
				$ENDDATE = $this->getPaypalTimeFormat($ENDDATE_d);
				$syncpaypalorderstatus->setProcessTime($now_date)
						->setBeginTime($STARTDATE_d)
						->setEndDate($ENDDATE_E)
						->setStatus(1)
						->save()
						;
			}else{
			//如果上次抓取失败,则继续抓取上次的记录。
				$ENDDATE_d = $model->getBeginTime();
				$ENDDATE_d = $model->getEndDate();
				$STARTDATE = $this->getPaypalTimeFormat($STARTDATE_d);
				$ENDDATE = $this->getPaypalTimeFormat($ENDDATE_d);
				$syncpaypalorderstatus = $model;
			}
			
		}
		
		//得到订单列表
		$TranslateList = $this->getTranslateList($STARTDATE,$ENDDATE);
		echo "*******************************\n";
		echo $STARTDATE."\n";
		echo $ENDDATE."\n";
		//var_dump($TranslateList);
		if($TranslateList){
			//得到只有交易号的数组
			$TranslateArray = $this->getTranslateArray($TranslateList);
		}
		var_dump($TranslateArray);
		$order_array = array();
		$i = 0;
		$increment_array = array();
		$i_arr = array();
		foreach($TranslateArray as $translate_id){
			$order_detial = $this->getjyinfo5($translate_id);
			$increment_id = $order_detial['INVNUM'];
			$payment_status = $order_detial['PAYMENTSTATUS'];
			//$order_array[$increment_id] = $payment_status;
			$i_arr[] = $increment_id;
			$order = Mage::getModel('sales/order')->loadByIncrementId(trim($increment_id));
			if($order->getId()){
				echo "increment_id:".$increment_id."\n";
				echo "old_statue:".$order->getState()."\n";
				$order->setState(Mage_Sales_Model_Order::STATE_PROCESSING, true)->save();
				echo "new_statue:".$order->getState()."\n";
				$increment_array[] = $increment_id;
			}
			
		}
		var_dump($i_arr);
		$increment_string = implode(",",$increment_array);
		$syncpaypalorderstatus->setStatus(2)->setIncrementIds($increment_string)->save();
		echo "$increment_string is complate\n";
		//$order->setState(Mage_Sales_Model_Order::STATE_COMPLETE, true)->save();
	
	}
	//返回所有的交易号数组。
	public function getTranslateArray($TranslateList){
		$TRANSACTIONID_ARRAY = array();
		foreach($TranslateList as $Translate_array){
			if(is_array($Translate_array)){
				for($i=0;$i<=99;$i++){
					$L_TRANSACTIONID = "L_TRANSACTIONID".$i;
					if(array_key_exists($L_TRANSACTIONID,$Translate_array)){
						$TRANSACTIONID_ARRAY[] = $Translate_array[$L_TRANSACTIONID];
						
					}
					
				}
			}
		}
		return $TRANSACTIONID_ARRAY;
	}
	
	//根据交易号得到订单的详细信息。
	public function getjyinfo5($transaction_serial_number) 
	{
		// Set request-specific fields.
		$transactionID = urlencode($transaction_serial_number);
		// Add request-specific fields to the request string.
		$nvpStr = "&TRANSACTIONID=$transactionID";
		// Execute the API operation; see the PPHttpPost function above.
		$httpParsedResponseAr = self::PPHttpPost5('GetTransactionDetails', $nvpStr);
		if("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) {
			//'GetTransactionDetails Completed Successfully: '.var_dump($httpParsedResponseAr, true);
			return $httpParsedResponseAr;   //返回些交易号所有信息,包括是否付款成功,客人地址等
		} else  {
			//'GetTransactionDetails failed: ' . var_dump($httpParsedResponseAr, true);
			return "NO GET";
		}

	}
	
	
	public function getTranslateList($STARTDATE,$ENDDATE,$trans_list_all_array = array()) 
	{
		// Set request-specific fields.
		//$transactionID = urlencode($transaction_serial_number);
		// Add request-specific fields to the request string.
		$nvpStr = "&STARTDATE=$STARTDATE&ENDDATE=$ENDDATE";
		// Execute the API operation; see the PPHttpPost function above.
		$httpParsedResponseAr = self::PPHttpPost5('TransactionSearch', $nvpStr);
		if("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) {
			//'GetTransactionDetails Completed Successfully: '.var_dump($httpParsedResponseAr, true);
			
			$trans_list_all_array[] = $httpParsedResponseAr;
			if(array_key_exists('L_SHORTMESSAGE0',$httpParsedResponseAr)){
				if($httpParsedResponseAr['L_SHORTMESSAGE0'] == "Search warning"){
					if(array_key_exists('L_TIMESTAMP99',$httpParsedResponseAr)){
						$end_TIMESTAMP = $httpParsedResponseAr['L_TIMESTAMP99'];
						$trans_list_array = $this->getTranslateList($STARTDATE,$end_TIMESTAMP,$trans_list_all_array);
						return $trans_list_array;
					}
				}
			}else{
				
				return $trans_list_all_array;   //返回些交易号所有信息,包括是否付款成功,客人地址等
			}
		} else  {
			//'GetTransactionDetails failed: ' . var_dump($httpParsedResponseAr, true);
			return "NO GET";
		}

	}
	
	
	
	
	function PPHttpPost5($methodName_, $nvpStr_,$i = 0) 
	{
		global $environment;
		$environment = 'live';
		// Set up your API credentials, PayPal end point, and API version.
		$API_UserName = urlencode('');  //这里你找授予权
		$API_Password = urlencode(''); //这里你找授予权
		$API_Signature = urlencode(''); //这里你找授予权
		$API_Endpoint = "https://api-3t.paypal.com/nvp";
		if("sandbox" === $environment || "beta-sandbox" === $environment) {
			$API_Endpoint = "https://api-3t.$environment.paypal.com/nvp";
		}
		$version = urlencode('51.0');
	
		// Set the curl parameters.
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $API_Endpoint);
		curl_setopt($ch, CURLOPT_VERBOSE, 1);
	
		// Turn off the server and peer verification (TrustManager Concept).
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
	
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_POST, 1);
	
		// Set the API operation, version, and API signature in the request.
		$nvpreq = "METHOD=$methodName_&VERSION=$version&PWD=$API_Password&USER=$API_UserName&SIGNATURE=$API_Signature$nvpStr_";
	
		// Set the request as a POST FIELD for curl.
		curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);
	
		// Get response from the server.
		$httpResponse = curl_exec($ch);
		
		
		if(!$httpResponse) {
			$i++;
			if($i>3){
				//获取三次失败后,则推出。
				exit("$methodName_ failed: ".curl_error($ch).'('.curl_errno($ch).')');
			}else{
				$httpResponse = $this->PPHttpPost5($methodName_, $nvpStr_,$i);
			}
		}else{
			//第一次获取数据失败,则再次获取。并返回、
			if($i>0){
				return $httpResponse;
			}
			
		}
		$httpResponseAr = explode("&", urldecode($httpResponse));
		
		$httpParsedResponseAr = array();
		foreach ($httpResponseAr as $i => $value) {
			$tmpAr = explode("=", $value);
			if(sizeof($tmpAr) > 1) {
				$httpParsedResponseAr[$tmpAr[0]] = $tmpAr[1];
			}
		}
	
		if((0 == sizeof($httpParsedResponseAr)) || !array_key_exists('ACK', $httpParsedResponseAr)) {
			exit("Invalid HTTP Response for POST request($nvpreq) to $API_Endpoint.");
		}
	
		return $httpParsedResponseAr;
	}
	
						   
}

$shell = new Mage_Shell_SyncPaypalOrderStatus();
$shell->run();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值