PayPal IPN with CodeIgniter - php

I am trying to implement a membership subscription service on a website built in CodeIgniter. I wish to use PayPal to manage payments, and am having a very hard time implementing this.
What I am trying to achieve is:
User fills in a membership form with
personal details
User selects a
subscription option (1 of 8 choices - each different price) and submits form
User is sent to PayPal to pay
User is returned to site upon successful payment and personal details are stored in database which creates user account (membership).
There is also the addition of form validation, I use the form_validation helper in CodeIgniter, but this needs to be done before PayPal payment can commence.
I have attempted to implement the PayPal_Lib from Ran Aroussi, but I feel it has not enough clear documentation or guidance on it. Any implemented examples or advice would be much appreciated.
Lucas

I found Ran's library a little hard to use too so I've written a replacement - which also has the benefit of performing more checks on the transaction, and logging the IPN call and the order details in your database. Here's the library on GitHub, I hope you find it useful:
https://github.com/orderly/codeigniter-paypal-ipn

Below is the unmodified code that i used with Ran's library.
Hope it helps.
<?php
/**
* PayPal_Lib Controller Class (Paypal IPN Class)
*
* Paypal controller that provides functionality to the creation for PayPal forms,
* submissions, success and cancel requests, as well as IPN responses.
*
* The class requires the use of the PayPal_Lib library and config files.
*
* #package CodeIgniter
* #subpackage Libraries
* #category Commerce
* #author Ran Aroussi <ran#aroussi.com>
* #copyright Copyright (c) 2006, http://aroussi.com/ci/
*
*/
class Paypal extends Controller
{
function Paypal()
{
parent::Controller();
$this->load->library('Paypal_Lib');
}
function index()
{
$this->form();
}
function form()
{
$this->paypal_lib->add_field('business', 'herrka_1245670546_biz#pandorascode.com');
$this->paypal_lib->add_field('return', site_url('paypal/success') );
$this->paypal_lib->add_field('cancel_return', site_url('paypal/cancel') );
$this->paypal_lib->add_field('notify_url', site_url('paypal/ipn') ); // <-- IPN url
$this->paypal_lib->add_field('custom', '470874552'); // <-- Verify return
$this->paypal_lib->add_field('item_name', 'Paypal Test Transaction');
$this->paypal_lib->add_field('item_number', '5');
$this->paypal_lib->add_field('amount', '9.95');
// if you want an image button use this:
$this->paypal_lib->image('button_03.gif');
// otherwise, don't write anything or (if you want to
// change the default button text), write this:
// $this->paypal_lib->button('Click to Pay!');
$data['paypal_form'] = $this->paypal_lib->paypal_form();
$this->load->view('paypal/form', $data);
}
function cancel()
{
$this->load->view('paypal/cancel');
}
function success()
{
//$data['pp_info'] = $this->input->post();
$data['pp_info'] = $_POST; //FIX?
$this->load->view('paypal/success', $data);
}
function ipn()
{
$ipn_valid = $this->paypal_lib->validate_ipn();
if ( $ipn_valid == TRUE )
{
/**
Log IPN
TODO: bunu daha guzel gozukecek sekilde yapayim ilerde.
**/
date_default_timezone_set('Europe/Istanbul');
$this->load->helper('date');
$raw = '';
foreach ($this->paypal_lib->ipn_data as $key=>$value)
{
$raw .= "\n$key: $value";
}
$this->load->model('model_paypal');
$data_ipn['user_id'] = $this->paypal_lib->ipn_data['custom']; /* get USER_ID from custom field. */
$data_ipn['txn_id'] = $this->paypal_lib->ipn_data['txn_id'];
$data_ipn['payment_status'] = $this->paypal_lib->ipn_data['payment_status'];
$data_ipn['mc_gross'] = $this->paypal_lib->ipn_data['mc_gross'];
$data_ipn['mc_fee'] = $this->paypal_lib->ipn_data['mc_fee'];
$data_ipn['mc_currency'] = $this->paypal_lib->ipn_data['mc_currency'];
$data_ipn['item_number'] = $this->paypal_lib->ipn_data['item_number'];
$data_ipn['datetime'] = mdate( "%Y-%m-%d %H:%i:%s" );
$data_ipn['status'] = IPN_ENTRY_AWAITING;
$data_ipn['raw'] = $raw;
$this->model_paypal->ipn_entry_add ( $data_ipn );
$ipn_payment_status = $this->paypal_lib->ipn_data['payment_status'];
if ( strtolower($ipn_payment_status) == 'pending' )
{
log_message('debug', 'payment status TAMAM');
$this->load->model('model_user_premium');
$ipn_item_number = $this->paypal_lib->ipn_data['item_number'];
$item_info = $this->model_user_premium->Premium_item_info ( $ipn_item_number );
$ipn_mc_gross = $this->paypal_lib->ipn_data['mc_gross'];
log_message('debug', 'Item fee: '. $item_info['item_fee'] );
if ( $item_info['item_fee'] == $ipn_mc_gross )
{
log_message('debug', 'fee ile gross TAMAM');
$data_account['user_id'] = $data_ipn['user_id'];
$data_account['type'] = $item_info['item_type'];
$data_account['date_expire'] = date("Y-m-d", mktime(0, 0, 0, date("m") + $item_info['date_extender'], date("d"), date("y") ) );
log_message('debug', 'UserID: '. $data_account['user_id'] );
log_message('debug', 'Type:'. $data_account['type'] );
log_message('debug', 'Expire:'. $data_account['date_expire'] );
$this->model_user_premium->Premium_membership_change( $data_ipn['user_id'], $data_account );
}
else
{
//TODO: report eksik transaction.
}
}
}
elseif ( $ipn_valid == FALSE )
{
$this->load->library('email');
$this->email->to( 'demo#demo.com' );
$this->email->subject('IPN - FAILED');
$this->email->from( 'notify#bulusturx.com', 'PAYPAL' );
$this->email->message('or 4 life');
$this->email->send();
}
}
function ipn_list()
{
//TODO: admin check
$this->load->helper('form');
$this->load->model('model_theme');
switch ( $_SERVER['REQUEST_METHOD'] )
{
case 'GET':
/* Theme System with Reference Variable ( first param ) */
$this->model_theme->Theme_returnThemeInfo( $data, 'paypal' );
$this->load->view( $data['theme_folder_vault'] . 'master-ipn_list', $data );
break;
case 'POST':
$this->load->model('model_paypal');
$user_id = $this->input->post('user_id');
$txn_id = $this->input->post('txn_id');
$list_ipn = $this->model_paypal->ipn_entry_list ( $user_id, $txn_id );
echo '<pre>';
print_r( $list_ipn );
echo '</pre>';
break;
default:
break;
}
}
function ipn_test()
{
$this->load->model('model_user_premium');
$data_account['user_id'] = 123;
$data_account['type'] = 4;
$data_account['date_expire'] = date("Y-m-d", mktime(0, 0, 0, date("m") + 12, date("d"), date("y") ) );
echo '<pre>';
print_r( $data_account );
echo '</pre>';
$this->model_user_premium->Premium_membership_change( 123, $data_account );
}
}
?>

