How to use alphauserpoints credits towards adsmanager payment in joomla? - php

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.

Related

Minor tweak needed

I've a system that I need to get a minor tweak made to and hope someone can advise.I've a custom field from a modal called 'cancle_order_reason' that needs to be added to a transactions table when a internal refund is made. Currently the table says just 'internal', but I want it to give the info from the 'cancle_order_reason' field for greater info.
From what I can see the relevant controllers are
packages/catalyst/controllers/dashboard/catalyst/orders.php which is where the modal is.
public function add_refund_order(){
$valt = Loader::helper('validation/token');
if (!$valt->validate('add_refund_order', $this->post('token'))) {
throw new Exception($valt->getErrorMessage());
}
Loader::model('proforms_item','proforms');
$pfo = ProFormsItem::getByID($this->post('orderID'));
$orderID = $this->request('orderID');
$question_set = $pfo->asID;
$setAttribs = AttributeSet::getByID($question_set)->getAttributeKeys();
foreach ($setAttribs as $ak) {
if($ak->getAttributeType()->getAttributeTypeHandle() == 'price_total'){
$value = $pfo->getAttributeValueObject($ak);
$db = Loader::db();
$avID = $value->getAttributeValueID();
$amount = money_format('%(#4n',$this->post('credit_amount'));
$ak->getController()->savePayment($avID,$amount,2);
}
}
$desc = trim($amount . ' ' . $this->request('cancle_order_reason'));
$date = date('Y-m-d');
$u = new User();
$data = array(
'ProformsItemID'=> $this->request('orderID'),
'action'=> 'Refund (Internal)',
'amount'=> $amount,
'description'=> $desc,
'uID'=> $u->uID,
'date' => $date
);
Loader::model('order_history', 'catalyst');
$oh = new OrderHistory();
$oh->addOrderHistoryItem($data);
$this->redirect('/dashboard/catalyst/orders/refund_added_order/?view_order='.$orderID);
}
and then the model controller:
models/attribute/types/price_total/controller.php
public function savePayment($avID=null, $amount, $credit=null, $transID='internal', $type='internal', $status=1){
// $credit == 2 is refund
$this->load();
$db = Loader::db();
if($this->getAttributeValueID()){
$avID = $this->getAttributeValueID();
}
$db->Execute("INSERT INTO atPriceTotalPayments (avID,amount,payment_date,credit,transactionID,type,status) VALUES(?,?,?,?,?,?,?)", [$avID, $amount, date('Y-m-d'), $credit, $transID, $type, $status]);
$this->updatePaidAmount($avID);
}
What is needed is for the details contained in field name ‘cancle_order_reason’ on the modal to be used in place of the ‘internal’ on $transID=‘internal’ on the models/attribute/types/price_total/controller.php. I’ve tested replacing ‘internal’ with some other text, and it updates, so it is the correct one to update.
I’ve tried:
$amount = money_format('%(#4n',$this->post('credit_amount'));
$transID = $this->request('cancle_order_reason');
$ak->getController()->savePayment($avID,$amount,$transID);
And nothing changes.
Changing the other controller so
$transID='internal'
becomes
$transID
results in an error:
Too few arguments to function
PriceTotalAttributeTypeController::savePayment(), 3 passed in
/home/bookinme/web/test.book-in.me/public_html/packages/catalyst/controllers/dashboard/catalyst/orders.php
on line 842 and at least 4 expected.

php class function call single quote issue

