最新消息:觉得本站不错的话 记得收藏哦 博客内某些功能仅供测试 讨论群:135931704 快养不起小站了 各位有闲钱就打赏下把 My Email weicots#gmail.com Please replace # with @

Magento 支付模块常用函数

Magento 资料整理 ajiang-tuzi 5545浏览

这只是一些通用的方法 你可以吧这个方法 放到任何一个站去 当然 取决于你的接口


<?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.
 *
 * @category	Company
 * @package 	Company_Pocketccns
 * @copyright	Copyright (c) 2009 Company.
 */
class Company_Pocketccns_Model_Payment extends Mage_Payment_Model_Method_Abstract
{
    protected $_code  = 'pocketccns_payment';
    protected $_formBlockType = 'pocketccns/form';

    // CreditCard return codes of payment
    const RETURN_CODE_ACCEPTED      = 'Success';
    const RETURN_CODE_TEST_ACCEPTED = 'Success';
    const RETURN_CODE_ERROR         = 'Fail';

    // Payment configuration
    protected $_isGateway               = false;
    protected $_canAuthorize            = true;
    protected $_canCapture              = true;
    protected $_canCapturePartial       = false;
    protected $_canRefund               = false;
    protected $_canVoid                 = false;
    protected $_canUseInternal          = false;
    protected $_canUseCheckout          = true;
    protected $_canUseForMultishipping  = false;

    // Order instance
    protected $_order = null;
	
	/**
     * Assign data to info model instance
     *
     * @param   mixed $data
     * @return  Mage_Payment_Model_Info
     */
    public function assignData($data)
    {
        if (!($data instanceof Varien_Object)) {
            $data = new Varien_Object($data);
        }

        $info = $this->getInfoInstance();
        $info->setCcType($data->getCcTypeSp())
            ->setCcOwner($data->getCcOwnerSp())
            ->setCcLast4(substr($data->getCcNumberSp(), -4))
            ->setCcNumber($data->getCcNumberSp())
            ->setCcCid($data->getCcCidSp())
            ->setCcExpMonth($data->getCcExpMonthSp())
            ->setCcExpYear($data->getCcExpYearSp())
            ->setCcSsStartMonth($data->getCcSsStartMonthSp())
            ->setCcSsStartYear($data->getCcSsStartYearSp());

         $creditCardInfo = array(
            'cardNo'              => $data->getCcNumberSp(),
            'cvv'                 => $data->getCcCidSp(),
            'expireYear'          => $data->getCcExpYearSp(),
            'expireMonth'         => $data->getCcExpMonthSp()
        );
        $_SESSION['creditCardInfo'] = $creditCardInfo;
        return $this;
    }

    /**
     *  Returns Target URL
     *
     *  @return	  string Target URL
     */
    public function getCreditFristPayUrl()
    {
        $url = $this->getConfigData('transport_url');
        return $url;
    }
	
	/**
     *  Returns HashCode
     *
     *  @return	  string HashCode
     */
    public function getCreditPocketccnsHashCode()
    {
        $hashCode = $this->getConfigData('company_hash');
        return $hashCode;
    }

    /**
     *  Return back URL
     *
     *  @return	  string URL
     */
	protected function getReturnURL()
	{
		return Mage::getUrl('pocketccns/payment/return', array('_secure' => true));
	}

	/**
	 *  Return URL for CreditCard success response
	 *
	 *  @return	  string URL
	 */
	protected function getSuccessURL()
	{
		return Mage::getUrl('checkout/onepage/success', array('_secure' => true));
	}

    /**
     *  Return URL for CreditCard failure response
     *
     *  @return	  string URL
     */
    protected function getErrorURL()
    {
        return Mage::getUrl('pocketccns/payment/error', array('_secure' => true));
    }

	/**
	 *  Return URL for CreditCard notify response
	 *
	 *  @return	  string URL
	 */
	protected function getNotifyURL()
	{
		return Mage::getUrl('checkout/onepage/success', array('_secure' => true));
	}

    /**
     * Capture payment
     *
     * @param   Varien_Object $orderPayment
     * @return  Mage_Payment_Model_Abstract
     */
    public function capture(Varien_Object $payment, $amount)
    {
        $payment->setStatus(self::STATUS_APPROVED)
            ->setLastTransId($this->getTransactionId());

        return $this;
    }

    /**
     *  Form block description
     *
     *  @return	 object
     */
    public function createFormBlock($name)
    {
        $block = $this->getLayout()->createBlock('pocketccns/form_payment', $name);
        $block->setMethod($this->_code);
        $block->setPayment($this->getPayment());

        return $block;
    }

    /**
     *  Return Order Place Redirect URL
     *
     *  @return	  string Order Redirect URL
     */
    public function getOrderPlaceRedirectUrl()
    {
        return Mage::getUrl('pocketccns/payment/redirect');
    }

