Magento sending SMS upon creating shipment - php

Banging my head for the last two days but unable to achieve this. Help!!
Whenever a shipment email is communicated I want to trigger a code which will send a SMS to the customer informing him/her that his order has been dispatched and also communicate the tracking number.
The code will be something like this:
<?php
$url = "http://www.abcde.in/binapi/pushsms.php?usr=xyz&pwd=abc&sndr=MEGYTR&ph=8888829554&text=This is test. MegaYtr&rpt=1";
$result = file_get_contents($url);
?>
Questions:
1) From where do I run this code?
2) How do I get additional info like Order Number, Customer Name, Grand Total & Tracking Number. I had done something similar for sending SMS when customer places order at that I used this code:
$order_id = Mage::getSingleton('checkout/session')->getLastRealOrderId();
$order_details = Mage::getModel('sales/order')->loadByIncrementId($order_id);
$shipping_address_data = $order_details->getShippingAddress();
$first_name = $shipping_address_data['firstname'];
$telephone = $shipping_address_data['telephone'];
$amount_paid = $order_details->total_paid;
$message = 'Dear '.$first_name.' thank you for shopping at abc.com. Your order'.$this->getOrderId().' amounting to Rs.'.$amount_paid.'is being processed.';
echo '<b>'.$message.' Please check your email for further details.</b>';
I am using Magento Community 1.7.0.1.

try this
i would like to give you an simple solution without need of modifying core files.
for that you need to create an observer for SuccessAction below is the event that will trigger your code when an order is successfull
checkout_onepage_controller_success_action
this will help you in creating observer for the above event create observer using this
one more thing i would like to add is in the controller at location Mage/Checkout/OnepageController search for successAction, this is the Action which is processed on the succes of order. Here on line 240 if you comment $session->clear(); than you would not require to place order again and again, just by refreshing the page you can check your changes.
And lastly FYI above event will dispatch orderId by using that you can load the order object, for doing that the below is the code
//load order object
$_order = Mage::getModel('sales/order')->loadByIncrementId($order_id_from_observer);

Related

How do I apply multiple coupons to an account in Recurly?

Recurly Create Subscription. It doesn’t seem like they allow multiple coupons to be allowed added to the account during creation, but am I wrong? Or is there another way to add a coupon to the account subscription?
I already have multiple coupons setting in Recurly turned on, I'm just not sure how to apply them. I'm also using the PHP library if that makes any difference.
I found out you can actually create subscription with multiple coupons at once. All you need to do is organize coupon codes into comma separated list.
You must use the redeem subscription endpoint (rather than the create subscription endpoint) if you wish to apply multiple coupons
<?php
$coupon = Recurly_Coupon::get('special');
$redemption = $coupon->redeemCoupon('1', 'USD');
?>
More information here
You should work with Redeem a Coupon on an Account
Definition
https://:subdomain.recurly.com/v2/coupons/:coupon_code/redeem
PHP Examples
<?php
$coupon = Recurly_Coupon::get('special');
$redemption = $coupon->redeemCoupon('1', 'USD');
?>
Result Format
<redemption href="https://your-subdomain.recurly.com/v2/accounts/1/redemptions/316a4213e8fa9e97390aff4995bda9e6">
<coupon href="https://your-subdomain.recurly.com/v2/coupons/special"/>
<account href="https://your-subdomain.recurly.com/v2/accounts/1"/>
<subscription href="https://your-subdomain.recurly.com/v2/subscriptions/315fbd7a25b04f1333ea9f4418994fb5"/>
<uuid>316a4213e8fa9e97390aff4995bda9e6</uuid>
<single_use type="boolean">false</single_use>
<total_discounted_in_cents type="integer">0</total_discounted_in_cents>
<currency>USD</currency>
<state>active</state>
<created_at type="datetime">2015-09-23T17:13:30Z</created_at>
</redemption>

Updating an order value with the PayPal PHP SDK