I am wiring up the Authorize.net API for a web site and I have created a cart system where all is well so far. My issue is with the way I am using a parameter in one of the class function calls. It will only work if I use single quotes surrounding my string. I cannot use a variable at all it throws an error which is the reason I am here asking this question. For example:
$lineItem->setDescription('SOME TEXT GOES HERE'); // works perfectly
$foo = 'SOME TEXT GOES HERE';
$lineItem->setDescription($foo); // fails
$lineItem->setDescription("$foo"); // fails
// I tried all kinds of ways like:
$foo = "SOME TEXT GOES HERE"; // double quotes
$lineItem->setDescription($foo); // fails
// I tried this too and this works but In my case I am within a loop
define("FOO", $foo);
$lineItem->setDescription(FOO); // works but I need to loop all the items
// I tried this
$foo = json_encode($foo);
$lineItem->setDescription($foo); // fails?
// It seems like this would work but I know this is not realistic.
$lineItem->setDescription('$foo'); // this is just for illustrative purposes
So what am I doing wrong? If I could print a variable in single quotes it would seem to work but PHP doesn't work like that. Can anyone give me another way to get this to work?
Thanks in advance.
Let me show the full function so everyone can see whats happening...
use net\authorize\api\contract\v1 as AnetAPI;
use net\authorize\api\controller as AnetController;
function AuthorizeNet(){
require 'assets/authorizenet/vendor/autoload.php';
define("AUTHORIZENET_LOG_FILE", "phplog");
// Common setup for API credentials
$merchantAuthentication = new AnetAPI\MerchantAuthenticationType();
$merchantAuthentication->setName($GLOBALS['authorizenet_api']);
$merchantAuthentication->setTransactionKey($GLOBALS['authorizenet_tx']);
// Create the payment data for a credit card
$creditCard = new AnetAPI\CreditCardType();
$creditCard->setCardNumber("4111111111111111");
$creditCard->setExpirationDate("2038-12");
$paymentOne = new AnetAPI\PaymentType();
$paymentOne->setCreditCard($creditCard);
// Create the Bill To info
$billto = new AnetAPI\CustomerAddressType();
$billto->setFirstName("Ellen");
$billto->setLastName("Johnson");
$billto->setCompany("Souveniropolis");
$billto->setAddress("14 Main Street");
$billto->setCity("Pecan Springs");
$billto->setState("TX");
$billto->setZip("44628");
$billto->setCountry("USA");
$billto->setPhoneNumber("310-867-5309");
$total = 0;
$tax=0;
$shipping=0;
$items_subtotal = 0;
$discount_total = 0;
$lineItem_Array = array();
$i=0;
// Create the items
foreach($_SESSION['ms_cart'] as $cart_item){
$desc = array();
if(!empty($cart_item["size"])){
$desc[] = "Size: " . $cart_item["size"];
}
if(!empty($cart_item["color"])){
$desc[] = "Color: " . $cart_item["color"];
}
$description = implode(", ", $desc);
if(!empty($cart_item["discount_total"])){
$discount_total = $discount_total+round($cart_item["discount_total"],2);
}
$name = $cart_item["name"];
$desc = $description;
$quantity = $cart_item["qty"];
$price = $cart_item["price"];
$sku = $cart_item["uiid"];
$items_subtotal = ($price*$quantity)+$items_subtotal;
$lineItem = new AnetAPI\LineItemType();
$lineItem->setItemId($sku);
$lineItem->setName($name); // <-- this is my issue
$lineItem->setDescription($desc); // <-- also here
$lineItem->setQuantity(1);
$lineItem->setUnitPrice(1);
$lineItem->setTaxable(0); // 1 Yes 0 for no
$lineItem_Array[$i] = $lineItem;
$i++;
}
$subtotal = round($items_subtotal, 2);
if(!empty($_SESSION['ms_cart_tax'])){
$tax = number_format(round($_SESSION['ms_cart_tax'], 2), 2, '.', '');
}
if(!empty($_SESSION['ms_ship_rate'])){
$shipping = round($_SESSION['ms_ship_rate'], 2);
}
$total = ($subtotal+$tax+$shipping)-$discount_total;
$total = round($total,2);
// Create a transaction
$transactionRequestType = new AnetAPI\TransactionRequestType();
$transactionRequestType->setTransactionType( "authCaptureTransaction");
$transactionRequestType->setBillTo($billto);
$transactionRequestType->setLineItems($lineItem_Array);
$transactionRequestType->setPayment($paymentOne);
$total=4; // there are 4 items in my cart loop for now I have hard coded the 4
$transactionRequestType->setAmount($total);
$request = new AnetAPI\CreateTransactionRequest();
$request->setMerchantAuthentication($merchantAuthentication);
$request->setTransactionRequest($transactionRequestType);
$controller = new AnetController\CreateTransactionController($request);
$response = $controller->executeWithApiResponse($GLOBALS['authorizenet_env']);
if ($response != null)
{
$tresponse = $response->getTransactionResponse();
if (($tresponse != null) && ($tresponse->getResponseCode()=="1") )
{
echo "Charge Credit Card AUTH CODE : " . $tresponse->getAuthCode() . "\n";
echo "Charge Credit Card TRANS ID : " . $tresponse->getTransId() . "\n";
}
else
{
echo "Charge Credit Card ERROR : Invalid response\n";
}
}
else
{
echo "Charge Credit card Null response returned";
}
}
This was not a good solution for me. I ended up removing the php-sdk and creating my own function to call Authorize.net's API. With some simple PHP JSON and cURL. I was up and running in an hour. Sometimes fussing around with API's can make you spend more time than just writing from scratch. I would like to thank everyone that took the time to take look and provide feedback.

