00001 <?php
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027 class Mage_AmazonPayments_Model_Payment_Cba extends Mage_Payment_Model_Method_Abstract
00028 {
00029
00030
00031
00032
00033
00034 protected $_code = 'amazonpayments_cba';
00035 protected $_formBlockType = 'amazonpayments/cba_form';
00036 protected $_api;
00037
00038 protected $_isGateway = false;
00039 protected $_canAuthorize = true;
00040 protected $_canCapture = false;
00041 protected $_canCapturePartial = false;
00042 protected $_canRefund = true;
00043 protected $_canVoid = false;
00044 protected $_canUseInternal = false;
00045 protected $_canUseCheckout = false;
00046 protected $_canUseForMultishipping = false;
00047
00048
00049
00050
00051 protected $_skipProccessDocument = false;
00052
00053
00054
00055
00056
00057
00058 public function isAvailable($quote=null)
00059 {
00060 return Mage::getStoreConfig('payment/amazonpayments_cba/active');
00061 }
00062
00063
00064
00065
00066
00067
00068 public function getCheckout()
00069 {
00070 return Mage::getSingleton('checkout/session');
00071 }
00072
00073
00074
00075
00076
00077
00078 public function getApi()
00079 {
00080 if (!$this->_api) {
00081 $this->_api = Mage::getSingleton('amazonpayments/api_cba');
00082 $this->_api->setPaymentCode($this->getCode());
00083 }
00084 return $this->_api;
00085 }
00086
00087
00088
00089
00090
00091
00092 public function getSession()
00093 {
00094 return Mage::getSingleton('amazonpayments/session');
00095 }
00096
00097
00098
00099
00100
00101
00102 public function getRedirectUrl()
00103 {
00104 return Mage::getUrl('amazonpayments/cba/redirect');
00105 }
00106
00107
00108
00109
00110
00111
00112 public function getAmazonRedirectUrl()
00113 {
00114 return $this->getApi()->getAmazonRedirectUrl();
00115 }
00116
00117
00118
00119
00120
00121
00122
00123 public function authorize(Varien_Object $payment, $amount)
00124 {
00125 parent::authorize($payment, $amount);
00126 return $this;
00127 }
00128
00129
00130
00131
00132
00133
00134
00135 public function capture(Varien_Object $payment, $amount)
00136 {
00137 parent::capture($payment, $amount);
00138 return $this;
00139 }
00140
00141 public function processInvoice($invoice, $payment)
00142 {
00143 parent::processInvoice($invoice, $payment);
00144 $invoice->addComment(
00145 Mage::helper('amazonpayments')->__('Invoice was created with Checkout by Amazon.')
00146 );
00147 return $this;
00148 }
00149
00150 public function cancel(Varien_Object $payment)
00151 {
00152 if ($this->_skipProccessDocument) {
00153 return $this;
00154 }
00155 $this->getApi()->cancel($payment->getOrder());
00156 $payment->getOrder()->addStatusToHistory(
00157 $payment->getOrder()->getStatus(),
00158 Mage::helper('amazonpayments')->__('Order was canceled with Checkout by Amazon.')
00159 );
00160 return $this;
00161 }
00162
00163
00164
00165
00166
00167
00168
00169 public function refund(Varien_Object $payment, $amount)
00170 {
00171 if ($this->_skipProccessDocument) {
00172 return $this;
00173 }
00174 $this->getApi()->refund($payment, $amount);
00175 $payment->getCreditmemo()->addComment(
00176 Mage::helper('amazonpayments')->__('Refund was created with Checkout by Amazon.')
00177 );
00178 return $this;
00179 }
00180
00181
00182
00183
00184
00185 public function handleCallback($_request)
00186 {
00187 $response = '';
00188
00189 if (!empty($_request['order-calculations-request'])) {
00190 $xmlRequest = urldecode($_request['order-calculations-request']);
00191
00192 $session = $this->getCheckout();
00193 $xml = $this->getApi()->handleXmlCallback($xmlRequest, $session);
00194
00195 if ($this->getDebug()) {
00196 $debug = Mage::getModel('amazonpayments/api_debug')
00197 ->setRequestBody(print_r($_request, 1))
00198 ->setResponseBody(time().' - request callback')
00199 ->save();
00200 }
00201
00202 if ($xml) {
00203 $xmlText = $xml->asXML();
00204 $response .= 'order-calculations-response='.urlencode($xmlText);
00205 #$response .= 'order-calculations-response='.base64_encode($xmlText);
00206
00207 $secretKeyID = Mage::getStoreConfig('payment/amazonpayments_cba/secretkey_id');
00208
00209 $_signature = $this->getApi()->calculateSignature($xmlText, $secretKeyID);
00210
00211 if ($_signature) {
00212 $response .= '&Signature='.urlencode($_signature);
00213 #$response .= '&Signature='.$_signature;
00214 }
00215 $response .= '&aws-access-key-id='.urlencode(Mage::getStoreConfig('payment/amazonpayments_cba/accesskey_id'));
00216
00217 if ($this->getDebug()) {
00218 $debug = Mage::getModel('amazonpayments/api_debug')
00219 ->setResponseBody($response)
00220 ->setRequestBody(time() .' - response calllback')
00221 ->save();
00222 }
00223 }
00224 } else {
00225 if ($this->getDebug()) {
00226 $debug = Mage::getModel('amazonpayments/api_debug')
00227 ->setRequestBody(print_r($_request, 1))
00228 ->setResponseBody(time().' - error request callback')
00229 ->save();
00230 }
00231 }
00232 return $response;
00233 }
00234
00235 public function handleNotification($_request)
00236 {
00237 if (!empty($_request) && !empty($_request['NotificationData']) && !empty($_request['NotificationType'])) {
00238
00239
00240
00241 if ($this->getDebug()) {
00242 $debug = Mage::getModel('amazonpayments/api_debug')
00243 ->setRequestBody(print_r($_request, 1))
00244 ->setResponseBody(time().' - Notification: '. $_request['NotificationType'])
00245 ->save();
00246 }
00247 switch ($_request['NotificationType']) {
00248 case 'NewOrderNotification':
00249 $newOrderDetails = $this->getApi()->parseOrder($_request['NotificationData']);
00250 $this->_createNewOrder($newOrderDetails);
00251 break;
00252 case 'OrderReadyToShipNotification':
00253 $orderReadyToShipDetails = $this->getApi()->parseOrder($_request['NotificationData']);
00254 $this->_proccessOrder($orderReadyToShipDetails);
00255 break;
00256 case 'OrderCancelledNotification':
00257 $cancelDetails = $this->getApi()->parseCancelNotification($_request['NotificationData']);
00258 $this->_skipProccessDocument = true;
00259 $this->_cancelOrder($cancelDetails);
00260 $this->_skipProccessDocument = false;
00261 break;
00262 default:
00263
00264 }
00265 } else {
00266 if ($this->getDebug()) {
00267 $debug = Mage::getModel('amazonpayments/api_debug')
00268 ->setRequestBody(print_r($_request, 1))
00269 ->setResponseBody(time().' - error request callback')
00270 ->save();
00271 }
00272 }
00273 return $this;
00274 }
00275
00276
00277
00278
00279
00280
00281 protected function _createNewOrder(array $newOrderDetails)
00282 {
00283
00284 if (array_key_exists('amazonOrderID', $newOrderDetails)) {
00285 $_order = Mage::getModel('sales/order')
00286 ->loadByAttribute('ext_order_id', $newOrderDetails['amazonOrderID']);
00287 if ($_order->getId()) {
00288
00289
00290
00291 $this->getApi()->syncOrder($_order);
00292 $_order = null;
00293 return $this;
00294 }
00295 $_order = null;
00296 }
00297 $session = $this->getCheckout();
00298
00299 #$quoteId = $session->getAmazonQuoteId();
00300
00301 $quoteId = $newOrderDetails['ClientRequestId'];
00302 $quote = Mage::getModel('sales/quote')->load($quoteId);
00303
00304 $baseCurrency = $session->getQuote()->getBaseCurrencyCode();
00305 $currency = Mage::app()->getStore($session->getQuote()->getStoreId())->getBaseCurrency();
00306
00307 $shipping = $quote->getShippingAddress();
00308 $billing = $quote->getBillingAddress();
00309
00310 $_address = $newOrderDetails['shippingAddress'];
00311 $this->_address = $_address;
00312
00313 $regionModel = Mage::getModel('directory/region')->loadByCode($_address['regionCode'], $_address['countryCode']);
00314 $_regionId = $regionModel->getId();
00315
00316 $sName = explode(' ', $newOrderDetails['shippingAddress']['name']);
00317 $sFirstname = isset($sName[0])?$sName[0]:'';
00318 $sLastname = isset($sName[1])?$sName[1]:'';
00319
00320 $bName = explode(' ', $newOrderDetails['buyerName']);
00321 $bFirstname = isset($bName[0])?$bName[0]:'';
00322 $bLastname = isset($bName[1])?$bName[1]:'';
00323
00324 $shipping->setCountryId($_address['countryCode'])
00325 ->setRegion($_address['regionCode'])
00326 ->setRegionId($_regionId)
00327 ->setCity($_address['city'])
00328 ->setStreet($_address['street'])
00329 ->setPostcode($_address['postCode'])
00330 ->setTaxAmount($newOrderDetails['tax'])
00331 ->setBaseTaxAmount($newOrderDetails['tax'])
00332 ->setShippingAmount($newOrderDetails['shippingAmount'])
00333 ->setBaseShippingAmount($newOrderDetails['shippingAmount'])
00334 ->setShippingTaxAmount($newOrderDetails['shippingTax'])
00335 ->setBaseShippingTaxAmount($newOrderDetails['shippingTax'])
00336 ->setDiscountAmount($newOrderDetails['discount'])
00337 ->setBaseDiscountAmount($newOrderDetails['discount'])
00338 ->setSubtotal($newOrderDetails['subtotal'])
00339 ->setBaseSubtotal($newOrderDetails['subtotal'])
00340 ->setGrandTotal($newOrderDetails['total'])
00341 ->setBaseGrandTotal($newOrderDetails['total'])
00342 ->setFirstname($sFirstname)
00343 ->setLastname($sLastname);
00344
00345 $_shippingDesc = '';
00346 $_shippingServices = unserialize($quote->getExtShippingInfo());
00347 if (is_array($_shippingServices) && array_key_exists('amazon_service_level', $_shippingServices)) {
00348 foreach ($_shippingServices['amazon_service_level'] as $_level) {
00349 if ($_level['service_level'] == $newOrderDetails['ShippingLevel']) {
00350 $shipping->setShippingMethod($_level['code']);
00351 $_shippingDesc = $_level['description'];
00352 }
00353 }
00354 }
00355
00356 $billing->setCountryId($_address['countryCode'])
00357 ->setRegion($_address['regionCode'])
00358 ->setRegionId($_regionId)
00359 ->setCity($_address['city'])
00360 ->setStreet($_address['street'])
00361 ->setPostcode($_address['postCode'])
00362 ->setTaxAmount($newOrderDetails['tax'])
00363 ->setBaseTaxAmount($newOrderDetails['tax'])
00364 ->setShippingAmount($newOrderDetails['shippingAmount'])
00365 ->setBaseShippingAmount($newOrderDetails['shippingAmount'])
00366 ->setShippingTaxAmount($newOrderDetails['shippingTax'])
00367 ->setBaseShippingTaxAmount($newOrderDetails['shippingTax'])
00368 ->setDiscountAmount($newOrderDetails['discount'])
00369 ->setBaseDiscountAmount($newOrderDetails['discount'])
00370 ->setSubtotal($newOrderDetails['subtotal'])
00371 ->setBaseSubtotal($newOrderDetails['subtotal'])
00372 ->setGrandTotal($newOrderDetails['total'])
00373 ->setBaseGrandTotal($newOrderDetails['total'])
00374 ->setFirstname($bFirstname)
00375 ->setLastname($bLastname);
00376
00377 $quote->setBillingAddress($billing);
00378 $quote->setShippingAddress($shipping);
00379
00380 $billing = $quote->getBillingAddress();
00381 $shipping = $quote->getShippingAddress();
00382
00383 $convertQuote = Mage::getModel('sales/convert_quote');
00384
00385 $order = Mage::getModel('sales/order');
00386
00387
00388 $order = $convertQuote->addressToOrder($billing);
00389
00390
00391 $order->setBillingAddress($convertQuote->addressToOrderAddress($billing))
00392 ->setShippingAddress($convertQuote->addressToOrderAddress($shipping));
00393
00394 $order->setShippingMethod($shipping->getShippingMethod())
00395 ->setShippingDescription($_shippingDesc)
00396 ->setForcedDoShipmentWithInvoice(true);
00397
00398 $order->setPayment($convertQuote->paymentToOrderPayment($quote->getPayment()));
00399
00400
00401
00402
00403 $order->setExtOrderId($newOrderDetails['amazonOrderID']);
00404
00405
00406 foreach ($quote->getAllItems() as $item) {
00407
00408 $order->addItem($convertQuote->itemToOrderItem($item));
00409
00410 $orderItem = $order->getItemByQuoteItemId($item->getId());
00411 $orderItem->setExtOrderItemId($newOrderDetails['items'][$item->getId()]['AmazonOrderItemCode']);
00412 $orderItemOptions = $orderItem->getProductOptions();
00413 $orderItemOptions['amazon_amounts'] = serialize(array(
00414 'shipping' => $newOrderDetails['items'][$item->getId()]['shipping'],
00415 'tax' => $newOrderDetails['items'][$item->getId()]['tax'],
00416 'shipping_tax' => $newOrderDetails['items'][$item->getId()]['shipping_tax'],
00417 'principal_promo' => $newOrderDetails['items'][$item->getId()]['principal_promo'],
00418 'shipping_promo' => $newOrderDetails['items'][$item->getId()]['shipping_promo']
00419 ));
00420 $orderItem->setProductOptions($orderItemOptions);
00421 $orderItem->setLockedDoInvoice(true)
00422 ->setLockedDoShip(true);
00423 }
00424
00425 $order->place();
00426
00427 $order->addStatusToHistory(
00428 $order->getStatus(),
00429 Mage::helper('amazonpayments')->__('New Order Notification received from Checkout by Amazon service.')
00430 );
00431
00432 $customer = $quote->getCustomer();
00433 if ($customer && $customer->getId()) {
00434 $order->setCustomerId($customer->getId())
00435 ->setCustomerEmail($customer->getEmail())
00436 ->setCustomerPrefix($customer->getPrefix())
00437 ->setCustomerFirstname($customer->getFirstname())
00438 ->setCustomerMiddlename($customer->getMiddlename())
00439 ->setCustomerLastname($customer->getLastname())
00440 ->setCustomerSuffix($customer->getSuffix())
00441 ->setCustomerGroupId($customer->getGroupId())
00442 ->setCustomerTaxClassId($customer->getTaxClassId());
00443 } else {
00444 $quote->setCustomerEmail($newOrderDetails['buyerEmailAddress'])
00445 ->setCustomerIsGuest(true)
00446 ->setCustomerGroupId(Mage_Customer_Model_Group::NOT_LOGGED_IN_ID);
00447 }
00448
00449 $quote->setIsActive(false);
00450 $quote->save();
00451
00452 $orderId = $order->getIncrementId();
00453 $this->getCheckout()->setLastQuoteId($quote->getId());
00454 $this->getCheckout()->setLastSuccessQuoteId($quote->getId());
00455 $this->getCheckout()->setLastOrderId($order->getId());
00456 $this->getCheckout()->setLastRealOrderId($order->getIncrementId());
00457
00458 $order->sendNewOrderEmail();
00459
00460
00461
00462 $this->getApi()->syncOrder($order);
00463 return $this;
00464 }
00465
00466
00467
00468
00469
00470
00471
00472 protected function _proccessOrder($amazonOrderDetails)
00473 {
00474 if (array_key_exists('amazon_order_id', $amazonOrderDetails)) {
00475 $order = Mage::getModel('sales/order')
00476 ->loadByAttribute('ext_order_id', $amazonOrderDetails['amazon_order_id']);
00477
00478 if ($order->getId()) {
00479
00480 foreach ($order->getAllVisibleItems() as $item) {
00481 if (array_key_exists($item->getExtOrderItemId(), $amazonOrderDetails['items'])) {
00482 $item->setLockedDoInvoice(false)
00483 ->setLockedDoShip(false)
00484 ->save();
00485 }
00486 }
00487 $order->addStatusToHistory(
00488 $order->getStatus(),
00489 Mage::helper('amazonpayments')->__('Order Ready To Ship Notification received form Checkout by Amazon service.')
00490 )->save();
00491 }
00492 }
00493 return true;
00494 }
00495
00496
00497
00498
00499
00500
00501
00502 protected function _cancelOrder($cancelDetails)
00503 {
00504 if (array_key_exists('amazon_order_id', $cancelDetails)) {
00505 $order = Mage::getModel('sales/order')
00506 ->loadByAttribute('ext_order_id', $cancelDetails['amazon_order_id']);
00507
00508 if ($order->getId()) {
00509 try {
00510 $order->cancel()
00511 ->addStatusToHistory(
00512 $order->getStatus(),
00513 Mage::helper('amazonpayments')->__('Cancel Order Notification received from Checkout by Amazon service.')
00514 )->save();
00515 } catch (Exception $e) {
00516 return false;
00517 }
00518 }
00519 }
00520 return true;
00521 }
00522
00523
00524
00525
00526
00527
00528
00529
00530 public function callbackXmlError(Exception $e)
00531 {
00532 $_xml = $this->getApi()->callbackXmlError($e);
00533 $secretKeyID = Mage::getStoreConfig('payment/amazonpayments_cba/secretkey_id');
00534 $_signature = $this->getApi()->calculateSignature($_xml->asXml(), $secretKeyID);
00535
00536 $response = 'order-calculations-response='.urlencode($_xml->asXML())
00537 .'&Signature='.urlencode($_signature)
00538 .'&aws-access-key-id='.urlencode(Mage::getStoreConfig('payment/amazonpayments_cba/accesskey_id'));
00539 return $response;
00540 }
00541
00542
00543
00544
00545
00546
00547 public function getCheckoutXmlFormFields()
00548 {
00549 $secretKeyID = Mage::getStoreConfig('payment/amazonpayments_cba/secretkey_id');
00550 $_quote = $this->getCheckout()->getQuote();
00551
00552 $xml = $this->getApi()->getXmlCart($_quote);
00553
00554 $xmlCart = array('order-input' =>
00555 "type:merchant-signed-order/aws-accesskey/1;"
00556 ."order:".base64_encode($xml).";"
00557 ."signature:{$this->getApi()->calculateSignature($xml, $secretKeyID)};"
00558 ."aws-access-key-id:".Mage::getStoreConfig('payment/amazonpayments_cba/accesskey_id')
00559 );
00560 if ($this->getDebug()) {
00561 $debug = Mage::getModel('amazonpayments/api_debug')
00562 ->setResponseBody(print_r($xmlCart, 1)."\norder:".$xml)
00563 ->setRequestBody(time() .' - xml cart')
00564 ->save();
00565 }
00566 return $xmlCart;
00567 }
00568
00569
00570
00571
00572
00573 public function returnAmazon()
00574 {
00575 $_request = Mage::app()->getRequest()->getParams();
00576 #$_amazonOrderId = Mage::app()->getRequest()->getParam('amznPmtsOrderIds');
00577 #$_quoteId = Mage::app()->getRequest()->getParam('amznPmtsReqId');
00578
00579 if ($this->getDebug()) {
00580 $debug = Mage::getModel('amazonpayments/api_debug')
00581 ->setRequestBody(print_r($_request, 1))
00582 ->setResponseBody(time().' - success')
00583 ->save();
00584 }
00585 }
00586
00587
00588
00589
00590
00591
00592 public function isInitializeNeeded()
00593 {
00594 return false;
00595 }
00596
00597
00598
00599
00600
00601
00602 public function getDebug()
00603 {
00604 return Mage::getStoreConfig('payment/' . $this->getCode() . '/debug_flag');
00605 }
00606 }