magento custome api connection to economics - magento

I am running an api for magento shop to connect to economics : please check this link for that api : https://github.com/tkjaergaard/Economic-PHP-SDK?_e_pi_=7%2CPAGE_ID10%2C1957533932
I just paste the folder in root directory and getting my order through
$orderId= Mage::getSingleton('checkout/session')->getLastRealOrderId();
$order= Mage::getSingleton('sales/order')->loadByIncrementId($orderId);
My question is I need to include api folder in root director / vendor / autoload.php file for connection my extension....
So that when an new order is been placed in my shop the total order details will be automatically add to economics api...
Any idea on this... thanks in advance.
Create a new Order This method lets you create a newOrder to a specific Debtor.Theaddmethod on thelineobject accepts a array containing information on the product line. The array accepts the following elements:.Product: The product number.required.Description: The line description.optional*.Price: The unit price of the line.optional*.Qty: The quantity of the line.optional*.Unit: The Unit number to use.optional
<?php
require(Mage::getBaseDir().DS.'Economic-PHP-SDK-master'.DS.'vendor'.DS.'autoload.php');
use tkj\Economics\Client;
use tkj\Economics\Order\Order;
$client = new Client($agreementNumber,$userID, $password);
$order = new Order($client);
$debtorNumber = 101;
$newOrder =$order->create($debtorNumber, function($line)
{
$data = array(
"product" => 301,
"description" => "Description of line.",
"price" => 825.00,
"qty" => 5,
"unit" => 2);
$line->add($data);
});
class EconomicAPI_Model_Observer {
public function ordermigrate($observer) {
$orderId = Mage::getSingleton('checkout/session')->getLastRealOrderId();
$order = Mage::getSingleton('sales/order')->loadByIncrementId($orderId);
// echo "order subtotal: ".$order->getSubtotal()."<br>";
// echo "shipping: ".$order->getShippingAmount()."<br>";
// echo "discount: ".$order->getDiscountAmount()."<br>";
// echo "tax: ".$order->getTaxAmount()."<br>";
// echo "grand total".$order->getGrandTotal()."<br><br><br>";
$to = 'karthickica#gmail.com';
$subject = 'Mail before Sale order place.';
$message = $orderId ;
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
mail($to, $subject, $message, $headers );
}
}

Related

email when images change, woocommerce product

I am attempting to send out an email anytime a woocommerce product has its images changed in any way.
I started off by attempting to get the $_POST of the image gallery, but I think I am calling it the wrong thing… I have tried the following:
$images = $_POST[‘image_ids’];
$images = $_POST[‘gallery_image_ids’];
Then I am comparing that value to the current image ids:
$oldImages = $product->get_gallery_image_ids();
If they do not match I am using wp_mail to send an email to various people.
I am doing all this inside a custom php function using:
add_action(‘pre_post_update’, ‘content_change_email’, 10, 2);
function content_change_email($post_ID, $data)
{
}
I assume the problem is originating with the
$images = $_POST[‘image_ids’];
$images = $_POST[‘gallery_image_ids’];
part of the code.
Can someone let me know what the correct meta field name for the gallery images is?
I solved my own problem…
I used a custom meta field to record the IDs for all the images, including the featured image then compared that to the current gallery images to see if they had changed, if they did then update the custom meta value with the new numbers and send an email to let people know the pictures changed.
code is as follows:
// send email when images change for a product
add_action( 'woocommerce_update_product', 'imagecheck_on_product_save', 10, 1 );
function imagecheck_on_product_save( $product_id ) {
$product = wc_get_product( $product_id );
// do something with this product
$metaImages = get_post_meta( $product_id, '_gallery_image_ids', true );
$currentImages = $product->get_gallery_image_ids();
$imageIDs = get_post_thumbnail_id( $product_id );
if ($imagesIDs != "" )
{
$imageIDs = $imageIDs . ", ";
foreach($currentImages as $value){
$imageIDs = $imageIDs . $value . ", ";
}
if ( $metaImages != $imageIDs ) {
update_post_meta( $product_id, '_gallery_image_ids', esc_attr( $imageIDs ) );
global $current_user;
wp_get_current_user();
$email = $current_user->user_email;
$lastuser = $current_user->user_firstname;
if ( $product->get_sku() != "" )
{
$memail = "<pre>USER: " . $lastuser . " made the following changes:</br>
Meta gallery images: " . $metaImages . "</br>
</br>
Actual gallery images: " . $imageIDs . "
" . $memail . "</pre>";
$headers = array('Content-Type: text/html; charset=UTF-8');
$subject = "PICTURES CHANGED - SKU: " . $product->get_sku();
$to = "(insert who you want to send to here)";
wp_mail( $to, $subject, $memail, $headers );
}
}
}
}