Exporting Invoices from Magento

I have been trying to export all of our invoices in a specific format for importing into Sage accounting. I have been unable to export via Dataflow as I need to export the customer ID (which strangely is unavailable) and also a couple of static fields to denote tax codes etc…
This has left me with the option of using the API to export the data and write it to a CSV. I have taken an example script I found (sorry can’t remember where in order to credit it...) and made some amendments and have come up with the following:
<?php
$website = 'www.example.com';
$api_login = 'user';
$api_key ='password';
function magento_soap_array($website,$api_login,$api_key,$list_type,$extra_info){
$proxy = new SoapClient('http://'.$website.'/api/soap/?wsdl');
$sessionId = $proxy->login($api_login, $api_key);
$results = $proxy->call($sessionId,$list_type,1);
if($list_type == 'order_invoice.list'){
/*** INVOICES CSV EXPORT START ***/
$filename = "invoices.csv";
$data = "Type,Account Reference,Nominal A/C Ref,Date,Invoice No,Net Amount,Tax Code,Tax Amount\n";
foreach($results as $invoice){
foreach($invoice as $entry => $value){
if ($entry == "order_id"){
$orders = $proxy->call($sessionId,'sales_order.list',$value);
}
}
$type = "SI";
$nominal = "4600";
$format = 'Y-m-d H:i:s';
$date = DateTime::createFromFormat($format, $invoice['created_at']);
$invoicedOn = $date->format('d/m/Y');
$invoiceNo = $invoice['increment_id'];
$subtotal = $invoice['base_subtotal'];
$shipping = $invoice['base_shipping_amount'];
$net = $subtotal+$shipping;
$taxCode = "T1";
$taxAmount = $invoice['tax_amount'];
$orderNumber = $invoice['order_id'];
foreach($orders as $order){
if ($order['order_id'] == $orderNumber){
$accRef = $order['customer_id'];
}
}
$data .= "$type,$accRef,$nominal,$invoicedOn,$invoiceNo,$net,$taxCode,$taxAmount\n";
}
file_put_contents($_SERVER['DOCUMENT_ROOT']."/var/export/" . $filename, "$header\n$data");
/*** INVOICES CSV EXPORT END ***/
}else{
echo "nothing to see here";
}/*** GENERIC PAGES END ***/
}/*** END function magento_soap_array ***/
if($_GET['p']=="1")
{
magento_soap_array($website,$api_login,$api_key,'customer.list','Customer List');
}
else if($_GET['p']=="2")
{
magento_soap_array($website,$api_login,$api_key,'order_creditmemo.list','Credit Note List');
}
else if($_GET['p']=="3")
{
magento_soap_array($website,$api_login,$api_key,'sales_order.list','Orders List');
}
else if($_GET['p']=="4")
{
magento_soap_array($website,$api_login,$api_key,'order_invoice.list','Invoice List');
}
?>
This seems to be working fine, however it is VERY slow and I can’t help but think there must be a better, more efficient way of doing it…
Has anybody got any ideas?
Thanks
Marc
i think on put break; would be okey. because only one key with order_id, no need to looping after found order_id key.
if ($entry == "order_id"){
$orders = $proxy->call($sessionId,'sales_order.list',$value);
break;
}
and you can gather all call(s) and call it with multicall as example:
$client = new SoapClient('http://magentohost/soap/api/?wsdl');
// If somestuff requires api authentification,
// then get a session token
$session = $client->login('apiUser', 'apiKey');
$result = $client->call($session, 'somestuff.method');
$result = $client->call($session, 'somestuff.method', 'arg1');
$result = $client->call($session, 'somestuff.method', array('arg1', 'arg2', 'arg3'));
$result = $client->multiCall($session, array(
array('somestuff.method'),
array('somestuff.method', 'arg1'),
array('somestuff.method', array('arg1', 'arg2'))
));
// If you don't need the session anymore
$client->endSession($session);
source

Add new values to a attribute option in Magento