OK, I've been banging my head against this for a few days now. I'm building a payment process into a PHP application which will allow for upselling products after a customer approves a payment.
I can get the payment charged to the customer without an issue, but if they select any kind of upsell product which requires the order value to change, then I get errors even though it is following to the letter what was in the documentation I could find...
Below is the test function I'm using, this is the function which is called when the user is redirected back to the website AFTER approving the payment.
public function confirmOrder($payer_id, $payment_id, $incentives = false){
//GET PAYMENT
$payment = Payment::get($payment_id, $this->apiContext);
//CREATE EXECUTION WITH PAYER ID
$execution = new PaymentExecution();
$execution->setPayerId($payer_id);
//APPLY PAYMENT AMOUNT - Original amount was 7.00
$amount = new Amount();
$amount = $amount->setCurrency('GBP')->setTotal('8.00');
//PATCH REPLACE
$patchReplace = new Patch();
$patchReplace = $patchReplace->setOp('replace')->setPath('/transactions/0/amount')->setValue($amount);
//CREATE PATCH OBJECT
$patchRequest = new PatchRequest();
$patchRequest = $patchRequest->setPatches(array($patchReplace));
try {
$payment->update($patchRequest, $this->apiContext);
} catch (PayPalConnectionException $ex) {
return "PATCH ERROR: State(" . $payment->getState() . ") ".$ex->getData();
}
}
This isn't the final code I will use but right now I'm just trying to get an order updated before I build in more of the logic. This code gives me the following error:
PATCH ERROR: State(created) {"name":"PAYMENT_STATE_INVALID","message":"This request is invalid due to the current state of the payment","information_link":"https://developer.paypal.com/webapps/developer/docs/api/#PAYMENT_STATE_INVALID","debug_id":"9caacdc1d652b"}
You can see I'm outputting the getState() which is coming back as 'created' which would normally be fine for updating in everything I can find but it is still failing.
Does anyone else have experience with the PayPal PHP SDK and could help point me in the right direction?
In PayPal, once the user has approved the payment from the consent screen, the amount cannot be changed, as you can understand the user agreed to pay only the amount he/she saw on the consent screen. Modifying the amount after user approves it, is not allowed, and that's why you are seeing that state exception, as the state is already approved.
Anyway, looking at your scenario, I think you might be interested in either creating order, or capture, instead of sale.
Also, in our PayPal-PHP-SDK, there are a lot of interesting documents that could help you understand PHP-SDK better. We also provide a lot of runnable samples, that you could setup in your local machine, by one command only.

Magento - Insufficient Stock Notification on Product Page