Here's a paypal library from Jamie Rumbelow that I've been using with minor tweaks:
http://bitbucket.org/jamierumbelow/codeigniter-paypal/src

Related

How to create order in magento programmatically with paypal payment method

How to create order in magento programmatically with paypal payment method.
We have implemented code for COD method or Check/Money order payment methods, now I need to implement payment, I searched alot but didn't found any answer, is there a proper way for this ?
first of all paypal is payment getaway which need authentication .
but you can try this code
file here : app/code/core/Mage/Paypal/Model/Express.php
function code here :
public function order(Varien_Object $payment, $amount)
{
$this->_placeOrder($payment, $amount);
$payment->setAdditionalInformation($this->_isOrderPaymentActionKey, true);
if ($payment->getIsFraudDetected()) {
return $this;
}
$order = $payment->getOrder();
$orderTransactionId = $payment->getTransactionId();
$api = $this->_callDoAuthorize($amount, $payment, $payment->getTransactionId());
$state = Mage_Sales_Model_Order::STATE_PROCESSING;
$status = true;
$formatedPrice = $order->getBaseCurrency()->formatTxt($amount);
if ($payment->getIsTransactionPending()) {
$message = Mage::helper('paypal')->__('Ordering amount of %s is pending approval on gateway.', $formatedPrice);
$state = Mage_Sales_Model_Order::STATE_PAYMENT_REVIEW;
} else {
$message = Mage::helper('paypal')->__('Ordered amount of %s.', $formatedPrice);
}
$payment->addTransaction(Mage_Sales_Model_Order_Payment_Transaction::TYPE_ORDER, null, false, $message);
$this->_pro->importPaymentInfo($api, $payment);
if ($payment->getIsTransactionPending()) {
$message = Mage::helper('paypal')->__('Authorizing amount of %s is pending approval on gateway.', $formatedPrice);
$state = Mage_Sales_Model_Order::STATE_PAYMENT_REVIEW;
if ($payment->getIsFraudDetected()) {
$status = Mage_Sales_Model_Order::STATUS_FRAUD;
}
} else {
$message = Mage::helper('paypal')->__('Authorized amount of %s.', $formatedPrice);
}
$payment->resetTransactionAdditionalInfo();
$payment->setTransactionId($api->getTransactionId());
$payment->setParentTransactionId($orderTransactionId);
$transaction = $payment->addTransaction(Mage_Sales_Model_Order_Payment_Transaction::TYPE_AUTH, null, false,
$message
);
$order->setState($state, $status);
$payment->setSkipOrderProcessing(true);
return $this;
}
you can customize this code as per you basic requirement
and let me know if you have any issue

