<?php

	/**
	 * Modul zur Zahlungsabwicklung über die PayPal REST API
	 * @author Daschmi (daniel@maennchen1.de)
	 */
	class wpsg_mod_paypalapi extends wpsg_mod_basic
	{

		var $apiContext = false;
		
		var $lizenz = 1;
		var $id = 10;		
		var $hilfeURL = 'http://wpshopgermany.de/?p=1728009';
		var $version = "9.9.9";
		var $free = false;
		
		private $currency = "EUR";
		
		/**
		 * Costructor
		 */
		public function __construct()
		{
				
			parent::__construct();
				
			$this->name = __('PayPal PLUS', 'wpsg');
			$this->group = __('Zahlungsarten', 'wpsg');
			$this->desc = __('Ermöglicht die Zahlungsart PayPal und PayPal PLUS, über die REST API Schnittstelle und Login mit PayPal Express.', 'wpsg');
		
		} // public function __construct()
				
		public function install()
		{
			
			$this->shop->checkDefault('wpsg_mod_paypalapi_aktiv', '1');
			$this->shop->checkDefault('wpsg_mod_paypalapi_paypalexpress', '1');
			$this->shop->checkDefault('wpsg_mod_paypalapi_plus_hint', __('Zahlen Sie die Bestellung mittels ihres PayPal Kontos', 'wpsg'), false, true);
			$this->shop->checkDefault('wpsg_mod_paypalapi_paypalexpress_name', __('PayPal', 'wpsg'), false, true);
			$this->shop->checkDefault('wpsg_mod_paypalapi_paypalexpress_subject', 'O%order_id% - K%kunde_id%', false, true);
			$this->shop->checkDefault('wpsg_mod_paypalapi_paypalexpress_details', '1');
					 			
			$this->shop->checkDefault('wpsg_mod_paypalapi_experience_label', '%shopinfo_name%', false, true);
			$this->shop->checkDefault('wpsg_mod_paypalapi_experience_locale_code', 'DE');
			
			$this->shop->checkDefault('wpsg_mod_paypalapi_plus_aktiv', '1');		
									
			$this->shop->checkDefault('wpsg_mod_paypalapi_stornostate', array('400' => '1', '500' => '1'));
							
		} // 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;
					
			$this->shop->render(WPSG_PATH_VIEW.'/mods/mod_paypalapi/settings_edit.phtml');
				
		} // public function settings_edit()
		
		public function settings_save()
		{
			
			$this->shop->update_option('wpsg_mod_paypalapi_clientid', $_REQUEST['wpsg_mod_paypalapi_clientid']);
			$this->shop->update_option('wpsg_mod_paypalapi_secret', $_REQUEST['wpsg_mod_paypalapi_secret']);
			$this->shop->update_option('wpsg_mod_paypalapi_sandbox', $_REQUEST['wpsg_mod_paypalapi_sandbox']);
			$this->shop->update_option('wpsg_mod_paypalapi_sandbox_clientid', $_REQUEST['wpsg_mod_paypalapi_sandbox_clientid']);
			$this->shop->update_option('wpsg_mod_paypalapi_sandbox_secret', $_REQUEST['wpsg_mod_paypalapi_sandbox_secret']);
			$this->shop->update_option('wpsg_mod_paypalapi_webhook_log', $_REQUEST['wpsg_mod_paypalapi_webhook_log']);
			$this->shop->update_option('wpsg_mod_paypalapi_webhook_logfile', $_REQUEST['wpsg_mod_paypalapi_webhook_logfile']);
			
			$this->shop->update_option('wpsg_mod_paypalapi_gebuehr', $_REQUEST['wpsg_mod_paypalapi_gebuehr']);
			$this->shop->update_option('wpsg_mod_paypalapi_mwst', $_REQUEST['wpsg_mod_paypalapi_mwst']);
			$this->shop->update_option('wpsg_mod_paypalapi_mwstland', $_REQUEST['wpsg_mod_paypalapi_mwstland']);
			
			$this->shop->update_option('wpsg_mod_paypalapi_stornostate', $_REQUEST['wpsg_mod_paypalapi_stornostate']);
			
			$this->shop->update_option('wpsg_mod_paypalapi_aktiv', $_REQUEST['wpsg_mod_paypalapi_aktiv']);
			$this->shop->update_option('wpsg_mod_paypalapi_paypalexpress', $_REQUEST['wpsg_mod_paypalapi_paypalexpress']);
			$this->shop->update_option('wpsg_mod_paypalapi_paypalexpress_name', $_REQUEST['wpsg_mod_paypalapi_paypalexpress_name'], false, true);
			$this->shop->update_option('wpsg_mod_paypalapi_plus_hint', $_REQUEST['wpsg_mod_paypalapi_plus_hint'], false, true);
			$this->shop->update_option('wpsg_mod_paypalapi_paypalexpress_subject', $_REQUEST['wpsg_mod_paypalapi_paypalexpress_subject']);
			$this->shop->update_option('wpsg_mod_paypalapi_paypalexpress_details', $_REQUEST['wpsg_mod_paypalapi_paypalexpress_details']);
			
			$this->shop->update_option('wpsg_mod_paypalapi_experience_label', $_REQUEST['wpsg_mod_paypalapi_experience_label'], false, true);
			$this->shop->update_option('wpsg_mod_paypalapi_experience_logo', $_REQUEST['wpsg_mod_paypalapi_experience_logo']);
			$this->shop->update_option('wpsg_mod_paypalapi_experience_locale_code', $_REQUEST['wpsg_mod_paypalapi_experience_locale_code']);
			
			$this->shop->createPage(__('Erfolgreiche PayPal Zahlung', 'wpsg'), 'wpsg_page_mod_paypalapi_success', $_REQUEST['wpsg_page_mod_paypalapi_success']);
			$this->shop->createPage(__('Fehlgeschlagene PayPal Zahlung', 'wpsg'), 'wpsg_page_mod_paypalapi_error', $_REQUEST['wpsg_page_mod_paypalapi_error']);
						
			$this->shop->update_option('wpsg_mod_paypalapi_plus_aktiv', $_REQUEST['wpsg_mod_paypalapi_plus_aktiv']);		
			
			// WebHook
			if (wpsg_isSizedInt($_REQUEST['wpsg_mod_paypalapi_create'])) $this->createWebHook();
			
			// PaymentExperience
			if (wpsg_isSizedString($_REQUEST['wpsg_mod_paypalapi_clientid']) && wpsg_isSizedString($_REQUEST['wpsg_mod_paypalapi_secret']))
			{
				
				$json_data = $this->api_getWebExperience();
				$paymentExperienceID = false;
				
				foreach ($json_data as $p) if ($p['name'] == 'wpShopGermany') $paymentExperienceID = $p['id'];
				
				if ($paymentExperienceID === false)
				{
					
					// PaymentExperience existiert nicht => anlegen
					$json_data = $this->api_createWebExperience();
				
					$this->shop->update_option('wpsg_mod_paypalapi_paymentExperience', $json_data['id']);
					
				}
				else
				{
				
					$this->shop->update_option('wpsg_mod_paypalapi_paymentExperience', $paymentExperienceID);
					
					$this->api_updateWebExperience($paymentExperienceID);
										
				}
				
			}
			
		} // public function settings_save()
		
		public function setOrderStatus($order_id, $status_id, $inform)
		{
		
			$oOrder = wpsg_order::getInstance($order_id);
			
			if ($oOrder->getPaymentID() == $this->id)
			{
				
				$arStornoState = (array)$this->shop->get_option('wpsg_mod_paypalapi_stornostate');
			
				if (array_key_exists($status_id, $arStornoState) && $arStornoState[$status_id] == '1')
				{
					
					if (wpsg_isSizedString($oOrder->getMeta('wpsg_mod_paypalapi_saleid')))
					{
					
						$bStorno = $this->stornoOrder($order_id);
						
						if ($bStorno === true) $this->shop->addBackendMessage(__('Zahlung erfolgreich über die PayPal API storniert.', 'wpsg'));
						else $this->shop->addBackendError(__('Es gab ein Problem bei der Stornierung der Zahlung über die PayPal API. Bitte Bestellprotokoll beachten.', 'wpsg'));
						
					}
					
				}	

			}
			 				
		}
				
		public function addPayment(&$arPayment)
		{
 					
			if (is_admin() || $this->shop->get_option('wpsg_mod_paypalapi_aktiv') == '1')
			{
					
				$mwst_value = $this->getTaxValue($this->shop->get_option('wpsg_mod_paypalapi_mwst'), $this->shop->getDefaultCountry());
			
				$arPayment[$this->id] = array(
					'id' => $this->id,
					'name' => __($this->shop->get_option('wpsg_mod_paypalapi_paypalexpress_name'), 'wpsg'),
					'preis' => $this->shop->get_option('wpsg_mod_paypalapi_gebuehr'),
					'mwst' => $this->shop->get_option('wpsg_mod_paypalapi_mwst'),
					'mwst_value' => $mwst_value,
					'mwst_null' => $this->shop->get_option('wpsg_mod_paypalapi_mwstland'),
					'hint' => __($this->shop->get_option('wpsg_mod_paypalapi_plus_hint'), 'wpsg'),
					'logo' => $this->shop->getRessourceURL('gfx/paypal.png')
				);
			
				if (isset($_REQUEST['wpsg_checkout2']))
				{
			
					$arBasket = $this->shop->basket->toArray();
			
					if ($this->shop->get_option('wpsg_preisangaben') == WPSG_NETTO || $arBasket['noMwSt'])
					{
			
						$payment_netto = $this->getPreis($this->shop->get_option('wpsg_mod_paypalapi_gebuehr'), $arBasket['sum']['preis']);
						$payment_brutto = wpsg_calculatePreis($payment_netto, WPSG_BRUTTO, $mwst_value);
			
					}
					else
					{
			
						$payment_brutto = $this->getPreis($this->shop->get_option('wpsg_mod_paypalapi_gebuehr'), $arBasket['sum']['preis']);
						$payment_netto = wpsg_calculatePreis($payment_brutto, WPSG_NETTO, $mwst_value);
			
					}
			
					// Entsprechenden Preis anzeigen
					if ($this->shop->getFrontendTaxview() == WPSG_NETTO)
					{
							
						$arPayment[$this->id]['price'] = $payment_netto;
							
					}
					else
					{
							
						$arPayment[$this->id]['price'] = $payment_brutto;
							
					}
			
				}
			
			}
			
		} // public function addPayment(&$arPayment)
				
		public function calcPayment(&$arBasket)
		{
				
			if ($this->id == $arBasket['checkout']['payment'])
			{
		
				$payment_price = $this->getPreis($this->shop->get_option('wpsg_mod_paypalapi_gebuehr'), $arBasket['sum']['preis']);
		
				if ($this->shop->get_option('wpsg_mod_paypalapi_mwstland') == '1' && $arBasket['noMwSt'])
				{
						
					// Keine MwSt. berechnen !
					$arBasket['sum']['preis_payment'] = $payment_price;
					$arBasket['sum']['preis_payment_brutto'] = $payment_price;
					$arBasket['sum']['preis_payment_netto'] = $payment_price;
						
					$arBasket['payment']['mwst'] = 0;
					$this->shop->arPayment[$arBasket['checkout']['payment']]['mwst_value'] = 0;
		
					$arBasket['payment']['tax_rata'] = false;
						
				}
				else
				{
						
					// MwSt berechnen (Angaben im Backend sind immer Brutto)
					$this->setPaymentKosten($arBasket, $payment_price, $this->shop->get_option('wpsg_mod_paypalapi_mwstland'));
		
				}
		
			}
				
		} // public function calcPayment(&$arBasket)
				
		public function checkout_handlePayment()
		{
				
			if (!array_key_exists($this->id, $this->shop->arPayment)) return false;
			
			$this->shop->view['wpsg_mod_paypalapi']['show'] = 0;
							
			// Wenn eine andere Zahlungsart als PayPal gewählt wurde und Zahlungskosten entstanden sind,
			// dann lösche ich die Zahlung und lasse neu wählen			
			if ($this->id != $_SESSION['wpsg']['checkout']['payment'] && isset($this->shop->view['basket']['sum']['preis_payment'])  && $this->shop->view['basket']['sum']['preis_payment'] != 0)
			{
			
				unset($_SESSION['wpsg']['checkout']['payment']);
				
				$this->shop->basket->initFromSession(true);
				$this->shop->view['basket'] = $this->shop->basket->toArray();
								
			}
						
			// Zahlung über kompletten Betrag schon vorbereitet
			if (isset($_SESSION['wpsg']['checkout']['payment_amount']) && $_SESSION['wpsg']['checkout']['payment'] == $this->id)
			{
				
				if (wpsg_tf($_SESSION['wpsg']['checkout']['payment_amount']) == $this->shop->view['basket']['sum']['preis_gesamt_brutto'])
				{
					
					if ($this->shop->hasMod('wpsg_mod_willcollect'))
					{
							
						$arCheckout = array(
							'payment' => $_SESSION['wpsg']['checkout']['payment'],
							'shipping' => $_SESSION['wpsg']['checkout']['shipping']
						);
					
						$error = false; $step = 2;
						$this->shop->callMod('wpsg_mod_willcollect', 'checkCheckout', array(&$step, &$error, &$arCheckout));
					
						if ($error === true)
						{
							
							$this->shop->view['wpsg_mod_paypalapi']['error'] = __('Die Zahlungsart PayPal ist leider nicht mit der Versandart "Selbstabholung" möglich. Ihre Zahlung wurde storniert und ihr Konto nicht belastet. Bitte wählen Sie eine andere Zahlungsart aus.', 'wpsg');
							
							$this->setViewForPayPalPLus();
							$this->shop->view['wpsg_mod_paypalapi']['show'] = 3;
								
						}
					
					}
					else
					{
					
						$this->shop->view['wpsg_mod_paypalapi']['show'] = 1;
						
					}
					
				}
				else
				{
			
					if (wpsg_isSizedInt($this->shop->get_option('wpsg_mod_paypalapi_plus_aktiv')))
					{
						
						$this->setViewForPayPalPLus();						
						$this->shop->view['wpsg_mod_paypalapi']['show'] = 3;
						
					}
					else
					{
					
						$this->shop->view['wpsg_mod_paypalapi']['show'] = 2;
						$this->shop->render(WPSG_PATH_VIEW.'/mods/mod_paypalapi/checkout_handlePayment.phtml');
						
						return false;
						
					}
					 
				}
				
			}
			else  
			{
				
				if (wpsg_isSizedInt($this->shop->get_option('wpsg_mod_paypalapi_plus_aktiv')))
				{
						
					$this->setViewForPayPalPLus();
					$this->shop->view['wpsg_mod_paypalapi']['show'] = 3;
						
				}
				else
				{
					
					return false;
					
				}
				
			}
			
			if (isset($_SESSION['wpsg']['checkout']['payment']) && $_SESSION['wpsg']['checkout']['payment'] != '10') 
			{ 
			
				$this->shop->view['wpsg_mod_paypalapi']['error'] = __('Sie hatten bereits eine Zahlungsart gewählt. Aufgrund technischer Einschränkungen muss diese Auswahl hier erneut durchgeführt werden.', 'wpsg');
				
			}
			 
			$this->shop->render(WPSG_PATH_VIEW.'/mods/mod_paypalapi/checkout_handlePayment.phtml');
			
			return '-2';
							 			
		} // public function checkout_handlePayment() 
		
		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 order_ajax()
		{
			
			if (wpsg_isSizedString($_REQUEST['do'], 'refund'))
			{
			
				$bStorno = $this->stornoOrder($_REQUEST['edit_id']);
				
				if ($bStorno === true) $this->shop->addBackendMessage(__('Zahlung erfolgreich über die PayPal API storniert.', 'wpsg'));
				else $this->shop->addBackendError(__('Es gab ein Problem bei der Stornierung der Zahlung über die PayPal API. Bitte Bestellprotokoll beachten.', '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'], 'refresh'))
			{
				
				list($payment_state, $sale_state) = $this->getState($_REQUEST['edit_id']);
				
				if (!wpsg_isSizedString($payment_state)) $this->shop->addBackendError(__('Status der Zahlung konnte nicht abgefragt werden.', 'wpsg'));
				else $this->shop->addBackendMessage(wpsg_translate(__('Status der Zahlung (#1#) erfolgreich abgefragt.', 'wpsg'), $payment_state.'/'.$sale_state));
				
				$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_done(&$order_id, &$done_view)
		{
		 
			// Bestellungen mit 0 geben nix aus
			if ($done_view['basket']['sum']['preis_gesamt_brutto'] <= 0) return;
			
			$oOrder = wpsg_order::getInstance($order_id);
			
			// Bestellungen die nicht mit PayPal API beglichen werden sollen ignorieren
			if ($oOrder->getPaymentID() != $this->id) return;
			
			if (wpsg_isSizedString(($oOrder->getMeta('wpsg_mod_paypalapi_paymentId'))))
			{
				
				$payment_info = $this->api_getPaymentInfo($oOrder->getMeta('wpsg_mod_paypalapi_paymentId'), true);
				
				$amount_approved = floatval($payment_info['transactions'][0]['amount']['total']);
				
				//if ($amount_approved === floatval($oOrder->getAmount()) && !wpsg_isSizedString($oOrder->getMeta('wpsg_mod_paypalapi_saleid')))
				if ($amount_approved === floatval($oOrder->getAmount()) && !wpsg_isSizedString($oOrder->getMeta('wpsg_mod_paypalapi_saleid')) && wpsg_isSizedString($payment_info['payer']['status'], 'VERIFIED'))
				{
					
					$payment_info_execute = $this->api_executePayment($oOrder->getMeta('wpsg_mod_paypalapi_paymentId'), $oOrder->getMeta('wpsg_mod_paypalapi_payer_id'));
					 
					if (wpsg_isSizedString($payment_info_execute['transactions'][0]['related_resources'][0]['sale']['id']))
					{
					
						$sale_id = $payment_info_execute['transactions'][0]['related_resources'][0]['sale']['id'];
						$payment_info = $payment_info_execute;
			
						$oOrder->setMeta('wpsg_mod_paypalapi_saleid', $sale_id);
						$oOrder->setMeta('wpsg_mod_paypalapi_salestate', $payment_info_execute['transactions'][0]['related_resources'][0]['sale']['state']);
						$oOrder->setMeta('wpsg_mod_paypalapi_paymentstate', $payment_info['state']);
					
						if ($payment_info['state'] == 'approved')
						{
								
							$this->shop->view['wpsg_mod_paypalapi']['done'] = '2';
							$this->shop->render(WPSG_PATH_VIEW.'/mods/mod_paypalapi/order_done.phtml');
							
							return;
							
						}
						
					}
					
				}
												
			}
		 
 			if ($payment_info['state'] == 'approved')
			{
			
				$this->shop->view['wpsg_mod_paypalapi']['done'] = '1';				
				
			}
			else
			{
				
				$json_data = $this->api_startPayment($done_view['basket'], $order_id);

				$approval_url = "";
				foreach ($json_data['links'] as $k => $l) if ($l['rel'] == 'approval_url') $approval_url = $l['href'];
				
				$this->shop->view['wpsg_mod_paypalapi']['approval_url'] = $approval_url;
				$this->shop->view['wpsg_mod_paypalapi']['mode'] = (($this->isSandbox())?'sandbox':'live');

			}
			
			$this->shop->render(WPSG_PATH_VIEW.'/mods/mod_paypalapi/order_done.phtml');
		
		} // public function order_done(&$order_id)

		public function order_view_afterpayment(&$order_id)
		{
			
			$oOrder = wpsg_order::getInstance($order_id);
			
			if ($oOrder->getPaymentID() == $this->id)
			{
				 
				$this->shop->render(WPSG_PATH_VIEW.'/mods/mod_paypalapi/order_view_afterpayment.phtml');
				
			}
			
		}
		
		public function basket_inner_prebutton(&$basket_view) 
		{ 
			
			if (!wpsg_isSizedInt($this->shop->get_option('wpsg_mod_paypalapi_aktiv')) || !wpsg_isSizedInt($this->shop->get_option('wpsg_mod_paypalapi_paypalexpress'))) return false; 
			
			$this->shop->render(WPSG_PATH_VIEW.'/mods/mod_paypalapi/basket_inner_prebutton.phtml');
			
		} // public function basket_inner_prebutton(&$basket_view)
				
		public function basket_save_done_array(&$order_id, &$kunde_id, &$arBasket) 
		{ 
			
			if (wpsg_isSizedString($_SESSION['wpsg']['checkout']['paymentId']))
			{
				
				$oOrder = wpsg_order::getInstance($order_id);
				
				$oOrder->setMeta('wpsg_mod_paypalapi_paymentId', $_SESSION['wpsg']['checkout']['paymentId']);
				$oOrder->setMeta('wpsg_mod_paypalapi_payer_id', $_SESSION['wpsg']['checkout']['payer_id']);
				
			}
			
		} // public function basket_save_done_array(&$order_id, &$kunde_id, &$arBasket)
		
		public function basket_submitSuccess() 
		{ 
			
			// Zahlungsart auf PayPal API festlegen
			$pre_payment = $_SESSION['wpsg']['checkout']['payment'];
			if ($_SESSION['wpsg']['checkout']['payment'] != $this->id) $_SESSION['wpsg']['checkout']['payment'] = $this->id;
			
			$this->shop->basket->initFromSession();
			
			$basketError = false;
			
			if ($this->shop->callMods('basket_check') == false)
			{
			
				// Hier stimmt was mit den Daten im Warenkorb nicht -> Zurück zum Warenkorb leiten
				// Zum Beispiel Produktvariablen im Warenkorb
				$this->shop->redirect($this->shop->getUrl(wpsg_ShopController::URL_BASKET));
				$basketError = true;
					
			}	
			
			if (!wpsg_isSizedString($_SESSION['wpsg']['checkout']['shipping']))
			{
			
				$this->shop->addFrontendError(__('Bitte eine gültige Versandart auswählen.', 'wpsg'));
				$basketError = true;

			}
			
			if (!wpsg_isSizedInt($_SESSION['wpsg']['checkout']['land']))
			{
				
				$this->shop->addFrontendError(__('Bitte ein Land auswählen, damit die Versandkosten bestimmt werden können.', 'wpsg'));
				$basketError = true;
				
			}
			
			if ($this->shop->hasMod('wpsg_mod_willcollect'))
			{
			
				$arCheckout = array(
					'payment' => $_SESSION['wpsg']['checkout']['payment'],
					'shipping' => $_SESSION['wpsg']['checkout']['shipping']
				);
				
				$error = false; $step = 2;
				$this->shop->callMod('wpsg_mod_willcollect', 'checkCheckout', array(&$step, &$error, &$arCheckout));
				
				if ($error === true) 
				{
					
					$basketError = true;
					$_SESSION['wpsg']['checkout']['payment'] = $pre_payment; 
					
				}
				
			}
			 
			// Bei Fehlern zurück zum Warenkorb leiten
			if ($basketError === true) $this->shop->redirect($this->shop->getUrl(wpsg_ShopController::URL_BASKET));
						
			// Zahlung starten
			$this->shop->redirect($this->shop->getUrl(wpsg_ShopController::URL_BASKET, 'wpsg_mod_paypalapi', 'startPayPalExpress'));
			
		} // public function basket_submitSuccess()
		
		/* Redirects */
		
		/**
		 * Wird bei einem WebHook Event aufgerufen
		 * @throws Exception
		 */
		public function webHookRedirect()
		{
						
			$bodyReceived = file_get_contents('php://input');
						
			// Log BEGIN
			if ($this->shop->get_option('wpsg_mod_paypalapi_webhook_log') == '1')
			{
			
				//$log_file = '/var/home/htdocs/shop.maennchen1.de/logs/webHook.log';
				$log_file = $this->shop->get_option('wpsg_mod_paypalapi_webhook_logfile');
				
				$log_JsonData = json_decode($bodyReceived, true);
				$log_paymentID = $log_JsonData['resource']['parent_payment'];
				$log_orderID = $this->db->fetchOne("SELECT `target_id` FROM `".WPSG_TBL_META."` WHERE `meta_table` = 'WPSG_TBL_ORDER' AND `meta_key` = 'wpsg_mod_paypalapi_paymentid' AND `meta_value` = '".wpsg_q($log_paymentID)."' ");
					
				$strLog = date('d.m.Y H:i:s', time())."\r\nRAW:".$bodyReceived."\r\nDECODED:".print_r($log_JsonData, 1)."\r\nPAYMENT_ID:".$log_paymentID."\r\nGEFUNDENE BESTELLID:".$log_orderID."\r\n---------------\r\n\r\n";
				file_put_contents($log_file, file_get_contents($log_file)."\r\n".$strLog);
			
			}
			// Log END
			
			$jsonData = json_decode($bodyReceived, true);
			
			$payment_id = $jsonData['resource']['parent_payment'];
			$amount = $jsonData['resource']['amount']['total'];
			$order_id = $this->db->fetchOne("SELECT `target_id` FROM `".WPSG_TBL_META."` WHERE `meta_table` = 'WPSG_TBL_ORDER' AND `meta_key` = 'wpsg_mod_paypalapi_paymentid' AND `meta_value` = '".wpsg_q($payment_id)."' ");
			
			$oOrder = wpsg_order::getInstance($order_id);			
			if ($oOrder === false) die(__('Keine Bestellung zu PaymentID gefunden.', 'wpsg'));
			
			list($payment_state, $sale_state) = $this->getState($order_id);
			$orderPaymentID = $oOrder->getMeta('wpsg_mod_paypalapi_paymentid');
			
			if ($this->shop->setPayMent($oOrder->id, $amount) && $orderPaymentID === $payment_id && $payment_state === 'approved' && $sale_state === 'completed')
			{
				
				$this->shop->setOrderStatus($oOrder->id, 100, true);					 			
				$oOrder->log(__('PayPalAPI WebHook Erfolg', 'wpsg'), print_r($jsonData, 1));
				
			}
			else 
			{
				
				$oOrder->log(__('PayPalAPI Abgelehnt', 'wpsg', print_r($jsonData, 1)."\r\nOrder PaymentID:".$orderPaymentID."\r\nRequest PaymentID:".$payment_id."\r\nOrder State:".$state));
									
			}
			 
			header('HTTP/1.1 200 OK'); exit(1);
						
		} // public function webHookRedirect()
				
		/**
		 * Wird aus dem Warenkorb bei PayPal Express aufgerufen
		 */
		public function startPayPalExpressRedirect()
		{
			 
			//Bestellung wird im BasketController schon angelegt
			//$order_id = $this->shop->basket->save(false);
			$order_id = $_SESSION['wpsg']['order_id'];
						
			$json_data = $this->api_startPayment($this->shop->basket->toArray(), $order_id);
			
			$approval_url = false;
			foreach ($json_data['links'] as $l) { if ($l['rel'] == 'approval_url') $approval_url = $l['href']; }
 
			$this->shop->redirect($approval_url);
			
		} // public function startPayPalExpressRedirect()
		 
		/**
		 * Wird aufgerufen wenn der Kunde von PayPal zurück zum Shop kommt
		 */
		public function returnPayPalExpressRedirect()
		{
			
			$json_data = $this->api_getPaymentInfo($_REQUEST['paymentId']);

			$order_id = $this->db->fetchOne("SELECT `target_id` FROM `".WPSG_TBL_META."` WHERE `meta_table` = 'WPSG_TBL_ORDER' AND `meta_key` = 'wpsg_mod_paypalapi_paymentid' AND `meta_value` = '".wpsg_q($_REQUEST['paymentId'])."' ");
			
			if (wpsg_isSizedInt($order_id))
			{
				
				$oOrder = wpsg_order::getInstance($order_id);
				
				if ($oOrder !== false && $oOrder->status != wpsg_ShopController::STATUS_UNVOLLSTAENDIG)
				{
						
					$json_data = $this->api_executePayment($_REQUEST['paymentId'], $_REQUEST['PayerID']);
					
					$this->getState($oOrder->id);
					
					if (wpsg_isSizedString($json_data['transactions'][0]['related_resources'][0]['sale']['id'])) $oOrder->setMeta('wpsg_mod_paypalapi_saleid', $json_data['transactions'][0]['related_resources'][0]['sale']['id']);
					
					$this->shop->redirect($this->shop->getDoneURL($oOrder->id));
						
				}

			}
				
			$execute_url = false;
			foreach ($json_data['links'] as $l) { if ($l['rel'] == 'approval_url') $execute_url = $l['href']; }
			
			$_SESSION['wpsg']['checkout']['payment'] = $this->id;
			$_SESSION['wpsg']['checkout']['vname'] = $json_data['payer']['payer_info']['first_name'];
			$_SESSION['wpsg']['checkout']['name'] = $json_data['payer']['payer_info']['last_name'];
			$_SESSION['wpsg']['checkout']['email'] = $json_data['payer']['payer_info']['email'];
			$_SESSION['wpsg']['checkout']['email2'] = $json_data['payer']['payer_info']['email'];
			$_SESSION['wpsg']['checkout']['tel'] = $json_data['payer']['payer_info']['phone'];
			$_SESSION['wpsg']['checkout']['strasse'] =  $json_data['payer']['payer_info']['shipping_address']['line1'];
			$_SESSION['wpsg']['checkout']['ort'] = $json_data['payer']['payer_info']['shipping_address']['city'];
			$_SESSION['wpsg']['checkout']['plz'] = $json_data['payer']['payer_info']['shipping_address']['postal_code'];
			$_SESSION['wpsg']['checkout']['land'] = $this->db->fetchOne("SELECT `id` FROM `".WPSG_TBL_LAND."` WHERE UPPER(`kuerzel`) = '".wpsg_q(strtoupper($json_data['payer']['payer_info']['shipping_address']['country_code']))."'");
			$_SESSION['wpsg']['checkout']['payment_amount'] = $json_data['transactions'][0]['amount']['total'];
			$_SESSION['wpsg']['checkout']['paymentId'] = $_REQUEST['paymentId'];
			$_SESSION['wpsg']['checkout']['payer_id'] = $json_data['payer']['payer_info']['payer_id'];
			
			$this->shop->basket->initFromSession(true);
			
			// Hier ist das Speichern ok. Dadurch werden die Neuen Kundendaten von PayPal in der Unvollständigen Bestellung aktualisiert
			$this->shop->basket->save(false);
									
			$check1 = $checkCheckout = $this->shop->basket->checkCheckout(1);
			$check2 = $checkCheckout = $this->shop->basket->checkCheckout(2);
			
			if ($check1 === false)
			{
					
				$this->shop->redirect($this->shop->getUrl(wpsg_ShopController::URL_CHECKOUT));
					
			}
			else if ($check2 === false)
			{
					
				$this->shop->redirect($this->shop->getUrl(wpsg_ShopController::URL_CHECKOUT2));
					
			}
			else
			{
			
				$this->shop->addFrontendMessage(__('Ihre Daten wurden von PayPal übernommen und Sie können die Bestellung direkt abschließen, nachdem Sie alles überprüft haben.', 'wpsg'));
					
				$this->shop->redirect($this->shop->getUrl(wpsg_ShopController::URL_OVERVIEW));
					
			}
			
		}
		 
		/**
		 * Wird für den AutoRefresh der Versandarten bei PayPal PLUS verwendet 
		 */
		public function ShippingSelectRedirect()
		{
			
			$_SESSION['wpsg']['checkout']['shipping'] = $_REQUEST['wpsg']['checkout']['shipping'];
				
			$this->shop->redirect($this->shop->getUrl(wpsg_ShopController::URL_CHECKOUT2));
			
		} // public function ShippingSelectRedirect()
		
		/**
		 * Wird bei PayPal Plus aufgerufen wenn eine Zahlungsmethode aus dem Shop aufgerufen wurde
		 */
		public function PaymentSelectRedirect()
		{
			
			$_SESSION['wpsg']['checkout']['payment'] = $_REQUEST['payment_id'];
			
			$this->shop->redirect($this->shop->getUrl(wpsg_ShopController::URL_OVERVIEW));
						
		} // public function PaymentSelectRedirect()
		
		/* Aktionen */
		
		/* Modulfunktionen */
		
		/**
		 * Definiert Variablen für das View welches den IFrame einbindet
		 */
		private function setViewForPayPalPLus() 
		{
			
			$json_data = $this->api_startPayment($this->shop->view['basket'], $_SESSION['wpsg']['order_id'], false);
			
			$approval_url = false;
			foreach ($json_data['links'] as $l) { if ($l['rel'] == 'approval_url') $approval_url = $l['href']; }
			
			// Das war mal drin mir ist nicht klar warum:
			//$_SESSION['wpsg']['checkout']['payment'] = false;
			
			$arThirdPartyPayment = array();
			
			foreach ($this->shop->arPayment as $payment_id => $payment)
			{
				
				if ($payment_id != $this->id)
				{
					 
					$strPricePrefix = '';
					
					if ($payment['price'] > 0) 
					{
						
						$strPricePrefix = wpsg_translate(__('Bei Auswahl dieser Zahlungsart entstehen Kosten von #1#.', 'wpsg'), wpsg_ff($payment['price'], $this->shop->get_option('wpsg_currency'))).' ';
						
					}
					
					$tpp = array(
						'redirectUrl' => $this->shop->getUrl(wpsg_ShopController::URL_BASKET, 'wpsg_mod_paypalapi', 'PaymentSelect', array('payment_id' => $payment_id)),
						'methodName' => $payment['name'],
						'description' => $strPricePrefix.$payment['hint']
					);
					
					if (wpsg_isSizedString($payment['logo_100x25'])) $tpp['imageUrl'] = $payment['logo_100x25'];
					 
					$arThirdPartyPayment[] = $tpp;
					
				}
				
			}
			
			$this->shop->view['wpsg_mod_paypalapi']['ThirdPartyPayment'] = $arThirdPartyPayment;
			$this->shop->view['wpsg_mod_paypalapi']['mode'] = (($this->isSandbox())?'sandbox':'live');
			$this->shop->view['wpsg_mod_paypalapi']['approval_url'] = $approval_url;
						
		}
		
		/**
		 * Wird optional beim speichern ausgelöst, versucht den WebHook anzulegen und setzt die BackendMeldungen
		 */
		private function createWebHook()
		{
		
			$create_webhook = false;
			$wh_url = $this->shop->getUrl(wpsg_ShopController::URL_BASKET, 'wpsg_mod_paypalapi', 'webHook', array(), true);
			
			$arWH = $this->api_getWebHooks();
					
			if (wpsg_isSizedArray($arWH))
			{
				
				foreach ($arWH as $wh)
				{
				
					if ($wh['url'] === $wh_url)
					{
				
						$nExists = true;
						break;
				
					}
				
				}
				
				if ($nExists === false) $create_webhook = true;
				else
				{
						
					$this->shop->addBackendError(__('WebHook ist bereits registriert.', 'wpsg'));
						
				}
				
			}
			else $create_webhook = true;
			
			if ($create_webhook === true)
			{
				
				$bOK = $this->api_createWebHook($wh_url);
				
				if ($bOK === true) $this->shop->addBackendMessage(__('WebHook erfolgreich angelegt.', 'wpsg'));
				else $this->shop->addBackendError(__('WebHook konnte nicht angelegt werden.', 'wpsg'));
				
			}
			 				
		} // private function createWebHook();
		
		/**
		 * Gibt den PaymentState und SaleState zurück
		 */
		public function getState($order_id)
		{
												
			$oOrder = wpsg_order::getInstance($order_id);
			
			if (!wpsg_isSizedString($oOrder->getMeta('wpsg_mod_paypalapi_paymentid'))) return false;
			
			$payment_info = $this->api_getPaymentInfo($oOrder->getMeta('wpsg_mod_paypalapi_paymentid'));
			
			$payment_state = $payment_info['state'];
			$sale_state = $payment_info['transactions'][0]['related_resources'][0]['sale']['state'];
 
			if (!wpsg_isSizedString($payment_state)) return false;
			
			if (wpsg_isSizedString($payment_state)) $oOrder->setMeta('wpsg_mod_paypalapi_paymentstate', $payment_state);
			if (wpsg_isSizedString($sale_state)) $oOrder->setMeta('wpsg_mod_paypalapi_salestate', $sale_state);
									
			return array($payment_state, $sale_state); 
			
		} // public function getState($order_id)
		
		public function stornoOrder($order_id)
		{
			
			$oOrder = wpsg_order::getInstance($order_id);
			if ($oOrder === false) $this->shop->throwErrorCode('10_3');
			
			$sale_id = $oOrder->getMeta('wpsg_mod_paypalapi_saleid');
			
			$json_data = $this->api_refundSale($sale_id, $oOrder->getAmount());
			
			$this->getState($oOrder->id);			
			
			return true;
			
		} // public function stornoOrder($order_id)
		
		/**
		 * Gibt true/false zurück ob die Api auf die PayPal Sandbox zurückgreift
		 * @return boolean
		 */
		public function isSandbox()
		{
			
			if (wpsg_isSizedInt($this->shop->get_option('wpsg_mod_paypalapi_sandbox')))
			{
				
				return true;
				
			}
			else
			{
				
				return false;
				
			}
			
		} // public function isSandbox()
		
		/* Neu ohne PHPApi */
			
		private function api_refundSale($sale_id, $amount)
		{
			
			$post_data = array(
				'amount' => array(
					'total' => number_format($amount, 2),
					'currency' => $this->currency
				)		
			);
			
			$json_data = $this->api_call('v1/payments/sale/'.$sale_id.'/refund', $post_data, $this->api_getAccessToken());
			
			return $json_data;
			
		} // private function api_refundSale($sale_id)
		
		/**
		 * Erstellt einen neuen WebHook für Zahlungseingänge auf der übergebenene URL
		 */
		private function api_createWebHook($url)
		{
			
			$post_data = array(
				'url' => $url,
				'event_types' => array(
					array(
						'name' => 'PAYMENT.SALE.COMPLETED'
					) 
				)
			);
			
			$json_data = $this->api_call('v1/notifications/webhooks', $post_data, $this->api_getAccessToken());
			 
			if (wpsg_isSizedString($json_data['id'])) return true;
			else return false;
			
		} // private function api_createWebHook($url)
		
		/**
		 * Gibt alle registrierten WebHooks zurück
		 */
		private function api_getWebHooks()
		{
			
			$json_data = $this->api_call('v1/notifications/webhooks', false, $this->api_getAccessToken());
			
			return $json_data['webhooks'];
			
		} // private function api_getWebHooks()
		
		/**
		 * Führt eine Zahlung aus
		 */
		private function api_executePayment($payment_id, $payer_id)
		{
			
			$post_data = array(
				'payer_id' => $payer_id
			);
			
			$json_data = $this->api_call('v1/payments/payment/'.$payment_id.'/execute', $post_data, $this->api_getAccessToken());
			
			return $json_data;
			
		} // private function api_executePayment($payment_id, $payer_id, $order_id)
		
		/**
		 * Aktualisiert eine Zahlungserfahrung
		 */
		private function api_updateWebExperience($paymentExperienceID)
		{
			
			$brand_name = $this->shop->replaceUniversalPlatzhalter(__($this->shop->get_option('wpsg_mod_paypalapi_experience_label'), 'wpsg'));
			$logo_image = $this->shop->get_option('wpsg_mod_paypalapi_experience_logo');
			
			$post_data = array(
				'name' => 'wpShopGermany',
				'presentation' => array(					
					'locale_code' => $this->shop->get_option('wpsg_mod_paypalapi_experience_locale_code')
				)
			);
			
			if (wpsg_isSizedString($brand_name)) $post_data['presentation']['brand_name'] = $brand_name;
			if (wpsg_isSizedString($logo_image)) $post_data['presentation']['logo_image'] = $logo_image;			
			
			$json_data = $this->api_call('v1/payment-experience/web-profiles/'.$paymentExperienceID, $post_data, $this->api_getAccessToken(), false, true, true);
				
			return $json_data;
			
		} // private function api_updateWebExperience($paymentExperienceID)
		
		/**
		 * Erstellt eine Zahlungserfahrung
		 */
		private function api_createWebExperience()
		{
			 
			$brand_name = $this->shop->replaceUniversalPlatzhalter(__($this->shop->get_option('wpsg_mod_paypalapi_experience_label'), 'wpsg'));
			$logo_image = $this->shop->get_option('wpsg_mod_paypalapi_experience_logo');
			
			$post_data = array(
				'name' => 'wpShopGermany',
				'presentation' => array(
					'locale_code' => $this->shop->get_option('wpsg_mod_paypalapi_experience_locale_code')
				)
			);
			
			if (wpsg_isSizedString($brand_name)) $post_data['presentation']['brand_name'] = $brand_name;
			if (wpsg_isSizedString($logo_image)) $post_data['presentation']['logo_image'] = $logo_image;
			
			$json_data = $this->api_call('v1/payment-experience/web-profiles', $post_data, $this->api_getAccessToken());
				
			return $json_data;
			
		} // private function api_createWebExperience()
		
		/**
		 * Gibt Informationen über angelegte Zahlungserfahrungen zurück
		 */
		private function api_getWebExperience()
		{
			
			$access_token = $this->api_getAccessToken();
			
			$json_data = $this->api_call('v1/payment-experience/web-profiles', false, $access_token);
			
			return $json_data;
			
		} // private function api_getWebExperience()
		
		/**
		 * Authorisiert eine Zahlung
		 */
		private function api_startPayment($arBasket, $order_id = false, $express = true)
		{
						
			$oOrder = wpsg_order::getInstance($order_id);
			$access_token = $this->api_getAccessToken();
 
			$item_list = array(
				'items' => array()
			);
			
			$post_data = array();
						
			$post_data['transactions'] = array(
				array(
					'amount' => array(
						'total' => number_format($arBasket['sum']['preis_gesamt_brutto'], 2),
						'currency' => $this->currency
					),
					'description' => $this->shop->replaceUniversalPlatzhalter(__($this->shop->get_option('wpsg_mod_paypalapi_paypalexpress_subject'), 'wpsg'), $order_id),
				)
			);
				
			$subTotal = 0;
			
			// Produkte
			foreach ($arBasket['produkte'] as $k => $p)
			{
			
				$product_price = ((wpsg_isSizedString($arBasket['noMwSt'], '1'))?$p['preis_netto']:$p['preis_brutto']);
				
				$item_list['items'][] = array(
					'quantity' => $p['menge'],
					'name' => $this->shop->getProductName($this->shop->getProduktID($p['id']), true),
					'description' => '',
					'sku' => $this->shop->getProductAnr($this->shop->getProduktID($p['id'])),
					'url' => $this->shop->getProduktLink($this->shop->getProduktID($p['id'])),
					'price' => number_format($product_price, 2),
					'currency' => $this->currency
				);
				
				$subTotal += $product_price * $p['menge'];
			
			}
			
			// Gutschein
			if (isset($arBasket['sum']['gs_brutto']))
			{
					
				$item_list['items'][] = array(
					'quantity' => '1',
					'name' => __('Gutschein', 'wpsg'),
					'description' => wpsg_translate(__('Eingelöster Gutschein Code:#1#', 'wpsg'), $arBasket['gs']['code']),
					'price' => number_format(-1 * $arBasket['sum']['gs_brutto'], 2),
					'currency' => $this->currency
				);
				
				$subTotal += -1 * $arBasket['sum']['gs_brutto'];
			
			}
				
			// Zahlungskosten/Vergünstigungen
			if (isset($arBasket['sum']['preis_payment_brutto']) && $arBasket['sum']['preis_payment_brutto'] != 0)
			{
			
				$item_list['items'][] = array(
					'quantity' => '1',
					'name' => (($arBasket['sum']['preis_payment_brutto'] > 0)?__('Gebühr für Zahlungsart', 'wpsg'):__('Rabatt durch Zahlungsart', 'wspg')),
					'description' => __('Rabatt, der Aufgrund der gewählten Zahlungsart entstanden ist.', 'wpsg'),
					'price' => number_format($arBasket['sum']['preis_payment_brutto'], 2),
					'currency' => $this->currency
				);
				
				$subTotal += $arBasket['sum']['preis_payment_brutto'];
			
			}
			
			// Rabatte auf Warenkorb
			if (isset($arBasket['sum']['preis_rabatt_brutto']) && $arBasket['sum']['preis_rabatt_brutto'] > 0)
			{
				 
				$item_list['items'][] = array(
					'quantity' => '1',
					'name' => __('Rabatt', 'wpsg'),
					'description' => __('Rabatt, der sich aus dem Warenkorbwert ergibt.', 'wpsg'),
					'price' => number_format(-1 * $arBasket['sum']['preis_rabatt_brutto'], 2),
					'currency' => $this->currency						
				); 
				
				$subTotal += -1 * $arBasket['sum']['preis_rabatt_brutto'];
				
			} 
			
			$post_data['intent'] = 'sale';
			$post_data['payer'] = array(
				'payment_method' => 'paypal'
			);			
				
			if ($oOrder->status == wpsg_ShopController::STATUS_UNVOLLSTAENDIG)
			{
			
				$post_data['redirect_urls'] = array(
					'return_url' => $this->shop->getUrl(wpsg_ShopController::URL_BASKET, 'wpsg_mod_paypalapi', 'returnPayPalExpress'),
					'cancel_url' => $this->shop->getUrl(wpsg_ShopController::URL_BASKET)
				);
				
			}
			else
			{
			
				$post_data['redirect_urls'] = array(
					'return_url' => $this->shop->getUrl(wpsg_ShopController::URL_BASKET, 'wpsg_mod_paypalapi', 'returnPayPalExpress'),
					'cancel_url' => $this->shop->getDoneURL($oOrder->id)
				);
				
			}
						
			// Versandkosten/Vergünstigungen
			if (isset($arBasket['sum']['preis_shipping_brutto']) && $arBasket['sum']['preis_shipping_brutto'] > 0)
			{
				
				$details['shipping'] = number_format($arBasket['sum']['preis_shipping_brutto'], 2);
				
			} 
			else if (isset($arBasket['sum']['preis_shipping_brutto']) && $arBasket['sum']['preis_shipping_brutto'] < 0)
			{
			
				$item_list['items'][] = array(
					'quantity' => '1',
					'name' => __('Rabatt aufgrund Versandart', 'wpsg'),
					'price' => number_format($arBasket['sum']['preis_shipping_brutto'], 2),
					'currency' => $this->currency
				);
				
				$subTotal += $arBasket['sum']['preis_shipping_brutto'];
				
			}
			
			if (wpsg_isSizedInt($this->shop->get_option('wpsg_mod_paypalapi_paypalexpress_details')))
			{
				
				if (wpsg_isSizedArray($details))
				{
			
					$post_data['transactions'][0]['amount']['details'] = $details;
					$post_data['transactions'][0]['amount']['details']['subtotal'] = number_format($subTotal, 2);
				
				}
				
				$post_data['transactions'][0]['item_list'] = $item_list;
				
			}
			else
			{
				
				$post_data['transactions'][0]['item_list'] = array(
					'items' => array(
						array(
							'quantity' => '1',
							'name' => $this->shop->replaceUniversalPlatzhalter(__($this->shop->get_option('wpsg_mod_paypalapi_paypalexpress_subject'), 'wpsg'), $order_id),
							'price' => number_format($arBasket['sum']['preis_gesamt_brutto'], 2),
							'currency' => $this->currency
						)
					)	
				); 
				
			}
			 
			if (wpsg_isSizedString($this->shop->get_option('wpsg_mod_paypalapi_paymentExperience')))
			{
				
				$post_data['experience_profile_id'] = $this->shop->get_option('wpsg_mod_paypalapi_paymentExperience');
				
			} 
			
			$json_data = $this->api_call('v1/payments/payment', $post_data, $access_token);
			 
			if (wpsg_isSizedString($json_data['id'])) $oOrder->setMeta('wpsg_mod_paypalapi_paymentId', $json_data['id']);
			 
			return $json_data;
			
		} // private function api_startPayment()
		
		/**
		 * Informationen zu einer authorisierten Zahlung holen
		 * @param unknown $payment_id
		 */
		private function api_getPaymentInfo($payment_id, $noError = false)
		{
			
			$json_data = $this->api_call('v1/payments/payment/'.$payment_id, false, $this->api_getAccessToken(), false, $noError);
									
			return $json_data;
			
		} // private function api_getPaymentInfo($payment_id)
		
		/**
		 * Generiert einen Access Token
		 */
		private function api_getAccessToken()
		{
						
			$json_data = $this->api_call('v1/oauth2/token', http_build_query(array('grant_type' => 'client_credentials')));
			
			return $json_data['access_token'];
			
		} // private function api_getAccessToken()
		
		/**
		 * Zentrale Funktion für Anfragen an die API
		 */
		private function api_call($command, $post_data, $auth_token = false, $patch = false, $noError = false, $put = false)
		{
						
			$ch = curl_init();
			
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
			
			if ($this->isSandbox()) curl_setopt($ch, CURLOPT_URL, "https://api.sandbox.paypal.com/".$command);
			else curl_setopt($ch, CURLOPT_URL, "https://api.paypal.com/".$command);
			
			$arHeader = array(
				'Accept: application/json',
				'Accept-Language: de_DE'
			);
			
			if ($auth_token === false)
			{
							
				if ($this->isSandbox())
				{
					
					if (!wpsg_isSizedString($this->shop->get_option('wpsg_mod_paypalapi_sandbox_clientid')) || !wpsg_isSizedString($this->shop->get_option('wpsg_mod_paypalapi_sandbox_secret')))
					{
						
						$this->api_handleError(__('Keine API Daten hinterlegt.', 'wpsg'));
						return;
						
					}
					
					curl_setopt($ch, CURLOPT_USERPWD, $this->shop->get_option('wpsg_mod_paypalapi_sandbox_clientid').':'.$this->shop->get_option('wpsg_mod_paypalapi_sandbox_secret'));
					
				}
				else 
				{
					
					if (!wpsg_isSizedString($this->shop->get_option('wpsg_mod_paypalapi_clientid')) || !wpsg_isSizedString($this->shop->get_option('wpsg_mod_paypalapi_secret')))
					{
					
						$this->api_handleError(__('Keine API Daten hinterlegt.', 'wpsg'));
						return;
						
					}
					
					curl_setopt($ch, CURLOPT_USERPWD, $this->shop->get_option('wpsg_mod_paypalapi_clientid').':'.$this->shop->get_option('wpsg_mod_paypalapi_secret'));
					
				}
				
			}
			else
			{
				
				$arHeader[] = 'Authorization: Bearer '.$auth_token;
				
			}
			
			if ($patch === true)
			{
				
				curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PATCH');
			
			} 
			else if ($put === true)
			{
					
				curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
			
			}
			else if ($post_data !== false)
			{
				
				curl_setopt($ch, CURLOPT_POST, true);
				
			}
			
			if (is_array($post_data))
			{
			
				$arHeader[] = 'Content-Type: application/json';
				 
				$post_data = json_encode($post_data, JSON_UNESCAPED_SLASHES);
 			
			}
			
			if ($post_data !== false) curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
				 
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_HTTPHEADER, $arHeader);			
									
			$output = curl_exec($ch);
			
			if ($auth_token === false && $output == '')
			{
				
				$this->api_handleError(__('API lieferte keinen AUTH Token. Vermutlich fehlerhafte Zugangsdaten.', 'wspg'));
				return;
				
			}
			
			$curl_error = curl_error($ch);
	 
			if (wpsg_isSizedString($curl_error)) $this->api_handleError($curl_error);
			
			curl_close($ch);
 
			$return = json_decode($output, true);
			
			if ($noError === true) return $return;
			
			if (is_array($return) && wpsg_isSizedString($return['error_description'])) $this->api_handleError($return['error_description']);
			
			if (!is_array($return) || wpsg_isSizedString($return['debug_id'])) $this->api_handleError($return);
			
			return $return;
			
		} // private function api_call($command)
		
		/**
		 * Fehlerbehandlung bei API Fehlern
		 */
		private function api_handleError($errorValue)
		{ 
						
			if (is_array($errorValue)) $errorValue = print_r($errorValue, 1);
			
			wpsg_debug($errorValue);
			
			if (wpsg_isSizedInt($_SESSION['wpsg']['order_id']))
			{
					 
				$oOrder = wpsg_order::getInstance($_SESSION['wpsg']['order_id']);
				$oOrder->log('PayPal API Fehler', $errorValue);
				
			}
			else if (wpsg_isSizedInt($_REQUEST['edit_id']))
			{
				
				$oOrder = wpsg_order::getInstance($_REQUEST['edit_id']);
				$oOrder->log('PayPal API Fehler', $errorValue);
				
			}
			
			if (!is_admin()) die();
			
		} // private function api_handleError($errorValue)
		
	} // class wpsg_mod_paypalapi extends wpsg_mod_basic

?>