I am using Magento 1.7.0.2. Whilst on the product page, if a customer attempts to add a quantity greater than we have in stock they receive a message stating ".. the requested quantity is not available".
Is there any way for magento to either email or log when this occurs? I.e. I receive an automatic email stating a customer has attempted to add X number of item X? This would allow me to identify lost sales due to us not having enough stock of a particular item?
Has anyone come across anything like this before or is this even possible?
Thank you in advance
Mike Prentice
yes this is possible
You have to code for this.
I came across this problem one time and what i have do like this below.
I have make one observer event to check if customer is requesting quantity more then available if so i sent email to admin.
What you can do is create one observer for chekout_cart_add_before event in this event you can put your logic.
Or otherwise you can use magento feature Backorders you can find this in inventory tab,if you enable this then customer can order even requested quantity > available quantity, customer can see one message in cart page about backorder.
There is no standart functionality to notify about low quantity products by email.
But there is RSS notification http://www.magentocommerce.com/wiki/modules_reference/english/mage_adminhtml/system_config/edit/cataloginventory
Extend this functionality to match your needs.
You could write some script which would parse RSS, and send email etc.
EDIT
Here is some extension you may like http://www.magentocommerce.com/magento-connect/low-stock-email-notification.html
But is is not free.
Here's how I've done it so that it sends a google analytics tracking event whenever a customer tries to order more than the available stock level.
First copy: app/code/core/Mage/CatalogInventory/Model/Stock/Item.php
To: app/code/local/Mage/CatalogInventory/Model/Stock/Item.php
so that you're not modifying a core file.
In app/code/local/Mage/CatalogInventory/Model/Stock/Item.php add this function
public function notifyOutOfStock($productId){
$session = Mage::getSingleton('checkout/session');
//Initialise as empty array, or use existing session data
$outOfStockItems = array();
if ($session->getOutOfStock()){
$outOfStockItems = $session->getOutOfStock();
}
try {
$product = Mage::getModel('catalog/product')->load($productId);
$sku = $product->getSKu();
if($sku){
//Add the current sku to our out of stock items (if not already there)
if(! isset($outOfStockItems[$sku]) ) {
$outOfStockItems[$sku] = 0;
}
}
} catch (Exception $e){
//Log your error
}
Mage::getSingleton('checkout/session')->setOutOfStock($outOfStockItems);
}
In that same file is another function called checkQuoteItemQty.
Inside that function you need to call your new function using $this->notifyOutOfStock($this->getProductId()); right after it sets each of the error messages and before the return statement.
So:
public function checkQuoteItemQty($qty, $summaryQty, $origQty = 0)
{
....
if ($this->getMinSaleQty() && ($qty) < $this->getMinSaleQty()) {
$result->setHasError(true)
->setMessage(
$_helper->__('The minimum quantity allowed for purchase is %s.', $this->getMinSaleQty() * 1)
)
->setQuoteMessage($_helper->__('Some of the products cannot be ordered in requested quantity.'))
->setQuoteMessageIndex('qty');
//** Call to new function **
$this->notifyOutOfStock($this->getProductId());
return $result;
}
.....
->setQuoteMessageIndex('qty');
//** Call to new function **
$this->notifyOutOfStock($this->getProductId());
return $result;
.....
What this does is add your product sku to an array in the checkout session.
This means you will have access to that info in the template file right after your page loads displaying the "Insufficient stock" notification.
So in one of your template files you can add some code to render the necessary JavaScript.
I've chosen header.phtml since it loads on every page. (Users can add quantities of items to the cart in the cart page as well as the product view page).
app/design/frontend/CUSTOMNAME/default/template/page/html/header.phtml
Somewhere down the bottom of the code add this:
<!-- GA tracking for out of stock items -->
<script>
try {
<?php
$session = Mage::getSingleton('checkout/session');
if ($session->getOutOfStock()){
$outOfStockItems = $session->getOutOfStock();
foreach($outOfStockItems as $sku=>$value) {
if($value==0){
//Render the GA tracking code
echo "_gaq.push(['_trackEvent', 'AddToCart', 'ProductQtyNotAvailable', '".$sku."']); \r\n";
//Set it to 1 so we know not to track it again this session
$outOfStockItems[$sku] = 1;
}
}
//Update the main session
Mage::getSingleton('checkout/session')->setOutOfStock($outOfStockItems);
}
?>
}
catch(err) {
//console.log(err.message);
}
</script>
Can confirm this works well and in my opinion is better than an email or RSS feed as you can analyse it along with the rest of your analytics.

Creating a single random Magento coupon

I'm having some trouble. What I want to do is automatically generate a single random coupon code in Magento each time someone subscribes to our newsletter. The coupon is 10 dollars off anything and will have an exp. date of two weeks after subscription.
So, I'm trying to write a simple script that trips when the "subscribe to our newsletter" form is submitted that will talk to Magento, ask Magento for a single random coupon code, set a few basic price rules (10 bucks off anything, one use per customer, one use per coupon, expires two weeks from generation) and then return a random coupon code (ex:WELCOME5798) which can be stored in a variable that will be passed, along w/ first+last name and e-mail to MailChimp via the MailChimp API. I have all this figured out EXCEPT for how to get Mage to generate such a code via a PHP script and then return said code (i.e. I have my form and I know how to pass values to MailChimp).
I'm new to Magento, so I'm having a tough time. I've seen the code in Mage/SalesRule/Model/Coupon and I've seen some examples of people solving somewhat similar questions, such as here: Magento - Create Unique Coupon Codes through code and mail it to the customer
But I'm really at a loss for where to start making this work for my own purposes. Could use some help/setting straight. :( Thanks folks.
So, what is your question? How to generate coupon for your requirements? Or how to arrange it in module?
You can use event newsletter_subscriber_save_after to inject your custom actions to the subscribe process.
Here is an example of coupon creation according to your needs
<?php
/**
* Create coupon for fixed price discount
*
* #param int $customer_id
* #param float $discount
*/
public function createCoupon($customer_id, $discount)
{
$customer = Mage::getModel('customer/customer')->load($customer_id);
$customerGroupIds = Mage::getModel('customer/group')->getCollection()->getAllIds();
$websitesId = Mage::getModel('core/website')->getCollection()->getAllIds();
$customer_name = $customer->getName();
$couponCode = Mage::helper('core')->getRandomString(9);
$model = Mage::getModel('salesrule/rule');
$model->setName('Discount for ' . $customer_name);
$model->setDescription('Discount for ' . $customer_name);
$model->setFromDate(date('Y-m-d'));
$model->setToDate(date('Y-m-d', strtotime('+2 days')));
$model->setCouponType(2);
$model->setCouponCode($couponCode);
$model->setUsesPerCoupon(1);
$model->setUsesPerCustomer(1);
$model->setCustomerGroupIds($customerGroupIds);
$model->setIsActive(1);
$model->setConditionsSerialized('a:6:{s:4:\"type\";s:32:\"salesrule/rule_condition_combine\";s:9:\"attribute\";N;s:8:\"operator\";N;s:5:\"value\";s:1:\"1\";s:18:\"is_value_processed\";N;s:10:\"aggregator\";s:3:\"all\";}');
$model->setActionsSerialized('a:6:{s:4:\"type\";s:40:\"salesrule/rule_condition_product_combine\";s:9:\"attribute\";N;s:8:\"operator\";N;s:5:\"value\";s:1:\"1\";s:18:\"is_value_processed\";N;s:10:\"aggregator\";s:3:\"all\";}');
$model->setStopRulesProcessing(0);
$model->setIsAdvanced(1);
$model->setProductIds('');
$model->setSortOrder(1);
$model->setSimpleAction('by_fixed');
$model->setDiscountAmount($discount);
$model->setDiscountStep(0);
$model->setSimpleFreeShipping(0);
$model->setTimesUsed(0);
$model->setIsRss(0);
$model->setWebsiteIds($websitesId);
try {
$model->save();
} catch (Exception $e) {
Mage::log($e->getMessage());
}
}

Set subscriber status in Magento programmatically

I am trying to write a module that syncs my newsletter subscribers in Magento with a external database. I need to be able to update the subscription status in Magento programmatically but I am having diffuculty getting the "setStatus" method in Magento to work. It does not throw any errors but the code does not seem to have any effect. Below is the code where I call the method:
$collection = Mage::getResourceModel('newsletter/subscriber_collection')->showStoreInfo()->showCustomerInfo();
foreach ($collection as $cust) {
$cust->setStatus(1);
}
In theory, this should set the status of all of my subscribers to "subscribed". I could optionally change the argument sent to "setStatus" to any of the below ints for a different status.
1: Subscribed
2: Status Not Active
3: Unsubscribed
How to best change the subscriber status or get this code working?
Here an import script:
<?php
require_once("./app/Mage.php");
Mage::app();
$subscribers = array('email1#server1.com', 'email2#server2.com');
foreach ($subscribers as $email) {
# create new subscriber without send an confirmation email
Mage::getModel('newsletter/subscriber')->setImportMode(true)->subscribe($email);
# get just generated subscriber
$subscriber = Mage::getModel('newsletter/subscriber')->loadByEmail($email);
# change status to "subscribed" and save
$subscriber->setStatus(Mage_Newsletter_Model_Subscriber::STATUS_SUBSCRIBED);
$subscriber->save();
}
?>
It seems that newsletter subscribers are also stored elsewhere. What you are setting is just a check in the customer base for some other use.
You need to do the following for each customer as well.
Mage::getModel('newsletter/subscriber')->subscribe($email);
See this link for a complete reference.
Thanks to the link #Ozair shared I was able to figure out what I needed to do.
I was successfully setting the status of the subscriber in the Magento subscriber object but I was not saving the object. I needed to call Magento's save method so it would call the ORM and write it to the database. All I need to do was add
$cust->save();
in the for loop. Below is the whole code snippet.
$collection = Mage::getResourceModel('newsletter/subscriber_collection')->showStoreInfo()->showCustomerInfo();
foreach ($collection as $cust) {
$cust->setStatus(1);
$cust->save();
}
I Hope this helps someone in the future. I needed it for a Constant Contact - Magento Synchronization extension I was making: http://www.freelunchlabs.com/store/constant-contact-and-magento-sync.html

Categories