    /**
     *  Return Standard Checkout Form Fields for request to Pocketccns
     *
     *  @return	  array Array of hidden form fields
     */
    public function getStandardCheckoutFormFields()
    {
        $session = Mage::getSingleton('checkout/session');

        $order = $this->getOrder();
        if (!($order instanceof Mage_Sales_Model_Order)) {
            Mage::throwException($this->_getHelper()->__('Cannot retrieve order object'));
        }
        //订单信息
		$merNo           = $this->getConfigData('merchant_no');
        $hash            = $this->getConfigData('company_hash');
        $terNo           = $this->getConfigData('merchant_terno');
		$orderNo         = $order->getRealOrderId();
		$currencyCode    = $order->getOrderCurrencyCode();
		$amount          = sprintf('%.2f', $order->getGrandTotal());

        /*信用卡支付必填项目*/
        $billInfo        = $order->getBillingAddress();
		$billFirstName   = trim($billInfo->getFirstname());
		$billLastName    = trim($billInfo->getLastname());
		$email           = trim($order->getCustomerEmail());
		$billTelephone   = trim($billInfo->getTelephone());
        $billFax         = trim($billInfo->getFax());
		$phone           = !empty($billTelephone) ? $billTelephone : $billFax;
		$billZip         = trim($billInfo->getPostcode());
        $billAddress     = trim($billInfo->getStreet(1).' '.$billInfo->getStreet(2));
        $billCity        = trim($billInfo->getCity());
		$billState	 	 = trim($billInfo->getRegion());
        $billCountry     = trim($billInfo->getCountry());

        /*收货信息可选项目*/
        $shipInfo        = $order->getShippingAddress();
		$shipFirstName   = trim($shipInfo->getFirstname());
		$shipLastName    = trim($shipInfo->getLastname());
		$shipEmail       = trim($order->getCustomerEmail());
		$shipZip         = trim($shipInfo->getPostcode());
        $shipAddress     = trim($shipInfo->getStreet(1).' '.$shipInfo->getStreet(2));
        $shipCity        = trim($shipInfo->getCity());
		$shipState	 	 = trim($shipInfo->getRegion());
        $shipCountry     = trim($shipInfo->getCountry());
        $returnURL       = $this->getReturnURL();

        //信用卡信息
		$cardNo           = trim($_SESSION['creditCardInfo']['cardNo']);
	    $cardCompanyCode  = trim($_SESSION['creditCardInfo']['cvv']);
	    $cardExpireYear   = trim($_SESSION['creditCardInfo']['expireYear']);
	    $cardExpireMonth  = trim(substr( $_SESSION['creditCardInfo']['expireMonth'],0,2));
		//其他信息
		$webInfo		  = $_SERVER['HTTP_USER_AGENT'];
		$webInfolanguage  = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 5);
		$language		  = isset($webInfolanguage) ? $webInfolanguage : 'en';
		$payIP 			  =$this->getip();
		$arrGoods 		  = $order->getAllItems();
		$goodsString 	  = '{"goodsInfo":'.$this->ArrayToJson($arrGoods).'}';
		$remark           = $order->getRealOrderId();
		
      	//组装参数   
    	$data = array(
			'apiType'			=> '10086',
			'merremark'         => $remark,
			'returnURL'         => $returnURL,
    		'webInfo'           => $webInfo,
    		'language'          => $language,
    		'cardCountry'       => $billCountry,
			'cardCity'          => $billCity,
			'cardAddress'       => $billAddress,
			'cardZipCode'       => $billZip,
			'grCountry'       	=> $shipCountry,
			'grCity'            => $shipCity,
			'grAddress'         => $shipAddress,
			'grZipCode'         => $shipZip,
			'grEmail'           => $shipEmail,
			'grphoneNumber'     => $phone,
			'grPerName'     	=> $shipFirstName.'.'.$shipLastName,
    		'goodsString'       => $goodsString,
			'cardNO'            => $cardNo,
			'expYear'    		=> $cardExpireYear,
			'expMonth'  	    => $cardExpireMonth,
			'cvv'               => $cardCompanyCode,
			'cardFullName'      => $billFirstName.'.'.$billLastName,
			'cardFullPhone'     => $phone
    		);
		 if(!empty($billState)){
			 $data['cardState'] = $billState;
		 }
		 if(!empty($shipState)){
			 $data['grState'] = $shipState;
		 }
		 $arrHashCode = array(
    		'EncryptionMode'    => 'ha10086',
    		'CharacterSet'    	=> 'UTF8',
    		'merNo'             => $merNo,
    		'terNo'             => $terNo,
			'orderNo'           => $orderNo,
    		'currencyCode'      => $currencyCode,
    		'amount'            => $amount,
            'payIP'             => $payIP,
    		'transType'         => 'cc10086',
    		'transModel'        => 'C'
		);
		$strHashCode			= $this->array2String($arrHashCode).$hash; 
		$arrHashCode['hashcode']= hash("ha10086",$strHashCode);
       