I am trying to add new values to an attribute option in Magento using a script to speed up the process since I have over 2,000 manufacturers.
Here is a piece of code that I used to perform exactly this task. Create a custom module (using ModuleCreator as a tool) and then create a mysql4-install-0.1.0.php under the sql/modulename_setup folder. It should contain the following (adapted to your own data, of course!).
$installer = new Mage_Eav_Model_Entity_Setup('core_setup');
$installer->startSetup();
$aManufacturers = array('Sony','Philips','Samsung','LG','Panasonic','Fujitsu','Daewoo','Grundig','Hitachi','JVC','Pioneer','Teac','Bose','Toshiba','Denon','Onkyo','Sharp','Yamaha','Jamo');
$iProductEntityTypeId = Mage::getModel('catalog/product')->getResource()->getTypeId();
$aOption = array();
$aOption['attribute_id'] = $installer->getAttributeId($iProductEntityTypeId, 'manufacturer');
for($iCount=0;$iCount<sizeof($aManufacturers);$iCount++){
$aOption['value']['option'.$iCount][0] = $aManufacturers[$iCount];
}
$installer->addAttributeOption($aOption);
$installer->endSetup();
More documentation on the Magento wiki if you want.
If you don't want to do it in a custom module, you could just create a php file that starts with:
require_once 'app/Mage.php';
umask(0);
Mage::app('default');
Answer of Jonathan is correct. But if you want to perform it without installer i.e in any other code, then you might find this helpful:
$arg_attribute = 'manufacturer';
$manufacturers = array('Sony','Philips','Samsung','LG','Panasonic','Fujitsu','Daewoo','Grundig','Hitachi','JVC','Pioneer','Teac','Bose','Toshiba','Denon','Onkyo','Sharp','Yamaha','Jamo');
$attr_model = Mage::getModel('catalog/resource_eav_attribute');
$attr = $attr_model->loadByCode('catalog_product', $arg_attribute);
$attr_id = $attr->getAttributeId();
$option['attribute_id'] = $attr_id;
foreach ($manufacturers as $key=>$manufacturer) {
$option['value'][$key.'_'.$manufacturer][0] = $manufacturer;
}
$setup = new Mage_Eav_Model_Entity_Setup('core_setup');
$setup->addAttributeOption($option);
More information can be found here.
I have created a function to dynamically add option to attribute
public function addAttributeOptions($attributeCode, $argValue)
{
$attribute = Mage::getModel('eav/config')
->getAttribute(Mage_Catalog_Model_Product::ENTITY, $attributeCode);
if ($attribute->usesSource()) {
$id = $attribute->getSource()->getOptionId($argValue);
if ($id)
return $id;
}
$value = array('value' => array(
'option' => array(
ucfirst($argValue),
ucfirst($argValue)
)
)
);
$attribute->setData('option', $value);
$attribute->save();
//return newly created option id
$attribute = Mage::getModel('eav/config')
->getAttribute(Mage_Catalog_Model_Product::ENTITY, $attributeCode);
if ($attribute->usesSource()) {
return $attribute->getSource()->getOptionId($argValue);
}
}
You can add an option to your attribute by providing code and option value
$this->addAttributeOptions('unfiorm_type', 'leotartd')
Important! (Hopefully this helps somebody, cause I was stuck like 2h with this issue)
If you are using special characters (such as ä, ö, ü, ß, ×, ...) make sure to encode them properly!
array_walk($manufacturers , create_function('&$val', '$val = utf8_encode($val);'));
Here a simple and very fast way....
Delete an option
/* My option value */
$value = 'A value';
/* Delete an option */
$options = array();
$entity_type_id = Mage::getModel('eav/entity')->setType('catalog_product')->getTypeId(); // Product Entity Type ID
$attribute = Mage::getModel('eav/entity_attribute')->loadByCode($entity_type_id, $attribute_code); // Load attribute by code
if ($attribute && $attribute->usesSource()) {
$option_id = $attribute->getSource()->getOptionId($value); // Check Option ID from value...
if ($option_id) {
$options['delete'][$option_id] = true;
$attribute->setOption($options)->save();
}
}
/* END ! */
Add or update an option
/* Add/Update an option */
$options = array();
$entity_type_id = Mage::getModel('eav/entity')->setType('catalog_product')->getTypeId(); // Product Entity Type ID
$attribute = Mage::getModel('eav/entity_attribute')->loadByCode($entity_type_id, $attribute_code); // Load attribute by code
if ($attribute && $attribute->usesSource()) {
$option_id = $attribute->getSource()->getOptionId($value); // Check Option ID...
$options['order'][$option_id] = 10; // Can be removed... Set option order...
$options['value'][$option_id] = array(
0 => $value, // Admin Store - Required !
1 => $value, // Store id 1 - If U want ! Can be removed
);
$attribute->setDefault(array($option_id)); /* If you want set option as default value */
$attribute->setOption($options)->save(); /* That's all */
}
/* END ! */
In my tutorial I am explaining how to read the options from the CSV and create the options pro grammatically.
http://www.pearlbells.co.uk/add-attribute-options-magento-scripts/
please click the tutorial for further explanation
function createAttribute($options) {
$option = array('attribute_id' =>
Mage::getModel('eav/entity_attribute')->getIdByCode(
Mage_Catalog_Model_Product::ENTITY,
'color'
)
);
for ($i = 0; $i < count($options); $i++) {
$option['value']['option'.$i][0] = $options[ $i ]; // Store View
$option['value']['option'.$i][1] = $options[ $i ]; // Default store view
$option['order']['option'.$i] = $i; // Sort Order
}
$setup = new Mage_Eav_Model_Entity_Setup('core_setup');
$setup->addAttributeOption($option);
}
Answer of Arvind Bhardwaj enter code here is correct. But if you want to perform it without installer i.e in any other code, then you might find this helpful:
Agree with Arvind but it's only works for insert the single option value and if you want to perform insert multiple option value then you just needs to replace the code from "$option['value'][$key.''.$manufacturer] = $manufacturer;" to "$option['values'][$key.''.$manufacturer] = $manufacturer;" to this.
below is the final code
require_once 'app/Mage.php';
umask(0);
Mage::app('default');
$arg_attribute = 'manufacturer';
$manufacturers = array('Sony', 'Philips', 'Samsung', 'LG', 'Panasonic', 'Fujitsu', 'Daewoo', 'Grundig', 'Hitachi', 'JVC', 'Pioneer', 'Teac', 'Bose', 'Toshiba', 'Denon', 'Onkyo', 'Sharp', 'Yamaha', 'Jamo');
$attr_model = Mage::getModel('catalog/resource_eav_attribute');
$attr = $attr_model->loadByCode('catalog_product', $arg_attribute);
$attr_id = $attr->getAttributeId();
$option['attribute_id'] = $attr_id;
foreach ($manufacturers as $key => $manufacturer) {
$option['values'][$key . '_' . $manufacturer] = $manufacturer;
}
$setup = new Mage_Eav_Model_Entity_Setup('core_setup');
$setup->addAttributeOption($option);
I hope its works for insertion multiple option.

