Is there a way to programmatically mark a shipping email as sent? After combing through Google for some help, I have come up empty handed.
I have set up an observer to send out an email as soon as a tracking number is added to a shipment, but I need to be able to some how show in the admin that the email has been sent instead of displaying "the shipment email is not sent."
UPDATE
Here is the code that I have. I can get the email to send just fine, but I cannot get the email_sent flag to be set
class WR_TrackingEmail_Model_Observer
{
public function sendTrackEmail($observer)
{
$track = $observer->getEvent()->getTrack();
$shipment = $track->getShipment(true);
$shipment->sendEmail();
$shipment->setEmailSent(true);
}
}
UPDATE 2
After trying the following code, I run into a new issue. The item is marked as shipped but for some reason I get a million copies of the shipping email. I am assuming that a loop is happening somewhere. Can anyone tell me what I am doing wrong here?
public function sendTrackEmail($observer)
{
$track = $observer->getEvent()->getTrack();
$shipment = $track->getShipment(true);
$shipment->sendEmail();
$shipment->setEmailSent(true);
$saveTransaction = Mage::getModel('core/resource_transaction')
->addObject($shipment)
->addObject($shipment->getOrder())
->save();
}
Normally this is the way to set all the Shipment statuses, along with all the notification emails:-
$_eachOrderTrackingNum = 'ANY_SPECIFIC_TRACKING_NUMBER';
$arrTracking = array(
'carrier_code' => 'ups',
'title' => 'United Parcel Service',
'number' => $_eachOrderTrackingNum,
);
$track = Mage::getModel('sales/order_shipment_track')->addData($arrTracking);
$shipment->addTrack($track);
$emailSentStatus = $shipment->getData('email_sent');
$customerEmail = $order->getData('customer_email');
if (!is_null($customerEmail) && !$emailSentStatus) {
$shipment->sendEmail($customerEmail, '');
$shipment->setEmailSent(true);
}
$saveTransaction = Mage::getModel('core/resource_transaction')
->addObject($shipment)
->addObject($shipment->getOrder())
->save();
Here "$shipment" is an object of "Mage_Sales_Model_Order_Shipment", after the order has been converted to this Shipment object. Also the "$order" is the specific Order object.
Hope it helps.
UPDATE
After seeing your update, it seems that you need to use the following code for your method "sendTrackEmail()":-
public function sendTrackEmail($observer)
{
$track = $observer->getEvent()->getTrack();
$shipment = $track->getShipment(true);
$shipment->sendEmail();
$shipment->setEmailSent(true);
$saveTransaction = Mage::getModel('core/resource_transaction')
->addObject($shipment)
->addObject($shipment->getOrder())
->save();
}
Related
I'm facing one issue while splitting the order on checkout. I followed these code mentioned in the link:-
https://magento.stackexchange.com/questions/196669/magento-2-split-order-for-every-item
and
https://github.com/magestat/magento2-split-order
Both solution is working with offline payment like check/mo, Cash on delivery, po number etc. But its not working with credit card details. Always getting error regarding credit card details.
I'm putting some more information through code:-
I am stuck at a point to distribute order and assign payment method into it.
there are two scenario i'm getting:
if i assign payment method checkmo,Cash on delivery then order is splitted and everything is working fine with this.
But i need to order products using credit card and when i assign payment method code(credit card payment method is 'nmi_directpost') and also assign card details into quote and placed and order then its showing me error differently, Some time its shows credit card details is not valid, sometime page is redirected to cart page without any log/exception. Here is bunch of code i'm trying to do:-
public function aroundPlaceOrder(QuoteManagement $subject, callable $proceed, $cartId, $payment = null)
{
$currentQuote = $this->quoteRepository->getActive($cartId);
// Separate all items in quote into new quotes.
$quotes = $this->quoteHandler->normalizeQuotes($currentQuote);
if (empty($quotes)) {
return $result = array_values([($proceed($cartId, $payment))]);
}
// Collect list of data addresses.
$addresses = $this->quoteHandler->collectAddressesData($currentQuote);
/** #var \Magento\Sales\Api\Data\OrderInterface[] $orders */
$orders = [];
$orderIds = [];
foreach ($quotes as $items) {
/** #var \Magento\Quote\Model\Quote $split */
$split = $this->quoteFactory->create();
// Set all customer definition data.
$this->quoteHandler->setCustomerData($currentQuote, $split);
$this->toSaveQuote($split);
// Map quote items.
foreach ($items as $item) {
// Add item by item.
$item->setId(null);
$split->addItem($item);
}
\Magento\Framework\App\ObjectManager::getInstance()->get('Psr\Log\LoggerInterface')->info('new quote 1st :-'. print_r($split->getData(),true));
$this->quoteHandler->populateQuote($quotes, $split, $items, $addresses, $payment);
// $split->getPayment()->setMethod('nmi_directpost');
// if ($payment) {
// $split->getPayment()->setQuote($split);
// $data = $payment->getData();
// $paymentDetails = $paymentCardDetails = '';
// $postData = file_get_contents("php://input");//Get all param
// $postData = (array)json_decode($postData);//Decode all json param
// foreach ($postData as $key => $value) {
// if ($key == 'paymentMethod') { //Get paymentMethod details
// $paymentDetails = (array)$value;
// foreach ($paymentDetails as $key1 => $paymentValue) {
// if ($key1 == 'additional_data') { //get paymentMethod Details like card details
// $paymentCardDetails = (array)$paymentValue;
// }
// }
// }
// }
// $split->setMethod('checkmo');
\Magento\Framework\App\ObjectManager::getInstance()->get('Psr\Log\LoggerInterface')->info('Paynet :-');
// $payment = $quotes->getPayment();
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$cart = $objectManager->get('\Magento\Checkout\Model\Cart');
$quote = $cart->getQuote();
$paymentMethod = $quote->getPayment()->getMethod();
$payment = $this->checkoutSession->getQuote()->getData();
\Magento\Framework\App\ObjectManager::getInstance()->get('Psr\Log\LoggerInterface')->info('second Paynet :-');
\Magento\Framework\App\ObjectManager::getInstance()->get('Psr\Log\LoggerInterface')->info('new quote :-'. print_r($paymentMethod,true));
// $split->setPayment($payment);
// $split->getPayment()->importData(array(
// 'method' =>'nmi_directpost',
// 'cc_type' =>'VI',
// 'cc_number' =>'4111111111111111',
// 'cc_exp_year' =>'2025',
// 'cc_exp_month'=>'10',
// ));
// }
// \Magento\Framework\App\ObjectManager::getInstance()->get('Psr\Log\LoggerInterface')->info('original quote :-'. print_r($quotes->getData(),true));
\Magento\Framework\App\ObjectManager::getInstance()->get('Psr\Log\LoggerInterface')->info('new quote :-'. print_r($split->getData(),true));
// \Magento\Framework\App\ObjectManager::getInstance()->get('Psr\Log\LoggerInterface')->info('new quote :-'. print_r($payment->getData(),true));
// Dispatch event as Magento standard once per each quote split.
$this->eventManager->dispatch(
'checkout_submit_before',
['quote' => $split]
);
$this->toSaveQuote($split);
$order = $subject->submit($split);
$orders[] = $order;
$orderIds[$order->getId()] = $order->getIncrementId();
if (null == $order) {
throw new LocalizedException(__('Please try to place the order again.'));
}
}
$currentQuote->setIsActive(false);
$this->toSaveQuote($currentQuote);
$this->quoteHandler->defineSessions($split, $order, $orderIds);
$this->eventManager->dispatch(
'checkout_submit_all_after',
['orders' => $orders, 'quote' => $currentQuote]
);
return $this->getOrderKeys($orderIds);
}
Please suggest how can we achieve order splitting with credit card payment.
Splitting payment across multiple credit cards like this is referred to as 'partial authorization'. (Note: This is a very different thing from 'partial invoicing' or 'partial capturing', terms you'll also see thrown around.)
Magento's default Authorize.Net gateway includes partial authorization functionality, you just have to enable it in the gateway settings. This works with both Community and Enterprise Edition. See official documentation on the setup and workflow here.
To my knowledge, this is the only payment method that supports it.
Note that the customer does not get to choose how much to charge to each card. Rather, if the card they enter does not have sufficient funds, they will be prompted to enter another one.
I'm trying to generate PayPal link to email, where user can pay for their order later. I'am using paypal/rest-api-sdk-php. For example using this route:
Route::get('/order/pay/{hash}', 'Frontend\PaymentController#orderPay')->name('order.pay');
My code for payment creation works (see code). When user cancel the payment or payment is unsuccessful, how can I return to the incomplete transaction and try to pay for it again? Should I create new payment everytime user goes to order pay route? Or can I simply identify the incomplete transaction in PayPal and redirect to some(?) PayPal link then?
use PayPal\Api\Payer;
use PayPal\Api\Item;
use PayPal\Api\ItemList;
use PayPal\Api\Details;
use PayPal\Api\Amount;
use PayPal\Api\Transaction;
use PayPal\Api\RedirectURLs;
use PayPal\Api\Payment;
/*
* #param \App\Order $order
* #return string
*/
public function createPayment($order)
{
$transaction = $this->getTransactionByOrderHash($order->hash);
if ($transaction) {
if ($transaction->is_refunded) {
return 'Paymant has already been refunded';
}
if ($transaction->is_payed) {
return 'Paymant has already been payed';
}
}
$price = $order->to_pay;
$currencyCode = $order->currency->iso_code;
try {
$payer = new Payer();
$payer->setPaymentMethod('paypal');
$item = new Item();
$item
->setName(__('invoice.pfa_title'))
->setCurrency($currencyCode)
->setQuantity(1)
->setSku($order->vs)
->setPrice($price);
$itemList = new ItemList();
$itemList->setItems([$item]);
$details = new Details();
$details
->setShipping(0)
->setTax(0)
->setSubtotal($price);
$amount = new Amount();
$amount
->setCurrency($currencyCode)
->setTotal($price)
->setDetails($details);
$transaction = new Transaction();
$transaction
->setAmount($amount)
->setItemList($itemList)
->setInvoiceNumber(uniqid());
$redirectUrls = new RedirectUrls();
$redirectUrls
->setReturnUrl(route('paypal.success', $order->hash))
->setCancelUrl(route('paypal.cancel'));
$payment = new Payment();
$payment
->setIntent('sale')
->setPayer($payer)
->setRedirectUrls($redirectUrls)
->setTransactions([$transaction]);
$payment->create($this->apiContext);
$approvalUrl = $this->getApprovalUrl($payment);
if ($approvalUrl) {
session([
'approval_url' => $approvalUrl,
'transaction_id' => $payment->getId(),
]);
return 'payment was successful';
}
} catch (PayPalConnectionException $ex) {
return json_decode($ex->getData());
} catch (Throwable $e) {
return $e->getMessage();
}
return 'payment was unsuccessful';
}
Why use the deprecated v1/payments PayPal-PHP-SDK, instead of the current v2/checkout/orders Checkout-PHP-SDK ?
In any case, yes you can create a new Payment/Order object everytime the customer attempts a checkout. Just set the invoice_id field to your own same but unique invoice/order number for the thing that customer is paying for, so that if the customer does happen to be trying to make a duplicate payment attempt for such a # that has already resulted in a successful transaction on your PayPal account before, it will be blocked by default (according to your PayPal account settings)
I'm struggling to get either to work and Omnipay doesn't come with much documentation. I've successfully used it for other payment gateways but not with Sagepay. I'm trying to integrate it into CodeIgniter but can work from examples in other frameworks - I'm getting desperate!
Thanks to some great help on github (see comments in my original post for the thread link), I now have some workable code which I will share here in case it helps someone else in the future.
<?php
use Omnipay\Omnipay;
class PaymentGateway {
//live details
private $live_vendor = 'xxx';
//test details
private $test_vendor= 'xxx';
//payment settings
private $testMode = true;
private $api_vendor = '';
private $gateway = null;
public function __construct()
{
parent::__construct();
//setup api details for test or live
if ($this->testMode) :
$this->api_vendor = $this->test_vendor;
else :
$this->api_vendor = $this->live_vendor;
endif;
//initialise the payment gateway
$this->gateway = Omnipay::create('SagePay_Server');
$this->gateway->setVendor($this->api_vendor);
$this->gateway->setTestMode($this->testMode);
}
public function initiate()
{
//get order details
$orderNo = customFunctionToGetOrderNo(); //get the order number from your system however you store and retrieve it
$params = array(
'description'=> 'Online order',
'currency'=> 'GBP',
'transactionId'=> $orderNo,
'amount'=> customFunctionToGetOrderTotal($orderNo)
);
$customer = customFunctionToGetCustomerDetails($orderNo);
$params['returnUrl'] = '/payment-gateway-process/' . $orderNo . '/'; //this is the Sagepay NotificationURL
$params['card'] = array(
'firstName' => $customer['billing_firstname'],
'lastName' => $customer['billing_lastname'],
'email' => $customer['billing_email'],
'billingAddress1' => $customer['billing_address1'],
'billingAddress2' => $customer['billing_address2'],
'billingCity' => $customer['billing_town'],
'billingPostcode' => $customer['billing_postcode'],
'billingCountry' => $customer['billing_country'],
'billingPhone' => $customer['billing_telephone'],
'shippingAddress1' => $customer['delivery_address1'],
'shippingAddress2' => $customer['delivery_address2'],
'shippingCity' => $customer['delivery_town'],
'shippingPostcode' => $customer['delivery_postcode'],
'shippingCountry' => $customer['delivery_country']
);
try {
$response = $this->gateway->purchase($params)->send();
if ($response->isSuccessful()) :
//not using this part
elseif ($response->isRedirect()) :
$reference = $response->getTransactionReference();
customFunctionToSaveTransactionReference($orderNo, $reference);
$response->redirect();
else :
//do something with an error
echo $response->getMessage();
endif;
} catch (\Exception $e) {
//do something with this if an error has occurred
echo 'Sorry, there was an error processing your payment. Please try again later.';
}
}
public function processPayment($orderNo)
{
$params = array(
'description'=> 'Online order',
'currency'=> 'GBP',
'transactionId'=> $orderNo,
'amount'=> customFunctionToGetOrderTotal($orderNo)
);
$customer = customFunctionToGetCustomerDetails($orderNo);
$transactionReference = customFunctionToGetTransactionReference($orderNo);
try {
$response = $this->gateway->completePurchase(array(
'transactionId' => $orderNo,
'transactionReference' => $transactionReference,
))->send();
customFunctionToSaveStatus($orderNo, array('payment_status' => $response->getStatus()));
customFunctionToSaveMessage($orderNo, array('gateway_response' => $response->getMessage()));
//encrypt it to stop anyone being able to view other orders
$encodeOrderNo = customFunctionToEncodeOrderNo($orderNo);
$response->confirm('/payment-gateway-response/' . $encodeOrderNo);
} catch(InvalidResponseException $e) {
// Send "INVALID" response back to SagePay.
$request = $this->gateway->completePurchase(array());
$response = new \Omnipay\SagePay\Message\ServerCompleteAuthorizeResponse($request, array());
customFunctionToSaveStatus($orderNo, array('payment_status' => $response->getStatus()));
customFunctionToSaveMessage($orderNo, array('gateway_response' => $response->getMessage()));
redirect('/payment-error-response/');
}
}
public function paymentResponse($encodedOrderNo)
{
$orderNo = customFunctionToDecode($encodedOrderNo);
$sessionOrderNo = customFunctionToGetOrderNo();
if ($orderNo != $sessionOrderNo) :
//do something here as someone is trying to fake a successful order
endif;
$status = customFunctionToGetOrderStatus($orderNo);
switch(strtolower($status)) :
case 'ok' :
customFunctionToHandleSuccess($orderNo);
break;
case 'rejected' :
case 'notauthed' :
//do something to handle failed payments
break;
case 'error' :
//do something to handle errors
break;
default:
//do something if it ever reaches here
endswitch;
}
}
I gave a talk last night about this, and have put the working demo scripts on github here:
https://github.com/academe/OmniPay-SagePay-Demo
SagePay Direct is a one-off action - OmniPay sends the transaction details and gets an immediate response.
SagePay Server involves a redirect of the user to the SagePay website to authorise the transaction using their card details. This API uses a notify message, where SagePay will call your application directly with the authorisation results. This happens outside of the user's session, and so requires the transaction to be stored in the database so it can be shared between the two transactions.
All this is in the scripts linked above. authorize.php will do the authorisation. Edit that to use SagePay\Direct or SagePay\Server to see how it works. The notification handler for SagePay\Server is sagepay-confirm.php and that ultimately sends the user to final.php where the result can be read from the transaction stored in the database.
The scripts are all commented and should make sense, but feel free to ask more questions about them here or in the issue tracker of that github repository.
I've not tried SagePay\Direct with 3D-Secure though. The scripts may need some modification to support that, assuming that combination is a thing.
I'm trying to send a confirmation email when a subscription order is created in magento but is not sending anything.
i know email configuration its fine because when i buy a regular product i do receive the email.
i created a template on System -> Transactional Emails , template with id=12, then on code on class AW_Sarp2_Model_Checkout_Type_Onepage extends Mage_Checkout_Model_Type_Onepage i call to send subs email method but it never sends any email
class AW_Sarp2_Model_Checkout_Type_Onepage extends Mage_Checkout_Model_Type_Onepage
{
public function saveOrder()
{ Mage::log("checkout/onepage",null,"onepageemail.log");
$isQuoteHasSubscriptionProduct = Mage::helper('aw_sarp2/quote')->isQuoteHasSubscriptionProduct(
$this->getQuote()
);
if (!$isQuoteHasSubscriptionProduct) //HERE I ASK IF IS A SUBSCRIBE PRODUCT {Mage::log("checkout/onepage34",null,"onepageemail.log");
return parent::saveOrder();
}
$this->validate();
$isNewCustomer = false;
switch ($this->getCheckoutMethod()) {
case self::METHOD_GUEST:Mage::log("checkout/onepage40",null,"onepageemail.log");
$this->_prepareGuestQuote();
break;
case self::METHOD_REGISTER:Mage::log("checkout/onepage43",null,"onepageemail.log");
$this->_prepareNewCustomerQuote();
$isNewCustomer = true;
break;
default:Mage::log("checkout/onepage47",null,"onepageemail.log");
$this->_prepareCustomerQuote();
break;
}
if ($this->getQuote()->getCustomerId()) {Mage::log("checkout/onepage52",null,"onepageemail.log");
$this->getQuote()->getCustomer()->save();
}
#AW_SARP2 override start
$service = Mage::getModel('aw_sarp2/sales_service_profile', $this->getQuote());Mage::log("checkout/onepage56",null,"onepageemail.log");
$service->submitProfile();Mage::log("checkout/onepage57",null,"onepageemail.log");
#AW_SARP2 override end
$this->getQuote()->save();Mage::log("checkout/onepage60",null,"onepageemail.log");
if ($isNewCustomer) {Mage::log("checkout/onepage61",null,"onepageemail.log");
try {
$this->_involveNewCustomer();Mage::log("checkout/onepage63",null,"onepageemail.log");
} catch (Exception $e) {
Mage::logException($e);
}
}
$this->_checkoutSession->setLastQuoteId($this->getQuote()->getId())
->setLastSuccessQuoteId($this->getQuote()->getId())
->clearHelperData();Mage::log("checkout/onepage71",null,"onepageemail.log");
// add recurring profiles information to the session
$profiles = $service->getRecurringPaymentProfiles();Mage::log("checkout/onepage73",null,"onepageemail.log");
if ($profiles) {Mage::log("checkout/onepage74",null,"onepageemail.log");
$ids = array();
foreach ($profiles as $profile) {
$ids[] = $profile->getId();
}Mage::log("checkout/onepage78",null,"onepageemail.log");
$this->sendSubscribeEmail2();Mage::log("checkout/onepage79",null,"onepageemail.log");
$this->_checkoutSession->setLastRecurringProfileIds($ids);
Mage::log("checkout/onepage82",null,"onepageemail.log");
}
return $this;
}
public function sendSubscribeEmail2(){ //HERE I TRY TO SEND THE EMAIL
$templateId = 12;
// Set sender information
$senderName = Mage::getStoreConfig('trans_email/ident_support/name');
$senderEmail = Mage::getStoreConfig('trans_email/ident_support/email');
$sender = array('name' => $senderName,
'email' => $senderEmail);
// Set recepient information
$recepientEmail = 'minorandres#gmail.com';
$recepientName = 'Test Test';
// Get Store ID
$storeId = Mage::app()->getStore()->getId();
// Set variables that can be used in email template
$vars = array('customerName' => 'test',
'customerEmail' => 'minorandres#gmail.com');
$translate = Mage::getSingleton('core/translate');Mage::log("checkout/onepage103",null,"onepageemail.log");
// Send Transactional Email
Mage::getModel('core/email_template')
->sendTransactional($templateId, $sender, $recepientEmail, $recepientName, $vars, $storeId);Mage::log("checkout/onepage106",null,"onepageemail.log");
if (!Mage::getModel('core/email_template')->getSentSuccess()) {
Mage::log("EXCEPTION!!!! =( checkout/onepage107",null,"onepageemail.log");
}
is there something in xml files that i have to do or other place?, please help me
Since i am dealing with subscription products they are handle by a different SMTP provider, on the exception.log i got and error "Mandril cant send email" something like that then i went to Admin Panel and under system>transactional emails has a subtab called mandril i configured that tool and create an account on mandril, then i put the API key indicaded by mandril into system>configuration>mandril(on left side).
Hello I have a forum and when a user creates a comment, I want that if he didn't type anything I want to show him an error that he must type something in :) but I dont know how to put him the the thread he is in.
I have this
if($this->_submit_validate_comment() == false) {
$this->post(); return;
}
function _submit_validate_comment() {
$this->form_validation->set_rules('kommentar', 'kommentar', 'required|min_length[4]');
return $this->form_validation->run();
}
You could do this with jquery but if that is not an option you could get the forum or topic id from the url (assuming your are using the url this way).
For example:
http://yoursite.com/forum/topic/12
if($this->_submit_validate_comment() == false)
{
$topic_id = $this->uri->segment(3);
redirect('/forum/topic/'. $topic_id);
}
Or
if($this->_submit_validate_comment() == false)
{
$topic_id = $this->uri->segment(3);
$this->topic($topic_id);
}
Hope this helps.
Thanks for helping i can see what you mean but it just dont work :b,
i have this
$topic_id = $this->uri->segment(3);
$this->post($topic_id);
return;
and my url is
localhost:8888/ci/index.php/forum/create_comment
it looks like it cant find the ID
my URL to the forum is
localhost:8888/ci/index.php/forum/post/33
this is my functions
function create_comment() {
if($this->_submit_validate_comment()
== false) { $id = $this->uri->segment(3);
$this->post($id); return;
//echo "validate fejl, kontakt lige
en admin!"; } else { $data =
array( 'fk_forum_traad' =>
$this->input->post('id'),
'brugernavn' =>
$this->session->userdata('username'),
'indhold' =>
$this->input->post('kommentar'),
'dato' => 'fejl' );
$this->load->model('forum_model');
$this->forum_model->create_comment($data);
redirect('/forum/post/'.
$this->input->post('id').'',
'refresh'); }
}
function post($id) {
$this->load->model('forum_model');
$data['query'] =
$this->forum_model->posts($this->uri->segment(3));
$this->load->model('forum_model');
$data['comments'] =
$this->forum_model->comments($this->uri->segment(3));
$data['content'] = 'forum_post_view';
$this->load->view('includes/template',
$data); }
Why not pass in the return uri in the form submission using a hidden input field? No additional work will be needed by the controller other than validation of the return uri before performing a redirect.
Place the validation error string in session class's flashdata for echoing out in the form, along with any other data used to pre-populate your form)