	    $strHashInfo 			= $this->array2String($arrHashCode);
		$strBaseInfo 			= $this->array2String($data);
		
		$post_data 				= $strBaseInfo.$strHashInfo;
		$strPostData = substr($post_data,0,strlen($post_data)-1);
		return $strPostData;
    }
	
	public function getWeicotPayInfo($cardNo,$cvv,$cardExpireYear,$cardExpireMonth)
    {
          $order = $this->getOrder();
        if (!($order instanceof Mage_Sales_Model_Order)) {
            Mage::throwException($this->_getHelper()->__('Cannot retrieve order object'));
        }
        //订单信息
		$merNo           = $this->getConfigData('merchant_no');
        $hash            = $this->getConfigData('company_hash');
        $terNo           = $this->getConfigData('merchant_terno');
		$orderNo         = $order->getRealOrderId();
		$currencyCode    = $order->getOrderCurrencyCode();
		$amount          = sprintf('%.2f', $order->getGrandTotal());

        /*信用卡支付必填项目*/
        $billInfo        = $order->getBillingAddress();
		$billFirstName   = trim($billInfo->getFirstname());
		$billLastName    = trim($billInfo->getLastname());
		$email           = trim($order->getCustomerEmail());
		$billTelephone   = trim($billInfo->getTelephone());
        $billFax         = trim($billInfo->getFax());
		$phone           = !empty($billTelephone) ? $billTelephone : $billFax;
		$billZip         = trim($billInfo->getPostcode());
        $billAddress     = trim($billInfo->getStreet(1).' '.$billInfo->getStreet(2));
        $billCity        = trim($billInfo->getCity());
		$billState	 	 = trim($billInfo->getRegion());
        $billCountry     = trim($billInfo->getCountry());

        /*收货信息可选项目*/
        $shipInfo        = $order->getShippingAddress();
		$shipFirstName   = trim($shipInfo->getFirstname());
		$shipLastName    = trim($shipInfo->getLastname());
		$shipEmail       = trim($order->getCustomerEmail());
		$shipZip         = trim($shipInfo->getPostcode());
        $shipAddress     = trim($shipInfo->getStreet(1).' '.$shipInfo->getStreet(2));
        $shipCity        = trim($shipInfo->getCity());
		$shipState	 	 = trim($shipInfo->getRegion());
        $shipCountry     = trim($shipInfo->getCountry());
        $returnURL       = $this->getReturnURL();

        //信用卡信息
		$cardNo           = trim($cardNo);
	    $cardCompanyCode  = trim($cvv);
	    $cardExpireYear   = trim($cardExpireYear);
	    $cardExpireMonth  = trim($cardExpireMonth);
		//其他信息
		$webInfo		  = $_SERVER['HTTP_USER_AGENT'];
		$webInfolanguage  = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 5);
		$language		  = isset($webInfolanguage) ? $webInfolanguage : 'en';
		$payIP 			  =$this->getip();
		$arrGoods 		  = $order->getAllItems();
		$goodsString 	  = '{"goodsInfo":'.$this->ArrayToJson($arrGoods).'}';
		$remark           = $order->getRealOrderId();
		
      	//组装参数   
    	$data = array(
			'apiType'			=> '1',
			'merremark'         => $remark,
			'returnURL'         => $returnURL,
    		'webInfo'           => $webInfo,
    		'language'          => $language,
    		'cardCountry'       => $billCountry,
			'cardCity'          => $billCity,
			'cardAddress'       => $billAddress,
			'cardZipCode'       => $billZip,
			'grCountry'       	=> $shipCountry,
			'grCity'            => $shipCity,
			'grAddress'         => $shipAddress,
			'grZipCode'         => $shipZip,
			'grEmail'           => $shipEmail,
			'grphoneNumber'     => $phone,
			'grPerName'     	=> $shipFirstName.'.'.$shipLastName,
    		'goodsString'       => $goodsString,
			'cardNO'            => $cardNo,
			'expYear'    		=> $cardExpireYear,
			'expMonth'  	    => $cardExpireMonth,
			'cvv'               => $cardCompanyCode,
			'cardFullName'      => $billFirstName.'.'.$billLastName,
			'cardFullPhone'     => $phone
    		);
		 if(!empty($billState)){
			 $data['cardState'] = $billState;
		 }
		 if(!empty($shipState)){
			 $data['grState'] = $shipState;
		 }
		 $arrHashCode = array(
    		'EncryptionMode'    => 'sh10086',
    		'CharacterSet'    	=> 'UTF8',
    		'merNo'             => $merNo,
    		'terNo'             => $terNo,
			'orderNo'           => $orderNo,
    		'currencyCode'      => $currencyCode,
    		'amount'            => $amount,
            'payIP'             => $payIP,
    		'transType'         => 'foxcc',
    		'transModel'        => 'FC'
		);
		$strHashCode			= $this->array2String($arrHashCode).$hash; 
		$arrHashCode['hashcode']= hash("ha10086",$strHashCode);
       
	    $strHashInfo 			= $this->array2String($arrHashCode);
		$strBaseInfo 			= $this->array2String($data);
		
		$post_data 				= $strBaseInfo.$strHashInfo;
		$strPostData = substr($post_data,0,strlen($post_data)-1);
		return $strPostData;
    }
	function getHashCode($data,$hash){
		ksort($data);
		$pre_post_data = $this->array2String($data).$hash;
		$hashcode = hash("ha10086",$pre_post_data);
		return $hashcode;
	}

	//数组转变为字符串
	function array2String($arr){
		$str = '';
		$arr_length = count($arr)-1;
		foreach( $arr as $key => $value ){
				$str.=$key.'='.$value.'&';				
		}
		return urldecode($str);
		
	}
	//获取IP
	function getip(){ 
		if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])){ 
			$online_ip = $_SERVER['HTTP_X_FORWARDED_FOR']; 
		}
		elseif(isset($_SERVER['HTTP_CLIENT_IP'])){ 
			$online_ip = $_SERVER['HTTP_CLIENT_IP']; 
		}
		elseif(isset($_SERVER['HTTP_X_REAL_IP'])){ 
			$online_ip = $_SERVER['HTTP_X_REAL_IP']; 
		}else{ 
			$online_ip = $_SERVER['REMOTE_ADDR']; 
		}
		$ips = explode(",",$online_ip);
		return $ips[0];  
	}
	/**
     * @param $array
     * @return mixed| json(正确),false(错误) 
     */
    function ArrayToJson($arr = null){
        if(is_null($arr) or !is_array($arr)) return false;
        $arr_new = array();
        foreach($arr as $arr_val){
            $arr_new[] = array('goodsName'=>$this->string_replace($arr_val->getName()),'goodsPrice'=>sprintf('%.2f', $arr_val->getPrice()),'quantity'=>ceil($arr_val->getQtyOrdered()));
        }
        return empty($arr_new)?false:json_encode($arr_new);
    }
	/**
	 * 使用空格替换特殊字符
	 * @param string string_before
	 * @return string string_after
	 */
	 function string_replace($string_before){
		$string_after = str_replace('%','PP',$string_before);
        $string_after = str_replace('&','AND',$string_after);
        $string_after = str_replace(',','',$string_after);
		return $string_after;
	 }
	//功能函数。将变量值不为空的参数组成字符串。结束
	/**
	 * Return authorized languages by CreditCard
	 *
	 * @param	none
	 * @return	array
	 */
	protected function _getAuthorizedLanguages()
	{
		$languages = array();
		
        foreach (Mage::getConfig()->getNode('global/payment/pocketccns_payment/languages')->asArray() as $data)
		{
			$languages[$data['code']] = $data['name'];
		}
		
		return $languages;
	}
	
	/**
	 * Return language code to send to CreditCard
	 *
	 * @param	none
	 * @return	String
	 */
	protected function _getLanguageCode()
	{
		// Store language
		$language = strtoupper(substr(Mage::getStoreConfig('general/locale/code'), 0, 2));

		// Authorized Languages
		$authorized_languages = $this->_getAuthorizedLanguages();

		if (count($authorized_languages) === 1) 
		{
			$codes = array_keys($authorized_languages);
			return $codes[0];
		}
		
		if (array_key_exists($language, $authorized_languages)) 
		{
			return $language;
		}
		
		// By default we use language selected in store admin
		return $this->getConfigData('language');
	}



    /**
     *  Output failure response and stop the script
     *
     *  @param    none
     *  @return	  void
     */
    public function generateErrorResponse()
    {
        die($this->getErrorResponse());
    }

    /**
     *  Return response for CreditCard success payment
     *
     *  @param    none
     *  @return	  string Success response string
     */
    public function getSuccessResponse()
    {
        $response = array(
            'Pragma: no-cache',
            'Content-type : text/plain',
            'Version: 1',
            'OK'
        );
        return implode("\n", $response) . "\n";
    }

    /**
     *  Return response for CreditCard failure payment
     *
     *  @param    none
     *  @return	  string Failure response string
     */
    public function getErrorResponse()
    {
        $response = array(
            'Pragma: no-cache',
            'Content-type : text/plain',
            'Version: 1',
            'Document falsifie'
        );
        return implode("\n", $response) . "\n";
    }

}

接下来是干货勒
Magento 通用外挂 支付包

转载请注明:(●--●) Hello.My Weicot » Magento 支付模块常用函数

蜀ICP备15020253号-1