<?php

	class wpsg_mod_crefopay extends wpsg_mod_basic 
	{

		var $lizenz = 2;
		var $id = 4000;
		var $hilfeURL = 'http://wpshopgermany.de/?p=1101756';
		var $version = "9.9.9";
		var $free = true;
		
		var $transactionMapping = array();
		
		var $mns = false; // Wird bei einer MNS auf true gesetzt, damit die Stornierung beispielsweise nicht zweimal auslöst.
		
		var $callPath = array(
			'pay' => 'pay',
			'capture' => 'pay/capture',
			'status' => 'status',
			'refund' => 'refund',
			'cancel' => 'cancel',
			'finish' => 'finishTransaction'			
		);
		
		/**
		 * Costructor
		 */
		public function __construct()
		{
				
			parent::__construct();
				
			// Hier ist die Vorgabe der Zuordnung beim installieren des Moduls für die MNS Benachrichtigung
			// -1 = Kein Wechsel
			$this->transactionMapping = array(
				'NEW' => array(-1, 'NEW'),	 
				'ACKNOWLEDGEPENDING' => array(-1, 'ACKNOWLEDGEPENDING'),
				'FRAUDPENDING' => array(-1, 'FRAUDPENDING'),
				'FRAUDCANCELLED' => array(-1, 'FRAUDCANCELLED'),
				'CIAPENDING' => array(-1, 'CIAPENDING'),
				'MERCHANTPENDING' => array(-1, 'MERCHANTPENDING'),
				'PAYPENDING' => array(-1, 'PAYPENDING'),
				'PAID' => array(100, 'PAID'),
				'CANCELLED' => array(-1, 'CANCELLED'),
				'CLEARED' => array(-1, 'CLEARED'),
				'PAYMENTFAILED' => array(200, 'PAYMENTFAILED'),
				'CHARGEBACK' => array(-1, 'CHARGEBACK'),
				'EXPIRED' => array(-1, 'EXPIRED'),
				'INPROGRESS' => array(-1, 'INPROGRESS'),
				'DONE' => array(100, 'DONE')
			);
			
			$this->name = __('CrefoPay', 'wpsg');
			$this->group = __('Zahlungsarten', 'wpsg');
			$this->desc = __('Ermöglicht die Zahlung über CrefoPay.', 'wpsg');
		
		} // public function __construct()
		
		public function install()
		{
			
			$this->shop->checkDefault('wpsg_mod_crefopay_autocapture', '0');
			$this->shop->checkDefault('wpsg_mod_crefopay_capturestatus', '250');
			$this->shop->checkDefault('wpsg_mod_crefopay_riskclass', '1');
			$this->shop->checkDefault('wpsg_mod_crefopay_currency', 'EUR');
			$this->shop->checkDefault('wpsg_mod_crefopay_sandbox', '1');
									
			foreach ($this->transactionMapping as $crefopay_status => $wpsg_status) $this->shop->checkDefault('wpsg_mod_crefopay_statemapping_'.$crefopay_status, $wpsg_status[0]);
	 
			$this->shop->checkDefault('wpsg_mod_crefopay_frameheight', 1100);
			
		} // public function install()
		
		public function settings_edit()
		{
			
			$pages = get_pages();
				
			$arPages = array(
					'-1' => __('Neu anlegen und zuordnen', 'wpsg')
			);
				
			foreach ($pages as $k => $v)
			{
				$arPages[$v->ID] = $v->post_title.' (ID:'.$v->ID.')';
			}
				
			$this->shop->view['pages'] = $arPages;
			
			$basket_link = $this->shop->getUrl(wpsg_ShopController::URL_BASKET);
				
			if (strpos($basket_link, "?") > 0) $basket_link_crefopay = $basket_link."&wpsg_plugin=wpsg_mod_crefopay&return=";
			else $basket_link_crefopay = $basket_link."?wpsg_plugin=wpsg_mod_crefopay&return=";
			
			$this->shop->view['url'] = array(
				'redirect_url' => $basket_link_crefopay.'redirect',
				'basket_url' => $basket_link,
				'agb_url' => $this->shop->getUrl(wpsg_ShopController::URL_AGB),
				'mns_url' => $basket_link_crefopay.'mns',
				'jump_url' => $this->getDoPayUrl()	
			);
			
			$this->shop->view['transactionMapping'] = $this->transactionMapping;
			
			$this->shop->render(WPSG_PATH_VIEW.'/mods/mod_crefopay/settings_edit.phtml');
			
		} // public function settings_edit()
		
		public function wpsg_order_view_customerdata(&$order_id)
		{
			
			$this->shop->view['arPayment'][$this->id]['name'] = $this->getOrderPaymentName($order_id); 
			
		} // public function wpsg_order_view_customerdata(&$order_id)
		
		public function settings_save()
		{
			
			$this->shop->update_option('wpsg_mod_crefopay_merchantID', $_REQUEST['wpsg_mod_crefopay_merchantID']);
			$this->shop->update_option('wpsg_mod_crefopay_shopID', $_REQUEST['wpsg_mod_crefopay_shopID']);
			$this->shop->update_option('wpsg_mod_crefopay_sandbox', $_REQUEST['wpsg_mod_crefopay_sandbox']);
			$this->shop->update_option('wpsg_mod_crefopay_privateKey', $_REQUEST['wpsg_mod_crefopay_privateKey']);
			$this->shop->update_option('wpsg_mod_crefopay_autocapture', $_REQUEST['wpsg_mod_crefopay_autocapture']);
			$this->shop->update_option('wpsg_mod_crefopay_capturestatus', $_REQUEST['wpsg_mod_crefopay_capturestatus']);
			$this->shop->update_option('wpsg_mod_crefopay_riskclass', $_REQUEST['wpsg_mod_crefopay_riskclass']);
			$this->shop->update_option('wpsg_mod_crefopay_currency', $_REQUEST['wpsg_mod_crefopay_currency']);						
			$this->shop->update_option('wpsg_mod_crefopay_frameheight', $_REQUEST['wpsg_mod_crefopay_frameheight']);
						
			// Mapping speichern
			foreach ($this->transactionMapping as $crefopay_state => $wpsg_state) $this->shop->update_option('wpsg_mod_crefopay_statemapping_'.$crefopay_state, $_REQUEST['wpsg_mod_crefopay_statemapping_'.$crefopay_state]);

			$this->shop->update_option('wpsg_mod_crefopay_mns_notice', $_REQUEST['wpsg_mod_crefopay_mns_notice']);
									
		} // public function settings_save()
		
		public function addPayment(&$arPayment)
		{
				
			$mwst_value = $this->getTaxValue($this->shop->get_option('wpsg_mod_crefopay_mwst'), $this->shop->getDefaultCountry());
		
			$arPayment = array();
			$arPayment[$this->id] = array(
				'id' => $this->id,
				'name' => __('CrefoPay', 'wpsg'),
				'preis' => 0,
				'mwst' => 0,
				'mwst_value' => 0,
				'mwst_null' => $this->shop->get_option('wpsg_mod_crefopay_mwstland'),
				'hint' => '',
				'logo' => $this->shop->getRessourceURL('mods/mod_crefopay/gfx/logo_crefopay.gif'),
				'logo_100x25' => $this->shop->getRessourceURL('mods/mod_crefopay/gfx/logo_100x25.png')
			);
					
		} // public function addPayment(&$arPayment)
		 	
		public function order_done(&$order_id, &$done_view)
		{
		
			// Bestellungen mit 0 geben nix aus
			/*
			if ($done_view['basket']['sum']['preis_gesamt_brutto'] <= 0) return;
				
			if ($this->shop->view['basket']['checkout']['payment'] == $this->id)
			{
					  				
				$oOrder = wpsg_order::getInstance($order_id);
				
				if (wpsg_isSizedString($oOrder->getMeta('wpsg_mod_crefopay_redirectURL')))
				{
					
					$this->shop->view['wpsg_mod_crefopay']['redirectURL'] = $oOrder->getMeta('wpsg_mod_crefopay_redirectURL');
					
				}
				else 
				{
				
					// Startet die Zahlung und setzt die VIEW Variablen
					$arResponse = $this->call_pay($order_id);
					
				}
				
				$this->shop->render(WPSG_PATH_VIEW.'/mods/mod_crefopay/order_done.phtml');
		
			}
			*/
		
		} // public function order_done(&$order_id)
		
		public function mail_payment()
		{
		
			if ($this->shop->view['basket']['checkout']['payment'] != $this->id) return;
				
			if ($this->shop->htmlMail === true)
			{
		
				echo '<a href="'.$this->shop->getDoneURL($this->shop->view['o_id']).'">'.__('Zahlungslink', 'wpsg').'</a>'.__(', um die Zahlung durchzuführen', 'wpsg');
		
			}
			else
			{
					
				echo wpsg_pad_right(__('Zahlungslink', 'wpsg').':', 35).$this->shop->getDoneURL($this->shop->view['o_id']);
		
			}
				
		} // public function mail_payment()
		
		public function wp_loaded() 
		{
					
			if (wpsg_isSizedString($_REQUEST['wpsg_plugin'], 'wpsg_mod_crefopay'))
			{
				
				//mail("daniel@maennchen1.de", "CREFOTEST ".$_REQUEST['return'], print_r($_REQUEST, 1));
				
				// Temporär den Request korrigieren
				// Anfrage URL: http://dev.wpshopgermany.de/warenkorb/?wpsg_plugin=wpsg_mod_crefopay&return=redirect?merchantID=2&...
				if (strpos($_REQUEST['return'], '?') !== false) 
				{
					
					parse_str(substr($_REQUEST['return'], strpos($_REQUEST['return'], '?') + 1), $req);		
					$_REQUEST = wpsg_array_merge($_REQUEST, $req);		
					$_REQUEST['return'] = substr($_REQUEST['return'], 0, strpos($_REQUEST['return'], '?')); 	
				
				}
				
				if ((wpsg_isSizedString($_REQUEST['return'], 'success') || wpsg_isSizedString($_REQUEST['return'], 'redirect')) && wpsg_isSizedInt($_REQUEST['basketID']))
				{
									
					$macFields = array('merchantID', 'storeID', 'orderNo', 'merchantReference', 'basketID', 'sessionID', 'paymentMethod', 'status', 'locale', 'version');
					
					$calc_mac = $this->handleMAC($_REQUEST, $macFields, true);
					
					if (wpsg_isSizedInt($_REQUEST['basketID']))
					{
						
						$oOrder = wpsg_order::getInstance($_REQUEST['basketID']);
						$oCustomer = $oOrder->getCustomer();

						$oOrder->setMeta('wpsg_mod_crefopay_paymentMethod', $_REQUEST['paymentMethod']);
						
						$this->shop->arPayment[$this->id]['name'] = $this->getOrderPaymentName($oOrder->id);
						
						// Mails versenden
						$this->shop->basket->initFromDB($oOrder->id);						
						
						$arBasket = $this->shop->basket->toArray();
						
						$arBasket['checkout']['datum'] = strtotime($oOrder->cdate);
						$arBasket['checkout']['knr'] = $oCustomer->knr;
						$arBasket['checkout']['onr'] = $oOrder->onr;
						
						$this->shop->basket->sendOrderSaveMails($oOrder->id, $arBasket);
						
						if ($oOrder === false) die('FEHLER');
												
						if ($calc_mac != $_REQUEST['mac'])
						{
							
							$oOrder->log(__('Fehler bei CrefoPay Zahlungsbenachrichtigung (MAC incorrect)', 'wpsg'), "Request Data:\r\n".print_r($_REQUEST, 1));
							 
						}
						else
						{
							
							if ($_REQUEST['status'] == 'OK')
							{
								
								$oOrder->log(__('Erfolgreiche CrefoPay Zahlungsbenachrichtigung', 'wpsg'), "Request Data:\r\n".print_r($_REQUEST, 1));
								 
							}
							else
							{
								
								$oOrder->log(__('Abgelehnte CrefoPay Zahlungsbenachrichtigung', 'wpsg'), "Request Data:\r\n".print_r($_REQUEST, 1));
															
							}
							
						}
						
					}
					
					$basket_link = $this->shop->getURL(wpsg_ShopController::URL_BASKET);
					
					if (strpos($basket_link, "?") > 0)
					{
							
						$destroyFrame_url = $basket_link . "&wpsg_plugin=wpsg_mod_crefopay&return=destroyFrame&status=".$_REQUEST['status'].'&order_id='.$_REQUEST['basketID'];
							
					}
					else
					{
							
						$destroyFrame_url = $basket_link . "?wpsg_plugin=wpsg_mod_crefopay&return=destroyFrame&status=".$_REQUEST['status'].'&order_id='.$_REQUEST['basketID'];
							
					}
					 
					die($destroyFrame_url);
					
				}
				else if (wpsg_isSizedString($_REQUEST['return'], 'destroyFrame'))
				{

					$this->call_status($_REQUEST['order_id'], false);
										
					$url = $this->shop->getDoneURL($_REQUEST['order_id']);
					
					die('<script type="text/javascript">/* <![CDATA[ */ 
							
						if (window != window.top || window.parent.frames.length > 0) 
						{
							
							parent.wpsg_mod_crefopay_destroyFrame("'.$url.'");

						}
						else
						{
							
							location.href = "'.$url.'";
							
						}	
							
					/* ]]> */</script>');
					
				}
				else if (wpsg_isSizedString($_REQUEST['return'], 'mns'))
				{
					
					$this->mns = true;
					
					$macFields = array(
						'version', 'merchantID', 'storeID', 'orderNo', 'paymentReference', 'basketID', 'userID', 'merchantReference', 'resultCode', 'amount',
						'currencyCode', 'previousTransactionStatus', 'transactionStatus', 'previousOrderStatus', 'orderStatus', 'timestamp'
					);
						
					$calc_mac = $this->handleMAC($_REQUEST, $macFields, true);
					
					if (wpsg_isSizedInt($_REQUEST['basketID']))
					{
					
						$oOrder = wpsg_order::getInstance($_REQUEST['basketID']);
					
						if ($oOrder === false) die('FEHLER');
					
						if ($calc_mac != $_REQUEST['mac'])
						{
								
							$oOrder->log(__('Fehler bei CrefoPay MNS (MAC incorrect)', 'wpsg'), "Request Data:\r\n".print_r($_REQUEST, 1));
					
						}
						else
						{
								
							$oOrder->log(wpsg_translate(__('Erfolgreiche CrefoPay MNS (#1#)', 'wpsg'), $_REQUEST['transactionStatus']), "Request Data:\r\n".print_r($_REQUEST, 1));
					
							$setStatus = $this->shop->get_option('wpsg_mod_crefopay_statemapping_'.$_REQUEST['transactionStatus']);
							
							if (wpsg_isSizedInt($setStatus) && array_key_exists($setStatus, $this->shop->arStatus) && $oOrder->status != $setStatus)
							{
																								
								$inform = $this->shop->get_option('wpsg_mod_crefopay_mns_notice');
								
								$this->shop->setOrderStatus($oOrder->id, $setStatus, wpsg_isSizedInt($inform));
								
							}
								
						}
					
					}
					
					die("MNS OK");
					
				}
				
			}
						
		} // public function wp_loaded()
		
		public function order_ajax()
		{
			
			if (wpsg_isSizedString($_REQUEST['do'], 'status'))
			{
							
				$bOK = $this->call_status($_REQUEST['edit_id']);
				
				if ($bOK !== false) $this->shop->addBackendMessage(__('CrefoPay Status wurde erfolgreich abgefragt.', 'wpsg'));
				else $this->shop->addBackendError(__('CrefoPay Status konnte nicht abgefragt werden. Bitte beachten Sie das Bestellprotokoll.', 'wpsg'));
				
				$this->shop->redirect(WPSG_URL_WP.'wp-admin/admin.php?page=wpsg-Order&action=view&edit_id='.$_REQUEST['edit_id']);
				
			}
			else if (wpsg_isSizedString($_REQUEST['do'], 'cancel'))
			{
								
				$bOK = $this->call_cancel($_REQUEST['edit_id']);
				
				if ($bOK !== false) 
				{
					
					$this->shop->addBackendMessage(__('CrefoPay Zahlungsabbruch wurde erfolgreich durchgeführt. Der Kunde kann die Zahlung nun über die Bestellabschlußseite (Link in E-Mail) neu starten.', 'wpsg'));
					
					// Zahlungsstatus auffrischen
					$this->call_status($_REQUEST['edit_id'], true);
					
				}
				else $this->shop->addBackendError(__('CrefoPay Zahlungsabbruch konnte nicht übermittelt werden. Bitte beachten Sie das Bestellprotokoll.', 'wpsg'));
			 	
				$this->shop->redirect(WPSG_URL_WP.'wp-admin/admin.php?page=wpsg-Order&action=view&edit_id='.$_REQUEST['edit_id']);
				
			}
			else if (wpsg_isSizedString($_REQUEST['do'], 'capture'))
			{
				
				$bOK = $this->call_capture($_REQUEST['edit_id']);
				
				if ($bOK !== false)
				{
					
					$this->shop->addBackendMessage(__('CrefoPay Zahlungseinzug wurde erfolgreich durchgeführt.', 'wpsg'));

					// Zahlungsstatus auffrischen
					$this->call_status($_REQUEST['edit_id'], true);
					
				}
				else $this->shop->addBackendError(__('CrefoPay Zahlungseinzug konnte nicht übermittelt werden. Bitte beachten Sie das Bestellprotokoll.', 'wpsg'));
					
				$this->shop->redirect(WPSG_URL_WP.'wp-admin/admin.php?page=wpsg-Order&action=view&edit_id='.$_REQUEST['edit_id']);
				
			}
			else if (wpsg_isSizedString($_REQUEST['do'], 'refund'))
			{
				
				$bOK = $this->call_refund($_REQUEST['edit_id']);
				
				if ($bOK !== false)
				{
					
					$this->shop->addBackendMessage(__('CrefoPay Rückerstattung wurde erfolgreich durchgeführt.', 'wpsg'));
					
					// Zahlungsstatus auffrischen
					$this->call_status($_REQUEST['edit_id'], true);
					
				}
				else $this->shop->addBackendError(__('CrefoPay Rückerstattung konnte nicht übermittelt werden. Bitte beachten Sie das Bestellprotokoll.', 'wpsg'));
				
				$this->shop->redirect(WPSG_URL_WP.'wp-admin/admin.php?page=wpsg-Order&action=view&edit_id='.$_REQUEST['edit_id']);
				
			}
			else if (wpsg_isSizedString($_REQUEST['do'], 'finish'))
			{
				
				$bOK = $this->call_finish($_REQUEST['edit_id']);
				
				if ($bOK !== false)
				{
					
					$this->shop->addBackendMessage(__('CrefoPay Abschluss wurde erfolgreich durchgeführt.', 'wpsg'));
										
				}
				else $this->shop->addBackendError(__('CrefoPay Abschluss konnte nicht übermittelt werden. Bitte beachten Sie das Bestellprotokoll.', 'wpsg'));
				
				$this->shop->redirect(WPSG_URL_WP.'wp-admin/admin.php?page=wpsg-Order&action=view&edit_id='.$_REQUEST['edit_id']);
				
			}
			 
		} // public function order_ajax()
		
		public function order_view_afterpayment(&$order_id)
		{
			
			$this->shop->render(WPSG_PATH_VIEW.'/mods/mod_crefopay/order_view_afterpayment.phtml');
			
		} // public function order_view_sidebar(&$order_id)
		
		public function setOrderStatus($order_id, $status_id, $inform)
		{

			// Nur bei Stornierung etwas machen
			if (!in_array($status_id, array('500')) || $this->mns === true) return;
			
			$oOrder = wpsg_order::getInstance($order_id);
			
			if ($status_id == '500' && $oOrder->getPaymentID() == $this->id) $response = $this->call_refund($order_id);
			
		}
		
		public function getPaymentName($payment_type, $order_id, &$payment_name) 
		{ 
			
			if ($payment_type == $this->id) $payment_name = $this->getOrderPaymentName($order_id);
			
		} // public function getPaymentName($payment_type, $order_id)
		
		public function template_redirect() 
		{ 

			if (wpsg_isSizedString($_REQUEST['wpsg_mod'], 'wpsg_mod_crefopay') && wpsg_isSizedString($_REQUEST['wpsg_action'], 'doOrder'))
			{
				
				// Hier die Prüfung durchführen und ggf. umleiten

				// Zahlungsart auf CrefoPay setzen
				$_SESSION['wpsg']['checkout']['payment'] = $this->id;
				$this->shop->basket->arCheckout['payment'] = $this->id;
				
				// Bestellung abschließen
				$this->shop->basket->initFromSession();
								
				$bOK = $this->shop->basket->checkCheckout();
				
				if ($bOK)
				{
						
					// Jetzt noch Module checken
					$bModulError = false; $this->shop->callMods('checkFinaly', array(&$bModulError));
						
					if ($bModulError === true)
					{
				
						$this->shop->redirect($this->shop->getURL(wpsg_ShopController::URL_CHECKOUT));
				
					}	
					else 
					{
					
						// Bestellung in Session sichern
						$_SESSION['wpsg']['wpsg_mod_crefopay']['wpsg_preCommit'] = $_SESSION['wpsg'];
												
						$order_id = $this->shop->basket->save();
							
						$_SESSION['wpsg']['wpsg_mod_crefopay']['order_id'] = $order_id;
						
						$this->shop->redirect($this->getDoPayUrl($order_id));
						
					} 
						
				}
				else
				{
						
					$this->shop->redirect($this->shop->getURL(wpsg_ShopController::URL_CHECKOUT));
						
				}
				
			}
			else if (isset($_REQUEST['orderNo']) && wpsg_isSizedInt($_SESSION['wpsg']['wpsg_mod_crefopay']['order_id']))
			{

				// Alte Bestellung aus Session laden
				$oOrder = wpsg_order::getInstance($_SESSION['wpsg']['wpsg_mod_crefopay']['order_id']);
				
				if ($oOrder->onr != $_REQUEST['orderNo']) die($this->shop->throwErrorCode('4000_1'));

				// Alte Bestellung löschen
				$oOrder->delete();
				
				// Hier kommt der Kunde zurück in den Warenkorb um die Bestellung abzuändern
				$_SESSION['wpsg'] = $_SESSION['wpsg']['wpsg_mod_crefopay']['wpsg_preCommit'];

				// Zum Warenkorb umleiten
				$this->shop->redirect($this->shop->getURL(wpsg_ShopController::URL_BASKET));
				
			}
			
		}
		
		public function content_filter(&$content) 
		{ 
			
			if (wpsg_isSizedString($_REQUEST['wpsg_mod'], 'wpsg_mod_crefopay') && wpsg_isSizedString($_REQUEST['wpsg_action'], 'doPay'))
			{
				
				// TODO Parameterproblem ändern wenn CrefoPay es gefixt hat
				// Aufruf: http://dev.wpshopgermany.de/warenkorb/?wpsg_mod=wpsg_mod_crefopay&wpsg_action=doPay&order_id=jump?jsEnabled=1&locale=
				if (wpsg_isSizedString($_REQUEST['order_id']) && strpos($_REQUEST['order_id'], 'jump') !== false)
				{
					
					$this->shop->view['wpsg_mod_crefopay']['redirectURL'] = $_REQUEST['uri'];
					
				}
				else
				{
				
					$hash = preg_replace('/(\+)|(\=)/', 'A', base64_encode(md5('wpsg_mod_crefopay'.$_REQUEST['order_id'], $this->shop->get_option("wpsg_salt"))));
					
					if ($hash != $_REQUEST['hash'])
					{
						
						$this->shop->addFrontendError(__('Es ist ein Fehler aufgetreten, bitte Shop Betreiber benachrichtigen.', 'wpsg'));
						
					}
					else
					{
						
						$oOrder = wpsg_order::getInstance($_REQUEST['order_id']);
						
						if (!wpsg_isSizedString($oOrder->getMeta('wpsg_mod_crefopay_redirectURL')))
						{
								
							// Startet die Zahlung 
							$response = $this->call_pay($_REQUEST['order_id']);
							
							if ($response === false)
							{
								
								$log = $oOrder->getLastLogEntry();
															
								$this->shop->addFrontendError($log['title']);
								
							}
							
						}
	 
						$this->shop->view['wpsg_mod_crefopay']['redirectURL'] = $oOrder->getMeta('wpsg_mod_crefopay_redirectURL');
											
					}
					
				}
				
				$content = $this->shop->render(WPSG_PATH_VIEW.'/mods/mod_crefopay/iframe.phtml', false);
								
				return -2;
				
			}
						
		} // public function content_filter(&$content)
		
		/* Modul Funktionen */
				
		/**
		 * Gibt den Namen der Zahlungsart für eine Bestellung zurück
		 */
		public function getOrderPaymentName($order_id)
		{
			
			$oOrder = wpsg_order::getInstance($order_id);
			if (wpsg_isSizedString($oOrder->getMeta('wpsg_mod_crefopay_paymentMethod')))
			{
			
				return $this->getCrefoPayPaymentName($oOrder->getMeta('wpsg_mod_crefopay_paymentMethod'));
			
			}
			else return wpsg_translate(__('CrefoPay / Unbestimmt', 'wpsg'));
			
		} // public function getOrderPaymentName($order_id)
		
		/**
		 * Gibt die URL zurück auf der der CrefoPay IFrame angezeigt wird
		 */
		public function getDoPayUrl($order_id = 'jump')
		{
			
			$param  = 'wpsg_mod=wpsg_mod_crefopay&amp;wpsg_action=doPay&order_id='.$order_id;
			
			if ($order_id != "jump")
			{
			
				$param .= '&hash='.preg_replace('/(\+)|(\=)/', 'A', base64_encode(md5('wpsg_mod_crefopay'.$order_id, $this->shop->get_option("wpsg_salt"))));
				
			}
			
			$url = $this->shop->getURL(wpsg_ShopController::URL_BASKET);
			$url .= ((strpos($url, '?') === false)?'?'.$param:'&amp;'.$param);
				
			return $url;
			
		} // public function getDoPayUrl()
		 
		/**
		 * Gibt die URL zu der Seite zurück auf der die Bestellung eingetragen wird   
		 * Diese Seite leitet dann auf die getDoPayUrl um nachdem
		 */
		public function getDoOrderUrl()
		{
			
			$url = $this->shop->getURL(wpsg_ShopController::URL_BASKET);
			$url .= ((strpos($url, '?') === false)?'?wpsg_mod=wpsg_mod_crefopay&amp;wpsg_action=doOrder':'&amp;wpsg_mod=wpsg_mod_crefopay&amp;wpsg_action=doOrder');
			
			return $url;
			
		} // public function getDoOrderUrl()
		 
		/**
		 * Gibt die für CrefoPay verwendete Währung zurück
		 */
		private function getCrefoCurrency()
		{
			
			if (!wpsg_isSizedString($this->shop->get_option('wpsg_mod_crefopay_currency')) || $this->shop->get_option('wpsg_mod_crefopay_currency') === false)
			{
				
				return 'EUR';
				
			}
			else
			{
				
				return $this->shop->get_option('wpsg_mod_crefopay_currency');
				
			}
			
		}
		
		/**
		 * Bricht eine Bezahlung ab, um sie neu starten zu können
		 * @param unknown $order_id
		 */
		public function call_cancel($order_id)
		{
			
			$oOrder = wpsg_order::getInstance($order_id);
			
			$data = array(
				'merchantID' => $this->shop->get_option('wpsg_mod_crefopay_merchantID'),
				'storeID' => $this->shop->get_option('wpsg_mod_crefopay_shopID'),
				'orderNo' => $oOrder->onr,
				'version' => '1.2'
			);
			
			$macFields = array('merchantID', 'storeID', 'orderNo', 'version');
				
			$this->handleMAC($data, $macFields);
				
			$response = $this->crefopay_call($order_id, $data, $this->callPath['cancel']);
			
			if ($response !== false)
			{
				 
				// Mac verifizieren
				$macFields = array(
					'merchantID', 'storeID', 'orderNo', 'version', 'errorCode', 'resultCode'
				);
					
				$calc_mac = $this->handleMAC($response, $macFields, true);
					
				if ($calc_mac == $response['mac'])
				{
			
					$oOrder->log(__('CrefoPay Zahlungsabbruch erfolgreich', 'wpsg'), "Response Data:\r\n".print_r($response, 1));
						
					return $response;
						
				}
				else
				{
			
					$oOrder->log(__('CrefoPay Zahlungsabbruch konnte nicht übermittelt werden (HASH Fehler)', 'wpsg'), "Response Data:\r\n".print_r($response, 1)."\r\nCalculated hash: ".$calc_mac);
			
				}
					
			} 
				
			return false;
			
		} // public function call_cancel($order_id)
		
		/**
		 * Führt eine Stornierung durch und setzt alle Erfolgreich/Nicht Erfolgreichen Log Einträgt
		 */
		public function call_refund($order_id)
		{
			
			$oOrder = wpsg_order::getInstance($order_id);
			
			$data = array(
				'merchantID' => $this->shop->get_option('wpsg_mod_crefopay_merchantID'),
				'storeID' => $this->shop->get_option('wpsg_mod_crefopay_shopID'),
				'orderNo' => $oOrder->onr,
				'refundDescription' => __('Stornierung', 'wpsg'),
				'totalAmount' => $oOrder->getAmount() * 100,
				'currency' => $this->getCrefoCurrency(),
				'referenceNo' => $order_id,
				'version' => '1.2'
			);
			
			$macFields = array('merchantID', 'storeID', 'orderNo', 'refundDescription', 'totalAmount', 'currency', 'referenceNo', 'version');
							
			$this->handleMAC($data, $macFields);
			
			$response = $this->crefopay_call($order_id, $data, $this->callPath['refund']);
			
			if ($response !== false)
			{
			 			
				// Mac verifizieren
				$macFields = array(
					'merchantID', 'storeID', 'orderNo', 'version', 'errorCode', 'resultCode'
				);
			
				$calc_mac = $this->handleMAC($response, $macFields, true);
			
				if ($calc_mac == $response['mac'])
				{

					$oOrder->log(__('CrefoPay Stornierung erfolgreich', 'wpsg'), "Response Data:\r\n".print_r($response, 1));
					
					return $response;
					
				}	
				else
				{
						
					$oOrder->log(__('CrefoPay Stornierung konnte nicht übermittelt werden (HASH Fehler)', 'wpsg'), "Response Data:\r\n".print_r($response, 1)."\r\nCalculated hash: ".$calc_mac);
										
				}
					
			} 
			
			return false;
			
		} // public function call_refund($order_id)
		
		/**
		 * Führt die eine Finish transaction Anfrage durch
		 * @param unknown $order_id
		 */
		public function call_finish($order_id)
		{
			
			$oOrder = wpsg_order::getInstance($order_id);
				
			$data = array(
				'merchantID' => $this->shop->get_option('wpsg_mod_crefopay_merchantID'),
				'storeID' => $this->shop->get_option('wpsg_mod_crefopay_shopID'),
				'orderNo' => $oOrder->onr,				
				'version' => '1.2'
			);
			
			$macFields = array('merchantID', 'storeID', 'orderNo', 'version');
				
			$this->handleMAC($data, $macFields);
			
			$response = $this->crefopay_call($order_id, $data, $this->callPath['finish']);
			
			if ($response === false)
			{
				
				// Fehler bereits über crefopay_call geloggt.
				return false;
				
			}
			else
			{
			
				// Mac verifizieren
				$macFields = array(
					'merchantID', 'storeID', 'orderNo', 'version', 'errorCode', 'resultCode'
				);
			
				$calc_mac = $this->handleMAC($response, $macFields, true);
			
				if ($calc_mac == $response['mac'] && $response['status'] == "OK")
				{
						
					if (!$noLog) $oOrder->log(__('CrefoPay Rückerstattung wurde erfolgreich durchgeführt', 'wpsg'), "Response Data:\r\n".print_r($response, 1));
			 						
					return $response;
						
				}
				else if ($calc_mac != $response['mac'])
				{
						
					if (!$noLog)$oOrder->log(__('CrefoPay Rückerstattung konnte nicht durchgeführt werden (HASH Fehler)', 'wpsg'), "Response Data:\r\n".print_r($response, 1)."\r\nCalculated hash: ".$calc_mac);
						
					return false;
						
				}
				else 
				{
				
					if (!$noLog)$oOrder->log(__('CrefoPay Rückerstattung konnte nicht erfolgreich durchgeführt werden', 'wpsg'), "Response Data:\r\n".print_r($response, 1)."\r\nCalculated hash: ".$calc_mac);
				
					return false;
				
				}
			
			}
			
		} // public function call_finish($order_id)
		
		/**
		 * Führt eine Statusabfrage durch und aktualisiert die Bestellung
		 */
		public function call_status($order_id, $noLog = false)
		{
			
			$oOrder = wpsg_order::getInstance($order_id);
			
			$data = array(
				'merchantID' => $this->shop->get_option('wpsg_mod_crefopay_merchantID'),
				'storeID' => $this->shop->get_option('wpsg_mod_crefopay_shopID'),
				'orderNo' => $oOrder->onr,
				'referenceNo' => '', // Order reference – in case of partial captures the unique reference for the partial order (e.g. the invoice number). So this is the reference that was used during the capture call. In case only the orderNo is used the system returns all information about the transaction. In case the referenceNumber is given, the system returns all information about the specific order.
				'version' => '1.2'				
			);
			
			$macFields = array('merchantID', 'storeID', 'orderNo', 'referenceNo', 'version');
			
			$this->handleMAC($data, $macFields);
			
			$response = $this->crefopay_call($order_id, $data, $this->callPath['status'], $noLog);
				
			if ($response === false)
			{
				
				// Fehler bereits über crefopay_call geloggt.
				return false;
			
			}
			else
			{
				
				// Mac verifizieren
				$macFields = array(
					'merchantID', 'storeID', 'orderNo', 'version', 'locale', 'resultCode', 'additionalInformation'
				);
				
				$calc_mac = $this->handleMAC($response, $macFields, true);
				
				if ($calc_mac == $response['mac'] && $response['status'] == "OK")
				{
					
					if (!$noLog) $oOrder->log(__('CrefoPay Status wurde erfolgreich abgefragt', 'wpsg'), "Response Data:\r\n".print_r($response, 1));
					 
					$oOrder->setMeta('wpsg_mod_crefopay_status', $response['resultCode']);
					$oOrder->setMeta('wpsg_mod_crefopay_status_time', time());
					
					if ($response['resultCode'] == 'PAID' && $oOrder->status != 100)
					{
						
						// Auf Zahlung akzeptiert setzen
						$this->shop->setOrderStatus($oOrder->id, 100, true);
						
					}
					
					return $response;
					
				} 
				else 
				{
					
					if (!$noLog)$oOrder->log(__('CrefoPay Status konnte nicht abgefragt werden (HASH Fehler)', 'wpsg'), "Response Data:\r\n".print_r($response, 1)."\r\nCalculated hash: ".$calc_mac);
					
					return false;
					
				}
				
			}
			
		} // public function call_status($order_id)
		
		/**
		 * Führt eine Capture Anfrage bei RETAIL Bestellungen durch
		 */
		public function call_capture($order_id)
		{
			
			$oOrder = wpsg_order::getInstance($order_id);
				
			$data = array(
				'merchantID' => $this->shop->get_option('wpsg_mod_crefopay_merchantID'),
				'storeID' => $this->shop->get_option('wpsg_mod_crefopay_shopID'),
				'orderNo' => $oOrder->onr,
				'totalAmount' => $oOrder->getAmount() * 100,
				'currency' => $this->getCrefoCurrency(),
				'referenceNo' => $oOrder->id,
				'version' => '1.2'				
			);
			
			$macFields = array(
				'merchantID', 'storeID', 'orderNo', 'totalAmount', 'currency', 'referenceNo', 'version',				
			);
				
			$this->handleMAC($data, $macFields);
			
			$response = $this->crefopay_call($order_id, $data, $this->callPath['capture']);
				
			if ($response !== false)
			{
				 
				// Mac verifizieren
				$macFields = array(
					'merchantID', 'storeID', 'orderNo', 'basketID', 'version', 'errorCode', 'resultCode'
				);
				
				$calc_mac = $this->handleMAC($response, $macFields, true);
				
				if ($calc_mac == $response['mac'])
				{
						 
					$oOrder->log(__('CrefoPay Capture wurde erfolgreich durchgeführt', 'wpsg'), "Response Data:\r\n".print_r($response, 1));
					
					return $response;
						
				}
				else
				{
						
					$oOrder->log(__('CrefoPay Capture konnte nicht gestartet werden (HASH Fehler)', 'wpsg'), "Response Data:\r\n".print_r($response, 1)."\r\nCalculated hash: ".$calc_mac);
						
				}
				
			}
			
			return false;
			
		} // public function call_capture($order_id)
		
		/**
		 * Führt eine CrefoPay Anfrage durch
		 */
		public function call_pay($order_id)
		{
			
			$oOrder = wpsg_order::getInstance($order_id);			
			$oCustomer = $oOrder->getCustomer();
						
			$data = array(
				'merchantID' => $this->shop->get_option('wpsg_mod_crefopay_merchantID'),
				'storeID' => $this->shop->get_option('wpsg_mod_crefopay_shopID'),
				'orderNo' => $oOrder->onr,
				'userID' => $oOrder->k_id,
				'name' => $oCustomer->vname, /* ? */
				'middleName' => '',
				'surname' => $oCustomer->name, // User’s surname
				'email' => $oCustomer->email, // User’s E-Mail-Adress
				'birthday' => $oCustomer->geb, // User’s date of birth, Dash as delimiter; YYYY-MM-DD, example: 1990-12-31
				'billingAddressRecipient' => $oOrder->getInvoiceFirstName().' '.$oOrder->getInvoiceName(), // User’s recipient name
				'billingAddressCo' => '', // Second address line of user’s billing address; e.g. c/O
				'billingAddressStreet' => $oOrder->getInvoiceStreetClear(), // User’s Street name of billing adress
				'billingAddressNo' => $oOrder->getInvoiceStreetNr(), // User’s house number of billing adress
				'billingAddressNoAdditional' => '', // Additional information to house number of users billing adress; e.g. appartment number
				'billingAddressState' => '', // State of user’s billing adress, e.g. NRW
				'billingAddressCity' => $oOrder->getInvoiceCity(), // City of user’s billing adress
				'billingAddressZip' => $oOrder->getInvoiceZip(), // ZIP code of of user’s billing adress
				'billingAddressCountry' => $oOrder->getInvoiceCountryKuerzel(), // 2- letter country code of of user’s billing adress according
				'deliveryAddressRecipient' => $oOrder->getShippingFirstName().' '.$oOrder->getShippingName(), // Differing delivery recipient name
				'deliveryAddressCo' => '', // Second address line of user’s differing delivery address
				'deliveryAddressStreet' => $oOrder->getShippingStreetClear(), // User’s Street name of differing delivery address. Required only if at least one of the remaining deliveryAddress fields were provided.
				'deliveryAddressNo' => $oOrder->getShippingStreetNr(), // User’s house number of differing delivery address
				'deliveryAddressNoAdditional' => '', // Additional information to house number of user’s differing delivery address
				'deliveryAddressState' => '', // State of user’s delivery adress, e.g. NRW
				'deliveryAddressCity' => $oOrder->getShippingCity(), // City of user’s differing delivery address. Required only if at least one of the remaining deliveryAddress fields were provided.
				'deliveryAddressZip' => $oOrder->getShippingZip(), // ZIP code of of user’s differing delivery address. Required only if at least one of the remaining deliveryAddress fields were provided.
				'deliveryAddressCountry' => $oOrder->getShippingCountryKuerzel(), // 2- letter country code of of user’s differing delivery address according ISO 3166. Required only if at least one of the remaining deliveryAddress fields were provided.
				'basketID' => $oOrder->id,
				'sessionID' => session_id(),
				'merchantReference' => '', // Merchant reference to be shown on reconciliation records
				'couponCode' => '', // Promotional coupon code entered by the end user
				'currency' => $this->getCrefoCurrency(), // Currency code according to ISO4217
				'basketAmount' => $oOrder->getProductAmount() * 100, // Overall sum of all basket items (excl. shipping, service fees, coupons) - Amount in smallest possible denomination e.g. 12366 ct; Amounts have always to be including all applicable taxes.
				'shippingAbsolute' => $oOrder->getShippingAmount() * 100, // Shipping fees - Amount in smallest possible denomination e.g. 12366 ct; Amounts have always to be including all applicable taxes
				'couponAbsolute' => '', // Coupon amount - Amount in smallest possible denomination e.g. 12366 ct; Amounts have always to be including all applicable taxes
				'riskclassOverall' => (($this->shop->get_option('wpsg_mod_crefopay_riskclass') !== false)?$this->shop->get_option('wpsg_mod_crefopay_riskclass'):1),							
				'shippingText' => $oOrder->getShippingTypName(), // Shipping option selected by the end user, e.g. “Standard delivery”
				'phoneNumber' => $oCustomer->tel, // User’s phone number
				'transactionType' => (($this->shop->get_option('wpsg_mod_crefopay_autocapture') === '1')?'DIRECT':'RETAIL'), // transaction type – even though this filed is mandatory omitting the field will use the default setting which is RETAIL
				'remoteAddress' => $_SERVER['REMOTE_ADDR'], // This is the end-user IP address, e.g. 172.1.1.1
				'categories' => '', // This parameter defines a transaction group or user category, and is only sent based on previous agreement between CrefoPay and the shop. This is comma separated value parameter.
				'basketValidity' => '1h', // Warenkorbgültigkeit (1h eingestellt)
				'locale' => 'de', // Step1 in Deutsch. Locale of payment pages. “de” for German, “en” for English, etc.
				'version' => '1.2', // This is the current API version
				'basketItems' => array()
			);
									
			$oOrder->setMeta('wpsg_mod_crefopay_transactionType', $data['transactionType']);
			
			foreach ($oOrder->getOrderProducts() as $oOrderProduct)
			{
				 
				$data['basketItems'][] = array(
					'basketItemText' => $oOrderProduct->getProduct()->getProductName(), // Basket item product name, e.g. Sneakers
					'basketItemCount' => $oOrderProduct->menge, // Basket item quantity
					'basketItemCurrency' => $this->getCrefoCurrency(), // Basket item currency
					'basketItemPrice' => round($oOrderProduct->price * 100), // Basket item total amount (i.e. quantity x item price) Amount in smallest possible denomination e.g. 12366 ct Amounts have always to be including all applicable taxes
					'basketItemRiskclass' => (($this->shop->get_option('wpsg_mod_crefopay_riskclass') !== false)?$this->shop->get_option('wpsg_mod_crefopay_riskclass'):1), // This risk class is calculated by the merchant per item.
					'basketItemPictureURL' => '', // URL to a product picture for the basket Item. Pictures should be 46x46px or will be scaled to this size. E.g © CREFOPAY AG 27/66 http://myshop.de/sneaker.gi))
					'basketItemPictureTitle' => '', // Basket item product picture title, usually short product name
					'basketItemProductURL' => $oOrderProduct->getProduct()->getProductURL(), // Basket item product link. E.g. http://myshop.tld/my-product/
					'basketItemAttribute' => ''									 				
				);
				
			}
			
			$data['basketItems'] = json_encode($data['basketItems']);
			 
			$macFields = array(
				'merchantID', 'storeID', 'orderNo', 'userID', 'name', 'middleName', 'surname', 'email', 'birthday', 'billingAddressRecipient',
				'billingAddressCo', 'billingAddressStreet', 'billingAddressNo', 'billingAddressNoAdditional', 'billingAddressState', 'billingAddressCity', 'billingAddressZip', 'billingAddressCountry', 'deliveryAddressRecipient', 'deliveryAddressCo', 
				'deliveryAddressStreet', 'deliveryAddressNo', 'deliveryAddressNoAdditional', 'deliveryAddressState', 'deliveryAddressCity',  'deliveryAddressZip', 'deliveryAddressCountry', 'basketID', 'sessionID', 'merchantReference',
				'couponCode', 'currency', 'basketAmount', 'shippingAbsolute', 'couponAbsolute', 'riskclassOverall', 'basketItems', 'basketValidity', 'shippingText', 'phoneNumber',
				'transactionType', 'categrories', 'locale', 'version'
			);
			
			$this->handleMAC($data, $macFields);
			 
			$response = $this->crefopay_call($order_id, $data, $this->callPath['pay']);
			
			if ($response === false)
			{
				
				// Fehler bereits über crefopay_call geloggt.
				return false;
				
			}
			else
			{
			
				// Mac verifizieren
				$macFields = array(
					'merchantID', 'storeID', 'orderNo', 'basketID', 'sessionID', 'merchantReference', 'redirectURL', 'version', 'status', 'paycoUserID'	
				);
				
				$calc_mac = $this->handleMAC($response, $macFields, true);
				
				if ($calc_mac == $response['mac'])
				{
					
					if ($response['status'] == "OK" && $response['basketID'] == $order_id)
					{
					
						$oOrder->log(__('CrefoPay Zahlung erfolgreich gestartet', 'wpsg'), "Response Data:\r\n".print_r($response, 1));
											
						$oOrder->setMeta('wpsg_mod_crefopay_redirectURL', $response['redirectURL']);
						$oOrder->setMeta('wpsg_mod_crefopay_paycoUserID', $response['paycoUserID']);
						
						return true;
						
					}
					else
					{
						
						$oOrder->log(__('CrefoPay Zahlung konnte nicht gestartet werden (Ungültige Antwort)', 'wpsg'), "Response Data:\r\n".print_r($response, 1));
						return false;
						
					}
					
				}
				else
				{
					
					$oOrder->log(__('CrefoPay Zahlung konnte nicht gestartet werden (HASH Fehler)', 'wpsg'), "Response Data:\r\n".print_r($response, 1)."\r\nCalculated hash: ".$calc_mac);
					return false;
					
				}
				
			}
			
		}
		 
		/**
		 * Gibt die URL für die Anfragen zurück
		 */
		private function getURL()
		{
			
			if ($this->shop->get_option('wpsg_mod_crefopay_sandbox') == '1') return 'http://payco-sandbox.de/';
			else return 'https://www.pay-co.net/';
			
		} // private function getURL()
						
		private function crefopay_call($order_id, $data, $call, $noLog = false)
		{
			
			$oOrder = wpsg_order::getInstance($order_id);
			
			$ch = curl_init();
				
			$strError = "";
				
			if (strlen(curl_error($ch))) {
			
				$strError = curl_errro($ch);
			
			}
			else
			{
			
				curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
				curl_setopt($ch, CURLOPT_URL, $this->getURL().$call.'/');
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
				curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
				curl_setopt($ch, CURLOPT_TIMEOUT, 60);
				curl_setopt($ch, CURLOPT_POST, 1);
				curl_setopt($ch, CURLOPT_HEADER, 0);
				curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data, '', '&'));
			
				$responseBody = @curl_exec($ch);
				$responseInfo = curl_getinfo($ch);
			
				if (strlen(curl_error($ch)))
				{
			
					$strError = wpsg_translate(__('CURL Error: #1#', 'wpsg'), curl_error($ch));
						
				}
				else
				{
						
					$json_response = @json_decode($responseBody, true);
			
					if (wpsg_isSizedArray($json_response))
					{
			
						if (isset($json_response['errorCode']) && $json_response['errorCode'] != 'OK')
						{
								
							$strError = $json_response['message'].' ('.$json_response['errorCode'].')';
								
						}
						else
						{
								
							// Alles gut -> MAC verifizieren			
							return $json_response;
															
						}
			
					}
					else
					{
							
						$strError = "JSON Error: ".json_last_error();
			
					}
						
				}
			
			}
				
			if (wpsg_isSizedString($strError) && !$noLog)
			{
			 
				$oOrder->log(wpsg_translate(__('CrefoPay Fehler: #1#', 'wpsg'), $strError), "Request Data:\r\n".print_r($data, 1)."\r\nResponse Body:\r\n".$responseBody."\r\n\r\nResponse Info:\r\n".print_r($responseInfo, 1));
				
			}
			
			return false;
			
		}
		
		/**
		 * Gibt den Klarnamen für eine CrefoPay Zahlungsart zurück
		 * @param String $payment_code
		 */
		private function getCrefoPayPaymentName($payment_code)
		{
			
			$arPayment = array(
				'BILL' => 'Rechnung',
				'BILL_SECURE' => 'Rechnung mit Zahlungsgarantie',
				'PREPAID' => 'Vorkasse',
				'COD' => 'Zahlung bei Lieferung',
				'CC3D' => '3D-Secure Kreditkarte',
				'CC' => 'Kreditkarte',
				'DD' => 'Überweisung',
				'PAYPAL' => 'PayPal',
				'PAYPALEXPRESS' => 'PayPal Express',
				'SU' => 'Sofortüberweisung'							
			);
			
			if (array_key_exists(strtoupper($payment_code), $arPayment)) return __($arPayment[$payment_code], 'wpsg');
			else return 'Unknown: '.$payment_code;
			
		} // private function getCrefoPayPaymentName($payment_code)
		
		private function handleMAC(&$data, $macFields, $bReturn = false) 
		{
			
			$key = $this->shop->get_option('wpsg_mod_crefopay_privateKey');

			$strToMac = '';
			
			foreach ($macFields as $mac_key) { $strToMac .= $data[$mac_key]; }
			 
			$strToMac = str_replace(array(" ", "\t", "\r", "\n", ' '), "", $strToMac);
 			
			// RFC2104 HMAC implementation for php.
			// Creates an SHA-1 HMAC.
			$b=64;// byte length for SHA-1
			$key = str_pad($key, $b, chr(0x00));
			$ipad = str_pad('', $b, chr(0x36));
			$opad = str_pad('', $b, chr(0x5c));
			$k_ipad = $key ^ $ipad;
			$k_opad = $key ^ $opad;
			
			$mac = sha1($k_opad.pack("H*", sha1($k_ipad.$strToMac)));
			
			if ($bReturn === true)
			{
				
				return $mac;
				
			}
			else
			{
			
				$data['mac'] = $mac;
				
			}
 
		}
		
	} // class wpsg_mod_crefopay extends wpsg_mod_basic

?>