Codeigniter - digital goods paypal library subscription response null

I am working on a subscription system web, I am using Paypal Digital Goods Classes (https://github.com/thenbrent/paypal-digital-goods), and made a custom library called paypal2
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Paypal2
{
public function DatosPaypal($arreglo = array(), $produccion)
{
if (count($arreglo)>0)
{
$idCliente = $arreglo['idcliente'];
$descripcion = $arreglo['descripcion'];
$precio = $arreglo['precio'];
$pagado = $arreglo['pagado'];
$cancelado = $arreglo['cancelado'];
$notificar = $arreglo['notificar'];
$moneda = $arreglo['moneda'];
$usuario = $arreglo['usuario'];
$clave = $arreglo['clave'];
$llave = $arreglo['llave'];
if (!class_exists('PayPal_Digital_Goods',false))
{
require_once APPPATH.'third_party/paypal/paypal-digital-goods.class.php';
if ($produccion == true) {
PayPal_Digital_Goods_Configuration::environment( 'live' );
}
PayPal_Digital_Goods_Configuration::username( $usuario );
PayPal_Digital_Goods_Configuration::password( $clave );
PayPal_Digital_Goods_Configuration::signature( $llave );
PayPal_Digital_Goods_Configuration::return_url( $pagado );
PayPal_Digital_Goods_Configuration::cancel_url( $cancelado );
PayPal_Digital_Goods_Configuration::notify_url( $notificar );
PayPal_Digital_Goods_Configuration::currency( $moneda ); // 3 char character code, must be one of the values here: https://developer.paypal.com/docs/classic/api/currency_codes/
if (!class_exists('PayPal_Subscription', false))
{
require_once APPPATH.'third_party/paypal/paypal-subscription.class.php';
$subscription_details = array(
'description' => $descripcion,
'initial_amount' => $precio,
'amount' => $precio,
'period' => 'Month',
'frequency' => '1',
'total_cycles' => '0',
'user_id' => $idCliente
);
$paypal_subscription = new PayPal_Subscription( $subscription_details );
$respuesta = $paypal_subscription;
return $respuesta;
}
}
}
else
{
return "ERROR";
}
}
}
And here is the controller functions that made the payment possible
function AjaxPagoSubscripcion($plan) //<-Works great
{
$this->load->library('paypal2');
$this->load->model('Usuarios_model');
$this->config->load('PayPal2');
$arreglo = $this->Usuarios_model->DatosPagoSubscripcion($plan);
$PaypalObject = $this->paypal2->DatosPaypal($arreglo, $this->config->config['PPproduction_mode']);
$this->config->set_item('PayPalObject', $PaypalObject);
$data['PayPal'] = $PaypalObject->print_buy_button();
$this->load->view('usuarios/pruebas');
}
function pagos2() //<-Don't know how to get the paypal response or migrate Paypal object
{
$allvariables = get_defined_vars();
$data["Variables"] = $allvariables;
$this->load->view('paypal/pagado');
}
It works great until the subsciption/payment is done, I don't know how to get the paypal response or to migrate the paypal object between controllers, any help would be really appreciated.
UPDATE
I made some changes, and some progress, but now it gives me this error
( ! ) Fatal error: Uncaught exception 'Exception' with message 'Calling PayPal with action CreateRecurringPaymentsProfile has Failed: Profile description is invalid' in G:\wamp\www\serviciosycomprasx\application\third_party\paypal\paypal-digital-goods.class.php on line 224
( ! ) Exception: Calling PayPal with action CreateRecurringPaymentsProfile has Failed: Profile description is invalid in G:\wamp\www\serviciosycomprasx\application\third_party\paypal\paypal-digital-goods.class.php on line 224
And here is the controller which accepts the payment (where the erro triggers obvious :D )
public function pagado($plan)
{
$this->load->library('paypal2');
$this->load->model('Usuarios_model');
$this->config->load('PayPal2');
$arreglo = $this->Usuarios_model->DatosPagoSubscripcion($plan);
//echo $arreglo->precio;
//echo "<pre>",print_r($arreglo),"</pre>"; exit();
$PaypalObject = $this->paypal2->DatosPaypal($arreglo, $this->config->config['PPproduction_mode']);
$prueba = $PaypalObject->start_subscription();
echo "<pre>",print_r($prueba),"</pre>"; exit();
//$data['PayPal'] = $prueba;
//$data['main_content'] = 'paypal/pagado';
//$this->load->view('includes/'.$this->config->config["tema"].'/template' , $data);
}
I finally did it, using the code inside the views, is not how is to be done, but worked finally

VirtueMart duplicate orders

I'm currently developing a payment plugin for VirtueMart. I have never used it before. The goal is:
When the user clicks to the confirm order button, he gets redirected to the bank interface (managed it, no work needed)
He then gets redirected back to the webshop with an answer from the bank (also done)
If the transaction is success, the order is stored as confirmed or if the transaction fails, the order is getting cancelled.
What I managed, is marked in the list above. For some reason, the order gets stored twice as pending, once when the user clicks the button, and once when the user gets redirected back to the shop. Also, if the transaction fails, the order is stored twice, also pending. I reused the standard payment plugin given with the VirtueMart aio package. All the above stuff is written in the plgVmConfirmedOrder function. I would post it here:
function plgVmConfirmedOrder ($cart, $order) {
if (!($method = $this->getVmPluginMethod ($order['details']['BT']->virtuemart_paymentmethod_id))) {
return NULL; // Another method was selected, do nothing
}
if (!$this->selectedThisElement ($method->payment_element)) {
return FALSE;
}
VmConfig::loadJLang('com_virtuemart',true);
VmConfig::loadJLang('com_virtuemart_orders', TRUE);
if (!class_exists ('VirtueMartModelOrders')) {
require(VMPATH_ADMIN . DS . 'models' . DS . 'orders.php');
}
$this->getPaymentCurrency($method);
$currency_code_3 = shopFunctions::getCurrencyByID($method->payment_currency, 'currency_code_3');
$email_currency = $this->getEmailCurrency($method);
$totalInPaymentCurrency = vmPSPlugin::getAmountInCurrency($order['details']['BT']->order_total,$method->payment_currency);
$dbValues['payment_name'] = $this->renderPluginName ($method) . '<br />' . $method->payment_info;
$dbValues['order_number'] = $order['details']['BT']->order_number;
$dbValues['virtuemart_paymentmethod_id'] = $order['details']['BT']->virtuemart_paymentmethod_id;
$dbValues['cost_per_transaction'] = $method->cost_per_transaction;
$dbValues['cost_percent_total'] = $method->cost_percent_total;
$dbValues['payment_currency'] = $currency_code_3;
$dbValues['email_currency'] = $email_currency;
$dbValues['payment_order_total'] = $totalInPaymentCurrency['value'];
$dbValues['tax_id'] = $method->tax_id;
$payment_info='';
if (!empty($method->payment_info)) {
$lang = JFactory::getLanguage ();
if ($lang->hasKey ($method->payment_info)) {
$payment_info = vmText::_ ($method->payment_info);
} else {
$payment_info = $method->payment_info;
}
}
if (!class_exists ('VirtueMartModelCurrency')) {
require(VMPATH_ADMIN . DS . 'models' . DS . 'currency.php');
}
$currency = CurrencyDisplay::getInstance ('', $order['details']['BT']->virtuemart_vendor_id);
if(!array_key_exists("fizetesValasz", $_REQUEST)){
$transaction_id = $this->getTransactionID();
$_REQUEST['tranzakcioAzonosito'] = $transaction_id;
$price = $cart->cartPrices['billTotal'];
$_REQUEST['osszeg'] = round($price);
$_REQUEST['devizanem'] = 'HUF';
$_REQUEST['backURL'] = "http://" . $_SERVER['SERVER_NAME'] . '/component/virtuemart/cart/confirm.html?Itemid=' . $_REQUEST['Itemid'];
$_REQUEST['nyelvkod'] = 'hu';
$dbValues['transaction_id'] = $transaction_id;
//this is where I redirect to the bank interface
process();
}
else{
//this is where I get the data about transaction
$transaction_datas = processDirectedToBackUrl(false);
$status_code = $transaction_datas->getStatuszKod();
$dbValues['otp_response'] = $status_code;
$this->storePSPluginInternalData ($dbValues);
$modelOrder = VmModel::getModel ('orders');
switch ($status_code) {
case 'FELDOLGOZVA':
if($transaction_datas->isSuccessful()){
$message = 'Sikeres Tranzakció!';
$new_status = $this->getNewStatus($method);
$order['customer_notified'] = 1;
$order['comments'] = '';
$modelOrder->updateStatusForOneOrder ($order['details']['BT']->virtuemart_order_id, $order, TRUE);
$message = getMessageText(($transaction_datas->getPosValaszkod()));
$cart->emptyCart();
$html = $this->renderByLayout('post_payment_success', array(
'message' =>$message,
'order_number' =>$order['details']['BT']->order_number,
'order_pass' =>$order['details']['BT']->order_pass,
'payment_name' => $dbValues['payment_name'],
'displayTotalInPaymentCurrency' => round($totalInPaymentCurrency['display'])
));
vRequest::setVar ('html', $html);
return TRUE;
}
else{
$new_status = $method->status_cancelled;
$modelOrder->updateStatusForOneOrder($order['details']['BT']->virtuemart_order_id, $order, TRUE);
$message = 'Sajnos a bank visszautasította a tranzakciót.';
$html = $this->renderByLayout('post_payment_failure', array(
'message' => $message
));
vRequest::setVar('html', $html);
return FALSE;
}
break;
case 'VEVOOLDAL_VISSZAVONT':
return FALSE;
break;
case 'VEVOOLDAL_TIMEOUT':
return FALSE;
break;
}
}
return FALSE;
}
Every help is appreciated. Thanks in advance!
So, the problem was the redirect url. There is an action called plgVmOnPaymentResponseReceived(). This is fired when a specific url is called. I only had to rewrite the $_REQUEST parameter for the redirection.

How to use alphauserpoints credits towards adsmanager payment in joomla?

Are there any plugins or hacks that let me use alphauserpoints credits towards payments for adsmanager adverts in joomla?
Here is my solution for Alphauserpoints 1.7.4, Adsmanager 2.7 RC3 and PaidSystem.
Edit components\com_paidsystem\api.paidsystem.php
After defined('_JEXEC') or die( 'Restricted access' ); add the below code
//AlphaUserPoints start
$api_AUP = JPATH_SITE.DS.'components'.DS.'com_alphauserpoints'.DS.'helper.php';
if ( file_exists($api_AUP))
{
require_once ($api_AUP);
}
//AlphaUserPoints end
Next you need to edit function getBalance($userid). This is in api.paidsystem.php
function getBalance($userid)
{
//Alphauserpoints substitute for value
//Get the RefferreID of a user
$referreid = AlphaUserPointsHelper::getAnyUserReferreID((int)$userid);
$profil=AlphaUserPointsHelper:: getUserInfo ($referreid);
$value=$profil->points;
//Alphauserpoints substitute for value end
//ORIGINAL CODE BELOW
/*$db =JFactory::getDbo();
//$db->setQuery( "SELECT credit FROM #__paidsystem_credits WHERE userid=".(int)$userid );
//To explicitly convert a value to integer, use either the (int) or (integer) casts.
$value = $db->loadResult();*/
if ($value == "")
$value = 0;
return $value;
}
Then edit the next function
//EDIT this to debit credits from alphauserpoints
//Use alphauserpoints rule to debit from alphauserpoints.
function removeCredits($userid,$num,$description)
{
$db =JFactory::getDbo();
//$db->setQuery( "SELECT credit FROM #__paidsystem_credits WHERE userid=".(int)$userid );
//$balance = (float) $db->loadResult();
$referreid = AlphaUserPointsHelper::getAnyUserReferreID((int)$userid);
$profil=AlphaUserPointsHelper:: getUserInfo ($referreid);
$balance=$profil->points;
//$db->setQuery( "UPDATE #__paidsystem_credits SET credit=credit-".(float)$num." WHERE userid=".(int)$userid );
//$db->query();
echo "removeCredits=$userid,$num";
$obj = new stdClass();
$obj->userid = $userid;
$obj->balance = $balance;
$obj->change = $num * -1;
$obj->description = $description;
$obj->date = date("Y-m-d H:i:s");
AlphaUserPointsHelper::newpoints( 'plgaup_purchaseadvertising', '','', 'purchase advertising', $num*-1);
$db->insertObject("#__paidsystem_history",$obj);
}
REMEMBER: You will need to create a new rule in the administrator section of the alphauserpoints component in Joomla for this to work. In my code the new rule name was called plgaup_purchaseadvertising.

Magento payment module with Moneris

With the help of https://github.com/ph/magento-moneris I have managed to create a Moneris payment gateway in Magento and I am testing it now with Moneris Development site.
I have got a couple of questions where I am confused and don't know how to proceed.
Is there a way I can set 'Authorize only' to 'Authorize and Capture' some where in the code so that the capture is performed at the same time when the order is placed?
Also Is there a way that the invoicing can be done at the same time as the order is placed with the invoice mail sent to the customer n store owner.
Ex: when the 'Place Order' is clicked, the customer's card details are checked and validated. If they are ok, then the payment is captured at the same time in the merchant's account and the invoice emails are sent to the customer and store owner.
If the card details are not right, then show an appropriate message on front end to the customer as well keep that order as pending with appropriate reason for the store owner to see.
The code I have for now is for _authorize n _capture functions. Do they need to be modified or new functions needs to be created.
public function authorize(Varien_Object $payment, $amount)
{
$error = false;
// check for payment
if($amount > 0) {
$payment->setAmount($amount);
// Map magento keys to moneris way
$order = $payment->getOrder();
$billing = $order->getBillingAddress();
$avsTemplate = array('avs_zipcode' => $order->getBillingAddress()->getPostcode(), 'avs_street_number' => $order->getBillingAddress()->getStreet(1),'', 'avs_street_name' => $order->getBillingAddress()->getStreet(2),'');
$mpgAvsInfo = new mpgAvsInfo($avsTemplate);
$cvdTemplate = array('cvd_value' => $payment->getCcCid(),'cvd_indicator' => 1);
$mpgCvdInfo = new mpgCvdInfo($cvdTemplate);
$transaction = $this->_build($payment, self::TRANSACTION_PREAUTH);
$transaction->setAvsInfo($mpgAvsInfo);
$transaction->setCvdInfo($mpgCvdInfo);
$response = $this->_send($transaction);
$payment->setCcApproval($response->getReceiptId())
->setLastTransId($response->getReceiptId())
->setCcTransId($response->getTxnNumber())
->setCcAvsStatus($response->getAuthCode())
->setCcCidStatus($response->getResponseCode());
if($response->getResponseCode() > 0 && $response->getResponseCode() <= self::ERROR_CODE_LIMIT)
{
$payment->setStatus(self::STATUS_APPROVED);
$message = 'AVS Response: ' . Mage::helper('paygate')->__($this->_errors[$response->getAvsResultCode()]);
$message .= '<br>CVD Response: ' . Mage::helper('paygate')->__($this->_errors[$response->getCvdResultCode()]);
Mage::getSingleton('core/session')->addSuccess($message);
}
else if($response->getResponseCode() > self::ERROR_CODE_LIMIT && $response->getResponseCode() < self::ERROR_CODE_UPPER_LIMIT)
{
$error = Mage::helper('paygate')->__($this->_errors[$response->getResponseCode()]);
}
else
{
$error = Mage::helper('paygate')->__('Incomplete transaction.');
}
}
else
{
$error = Mage::helper('paygate')->__('Invalid amount for authorization.');
}
if ($error !== false)
Mage::throwException($error);
return $this;
}
/**
* Capture the authorized transaction for a specific order
* #var Variant_Object $payment
* #var Float $amount
*/
public function capture(Varien_Object $payment, $amount) {
$error = false;
// check for payment
if ($amount <= 0)
{
Mage::throwException(Mage::helper('paygate')->__('Invalid amount for capture.'));
}
if($amount > 0)
{
$payment->setAmount($amount);
// Map magento keys to moneris way
$transaction = $this->_build($payment, self::TRANSACTION_COMPLETION);
$response = $this->_send($transaction);
if($response->getResponseCode() > 0 && $response->getResponseCode() <= self::ERROR_CODE_LIMIT)
{
$payment->setStatus(self::STATUS_SUCCESS);
$message = 'AVS Response: ' . Mage::helper('paygate')->__($this->_errors[$response->getAvsResultCode()]);
$message .= '<br>CVD Response: ' . Mage::helper('paygate')->__($this->_errors[$response->getCvdResultCode()]);
Mage::getSingleton('core/session')->addSuccess($message);
}
else if($response->getResponseCode() > self::ERROR_CODE_LIMIT && $response->getResponseCode() < self::ERROR_CODE_UPPER_LIMIT)
{
$error = Mage::helper('paygate')->__($this->_errors[$response->getResponseCode()]);
}
else
{
$error = Mage::helper('paygate')->__('Incomplete transaction.');
}
}
else
{
$error = Mage::helper('paygate')->__('Invalid amount for capture.');
}
// we've got something bad here.
if ($error !== false)
Mage::throwException($error);
return $this;
}
Feel free to correct me anywhere or suggest a better way of doing what I'm trying to do.
In the end I'm looking forward to build a basic Moneris payment gateway in Magento which authorizes n captures the amount if the card details are right and sends invoice mails to customer n store owner all at the same time at the click of 'place order'.
And if the card details are wrong then show appropriate message to customer and keep it as pending with right reason for pending payment for the store owner to see.

Categories