How to get order details after an order placed using observer

I would like to get the order details using observer ,
Once i get the order it will sent order details to my test email , but i can not able to get the order details.
please check the code which i tried to get the order details, Can someone let me know how can i get the order details , thanks.
public function postdata($observer) {
$to = 'testmail#gmail.com';
$subject = 'Mail after Sale order place.';
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$message = 'This is my first Magento Observer After Sale order place';
mail($to, $subject, $message, $headers);
$order = $observer->getEvent()->getOrder();
$order_message = $order;
foreach($order as $ok => $ov) {
$order_message .= $ok. " => " .$ov;
}
mail($to, $subject, $message, $headers);
}
}
You can configure Magento to send you a copy of the order confirmation email that gets sent to the customer. If that is sufficient for your needs, this previously answered question will do the trick.
Use sale_order_save_after event to get the order details after place the order.

STRANGE...Not able to get cart items in magento on a custom page (only when the customer is logged in)

Here is the standard code I am using for getting cart items and their attributes which works only when the customer is not logged in. As soon as I log in using my account this script stops working and does not return the items in the cart. Also the cart items count is also 0. But as soon as I close the browser(session ends..) and the script returns the cartitems correctly! Very strange, I have not been able to find out the cause. Please guide, anyone?
require_once('../app/Mage.php') ;
umask(0);
Mage::app();
Mage::getSingleton('core/session', array('name'=>'frontend'));
$session = Mage::getSingleton('checkout/session');
$items = $session->getQuote()->getAllVisibleItems();
foreach ($items as $item) {
//$canProceed=0;
echo $productname = $item->getName(); //HERE IS THE COMPLETE CODE:<?php
ini_set('display_errors',true);
require_once('../app/Mage.php') ;
Mage::setIsDeveloperMode(true);
umask(0);
Mage::app();
//Getting buyer's country label
$bcountry1 = $_REQUEST['country']; //gets country code
$_countries = Mage::getResourceModel('directory/country_collection')
->loadData()
->toOptionArray(false);
foreach($_countries as $_country){
if ($_country['value']==$bcountry1){$bcountry = $_country['label'];}
}
//Fetching vendor for each product
$config = Mage::getConfig()->getResourceConnectionConfig("default_setup");
$dbinfo = array("host" => $config->host,
"user" => $config->username,
"pass" => $config->password,
"dbname" => $config->dbname );
$hostname = $dbinfo["host"];
$user2 = $dbinfo["user"];
$password = $dbinfo["pass"];
$dbname = $dbinfo["dbname"];
$dbhandle = mysql_connect($hostname,$user2,$password) or die("Unable to connect");
$selected = mysql_select_db("myart2",$dbhandle);
$Proceed=0;
//Getting all products in the cart
//echo $cart = Mage::getSingleton('checkout/cart')->getItemsCount();
// Secret Sauce - Initializes the Session for the FRONTEND
// Magento uses different sessions for 'frontend' and 'adminhtml'
Mage::getSingleton('core/session', array('name'=>'frontend'));
$session = Mage::getSingleton('checkout/session');
$items = $session->getQuote()->getAllVisibleItems();
foreach ($items as $item) {
//$canProceed=0;
$productname = $item->getName();
$product = Mage::getModel('catalog/product')->loadByAttribute('sku', $item->getSku(), array('manufacturer'));
$manufacturer = $product->getResource()->getAttribute('manufacturer')->getFrontEnd()->getValue($product);
$qry="select * from vendors WHERE company_name='$manufacturer'";
$result = mysql_query($qry) or die("Unable to run select query");
$row = mysql_fetch_array($result) or die("Unable to fetch data");
if( strcasecmp($row['country'],$bcountry)!=0 && $row['ships_abroad']!=1)
{$Proceed=1;$productnames[]=$productname;}
}
if($Proceed==1)
{
echo implode(',',$productnames);
}
else {echo 1; }
?>
I've tested the following four main permutations, and the code works in a stock CE1.7 instance in all cases:
Create guest quote
Convert guest quote to customer quote via login
Instantiate existing customer quote via login
Merge guest quote with customer quote via login
Adjust the server & app environment params as follows to view & rule out any errors (edit - added complete script; note the closing "}"):
<?php
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors',true);
require_once('../app/Mage.php') ;
Mage::setIsDeveloperMode(true);
umask(0);
Mage::app();
$session = Mage::getSingleton('checkout/session');
$items = $session->getQuote()->getAllVisibleItems();
foreach ($items as $item) {
//$canProceed=0;
echo $productname = $item->getName();
}

How to access Magento from CodeIgniter?

I have a default CodeIgniter 2.1 install with Magento 10.4.4 installed in a subdir called store.
The following code works when run from web root (with .htaccess disabled). It will give the firstname, lastname of the logged in Magento user.
<?php
$site_root = '/var/www/mysite/www/httpdocs';
require_once ($site_root . '/store/app/Mage.php');
umask(0);
// Initialize Magento and hide sensitive config data below site root
$name='frontend';
$options = array('etc_dir' => realpath('../magento-etc'));
Mage::app('default','store', $options);
Mage::getSingleton("core/session", array("name" => $name));
$websiteId = Mage::app()->getWebsite()->getId();
echo "websiteid: $websiteId<br>";
$store = Mage::app()->getStore();
$customer = Mage::getModel("customer/customer");
$customer->website_id = $websiteId;
$customer->setStore($store);
echo 'customerwebsiteId: ' . $customer->website_id . '<br>';
$session = Mage::getSingleton('customer/session');
$magento_message = 'Welcome ';
// Generate a personalize greeting
if($session->isLoggedIn()){
$magento_message .= $session->getCustomer()->getData('firstname').' ';
$magento_message .= $session->getCustomer()->getData('lastname').'!';
}else{
$magento_message .= 'Guest!';
}
echo $magento_message;
?>
But, if I run this in a CodeIgniter model, then isLoggedIn returns false.
Here is the CodeIgniter page:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Test_mage extends CI_Controller {
function __construct()
{
parent::__construct();
}
public function index()
{
$site_root = '/var/www/mysite/www/httpdocs';
require_once ($site_root . '/store/app/Mage.php');
umask(0);
// Initialize Magento and hide sensitive config data below site root
$name='frontend';
$options = array('etc_dir' => realpath('../magento-etc'));
Mage::app('default','store', $options);
Mage::getSingleton("core/session", array("name" => $name));
$websiteId = Mage::app()->getWebsite()->getId();
echo "websiteid: $websiteId<br>";
$store = Mage::app()->getStore();
$customer = Mage::getModel("customer/customer");
$customer->website_id = $websiteId;
$customer->setStore($store);
echo 'customerwebsiteId: ' . $customer->website_id . '<br>';
$session = Mage::getSingleton('customer/session');
$magento_message = 'Welcome ';
// Generate a personalize greeting
if($session->isLoggedIn()){
$magento_message .= $session->getCustomer()->getData('firstname').' ';
$magento_message .= $session->getCustomer()->getData('lastname').'!';
}else{
$magento_message .= 'Guest!';
}
echo $magento_message;
}
}
CodeIgniter is doing something that I have not been able to track yet. The websiteId is returned correctly, but isLoggedIn returns false.
Anyone have any ideas? THANKS!!
I use both but ive never tried to mash them like that. I foresee quite a few problems.
How are you patching into magento?
You might need two db connections running :
$db['magento']
$db['default'] // codeigniter default
Sessions could become a real problem here also aswell as config data.
Consider sticking with magento for now, then maybe patch into your blog/website via a RESTFul service.
Both code examples above work fine. The problem I had was calling session_start() near the top of the CodeIgniter index.php file. Once that was removed, it all started working.
For posterity, here is a Magento 10 Library for CodeIgniter 2.1:
application/libraries/magento.php
<?php if ( ! defined('BASEPATH')) exit("No direct script access allowed");
Class Magento {
function __construct($params)
{
global $site_root;
$name = $params['name'];
// Include Magento application
require_once ($site_root . '/store/app/Mage.php');
umask(0);
// Initialize Magento and hide sensitive config data below site root
// Uncomment next line if you have moved app/etc
// $options = array('etc_dir' => realpath('../magento-etc'));
Mage::app('default','store', $options=null);
return Mage::getSingleton("core/session", array("name" => $name));
}
}
// end of magento.php
Usage example app/model/test_mage.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Test_mage extends CI_Controller {
function __construct()
{
parent::__construct();
$params = array('name' => 'frontend'); // frontend or adminhtml
$this->load->library('magento', $params);
}
public function index()
{
$session = Mage::getSingleton('customer/session');
$magento_message = 'Welcome ';
// Generate a personalize greeting
if ($session->isLoggedIn())
{
$magento_message .= $session->getCustomer()->getData('firstname').' ';
$magento_message .= $session->getCustomer()->getData('lastname').'!';
}
else
$magento_message .= 'Guest!';
echo $magento_message . '<br>';
}
}
// end of test_mage.php

Daily Inventory Update through remote FTP file

It’s been 2 days and I came across many tutorials, videos, extension which explains how to do daily updates on my products but none of them seem to work.
I have a website which has around 3,000 products with attributes and all. My supplier updates the inventory file on daily basis and the updated inventory file is kept on a remote ftp to which I have access to.
What I need is the following:
Daily inventory update which will include, prices, quantity, etc
Remove items which has quantity 0
Add new items as per the updated inventory file
I am sure someone out there has answer to my questions. So please get back to me asap.
Fisrt, by "Remove items which has quantity 0", I think you mean to set products as "out of stock" when the inventory is decreased to 0. This is handled automatically by Magento after you update the inventory.
The built-in import/export function should fulfill your requirements.
Some more tutorials if you don't mind:
Tutorial: Using Magento’s Import/Export Profiles
How to add/edit/remove products using the import/export tool
Here, I will share just inventory update ( but this is not good way ). You should create "tab delimited" file as follows :
SKU QTY
978 34
633 0
Then you can create cron job to run this script.
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
set_time_limit(0);
ini_set('memory_limit','1024M');
include('app/Mage.php');
Mage::App('default');
//get magento db connection for query
$db_query = Mage::getSingleton('core/resource')->getConnection('core_read');
//get magento db connection for update, add, delete sql statements
$db_update = Mage::getSingleton('core/resource')->getConnection('core_write');
//mail receipent
$to = 'youremail#yoursite.com';
if ($handle = opendir('./var/export'))
{
while (false !== ($file = readdir($handle)))
{
$sku_success = '';
if ($file != '.' && $file != '..')
{
$filename = './var/export/'.$file;
$handle_file = fopen($filename,'r');
$counter = 1;
while (($data = fgetcsv($handle_file, 1000, '\t'))!== FALSE) //read tab delimited
{
if($counter!=1)
{
$sku= $data[0];
$qty = $data[1];
$exists = $db_query->query("SELECT COUNT(sku) cnt FROM catalog_product_entity WHERE sku = '$sku' LIMIT 1");
$found = (($exists->fetchObject()->cnt) > 0) ? true : false;
if ($found == true) //product found, update
{
$entity_id = getEntityIdBySku($db_query, $sku);
updateStockQty ($db_update, $entity_id, $qty);
echo 'product $sku inventory updated?';
$sku_success.= $sku;
} else {
//sku not found, notify by email
$body = "SKU#:".$sku." of ".$file." with a qty of ".$qty." was not found in the the inventory";
sendMsg("SKU#:".$sku." not found!",$to,$body);
}
}
$counter++;
}
fclose($handle_file);
$body = "<strong>SKU?S IMPORTED</strong>".$sku_success."<br/>";
sendMsg($file." successfully imported!",$to,$body);
}
}
closedir($handle);
}
function getEntityIdBySku($db_connection, $sku) //get entity id by its sku
{
$entity_row = $db_connection->query("SELECT entity_id FROM catalog_product_entity p_e WHERE p_e.sku = '$sku'")->fetchObject();
$entity_id = $entity_row->entity_id;
return $entity_id;
}
function updateStockQty($db_connection, $entity_id, $qty) //updates the stock quantity
{
$db_connection->query("UPDATE cataloginventory_stock_item s_i, cataloginventory_stock_status s_s
SET s_i.qty = '$qty', s_i.is_in_stock = IF('$qty'>0, 1,0),
s_s.qty = '$qty', s_s.stock_status = IF('$qty'>0, 1,0)
WHERE s_i.product_id = '$entity_id' AND s_i.product_id = s_s.product_id ");
}
function sendMsg($subject, $to, $body)//sends email
{
$headers = 'MIME-Version: 1.0' . '\n';
$headers .= 'Content-type: text/html; charset=iso-8859-1'. '\n';
$headers .= 'To: '.$to. '\n';
$headers .= 'From: webmaster#yoursite.com'. '\n';
if (mail($to, $subject, $body,$headers))
{
echo('Message sent!');
} else {
echo('Message failed.');
}
}
?>
The script by courtesy of the Deepcodeonline

Resources