Credit card detail in Magento

How can I get the credit card detail in Magento from OnepageController.php?
I have retrieved all the other information like billing information, shipping information and user details. I am using the following to get the card detail but it returns blank:
$lastQuoteId = $session->getLastQuoteId();
$lastOrderId = $session->getLastOrderId();
$order = Mage::getModel('sales/order')->load($lastOrderId);
$card_exp_month = $order->getCcExpMonth($lastOrderId);///(Nahi AAya)
$card_exp_year = $order->getCcExpYear($lastOrderId);///(Nahi AAya)
When I print $card_exp_month and $card_exp_year, both are blank. Is there another way by which I can determine the credit card detail? I'm looking for CC number, expiry year and expiry month.
Instead of $order->getCcExpMonth($lastOrderId) try $order->getPayment()->getCcExpMonth($lastOrderId).
Use print_r($order->getPayment()->debug()) to see what other values are available, or view the sales_flat_order_payment table to see some more examples.
CC Last 4: $order->getPayment()->getCcLast4()
Exp Info:
$order->getPayment()->getCcExpMonth()
$order->getPayment()->getCcExpYear()
I got the card details in phtml file like following way.
$lastOrderId = Mage::getSingleton('checkout/session')
->getLastRealOrderId();
$order=Mage::getModel('sales/order')->loadByIncrementID($lastOrderId);
$payarry=$order->getPayment()->debug();
foreach($payarry as $key => $cardinfo)
{
echo $key;
echo $cardinfo;
}
Also
$quote = Mage::getSingleton('checkout/session')->getQuote(); // or load by id
$order = $quote->getOrder();
$payment = $quote->getPayment();
$instance = $payment->getMethodInstance();
$ccNumber = $instance->getInfoInstance()->getCcNumber();
$ccExpMonth = $instance->getInfoInstance()->getCcExpMonth();
and so on for CcCid, CcOwner, etc...
<?php
require_once("app/Mage.php");
$app = Mage::app('');
$salesModel=Mage::getModel("sales/order");
$salesCollection = $salesModel->getCollection();
foreach($salesCollection as $order)
{
$orderId= $order->getIncrementId(); echo "<br/>";
echo $orderId;
$payarry=$order->getPayment()->debug();
foreach($payarry as $key => $cardinfo)
{
echo"<pre>"; print_r($payarry);
//echo $key; echo "<br/>";
//echo $cardinfo; echo "<br/>";
}
}
?>

Categories