How to get all order payment method information in magento2 - magento2

I try to get order related information like order status, total amount, payment method etc.
I got order status using
$_order->getStatusLabel();
But how I get payment method-related information in Magento 2.

In Block file
/** #var \Magento\Sales\Model\ResourceModel\Order\Payment\Collection */
protected $_paymentCollectionFactory;
/** #var \Magento\Sales\Model\ResourceModel\Order\CollectionFactory */
protected $_orderCollectionFactory;
/** #var \Magento\Sales\Model\ResourceModel\Order\Collection */
protected $orders;
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,\Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderCollectionFactory, \Magento\Sales\Model\ResourceModel\Order\Payment\CollectionFactory $paymentCollectionFactory, array $data = []
) {
$this->_orderCollectionFactory = $orderCollectionFactory;
$this->_paymentCollectionFactory = $paymentCollectionFactory;
parent::__construct($context, $data);
}
public function getPaymentsCollection() {
$collection = $this->_paymentCollectionFactory->create()->addFieldToSelect('*');
return $collection;
}
public function getOrders($storeId) {
if (!$this->orders) {
$this->orders = $this->_orderCollectionFactory->create()->addFieldToSelect('*');
}
return $this->orders;
}
In phtml file
$_orders = $block->getOrders();
if ($_orders && count($_orders)) {
$payments = $block->getPaymentsCollection();
$chekmo = $cod = $free = $bank = $paypalgrp = 0;
foreach ($payments as $_payment) {
$method = $_payment->getMethod();
switch ($method) {
case 'checkmo' : $chekmo++;
break;
case 'cashondelivery' : $cod++;
break;
case 'free' : $free++;
break;
case 'banktransfer' : $bank++;
break;
case 'paypal_group_all_in_one' : $paypalgrp++;
break;
}
}
echo "Payment Methods<br>";
echo "Check / Money Order Methods " . $ckeckmo;
echo "Cash on Delivery Methods " . $cod;
echo "Free Methods " . $free;
echo "Bank Transfer Methods " . $bank;
echo "Paypal group all in one Methods " . $paypalgrp;
}
else{
echo "You have no Orders";
}

Following code will be helpful
$orderId = 1001;
$order = $this->order->load($orderId);
$method=$order->getPayment()->getMethod();
$expmonth=$order->getPayment()->getCcExpMonth();
$expyear=$order->getPayment()->getCcExpYear();
$cclast4=$order->getPayment()->getCcLast4();
$ipaddress=$order->getRemoteIp();
$billingaddress=$order->getBillingAddress();
$billingcity=$billingaddress->getCity();
$billingstreet=$billingaddress->getStreet();
$billingpostcode=$billingaddress->getPostcode();
$billingtelephone=$billingaddress->getTelephone();
$billingstate_code=$billingaddress->getRegionCode();
$shippingaddress=$order->getShippingAddress();
$shippingcity=$shippingaddress->getCity();
$shippingstreet=$shippingaddress->getStreet();
$shippingpostcode=$shippingaddress->getPostcode();
$shippingtelephone=$shippingaddress->getTelephone();
$shippingstate_code=$shippingaddress->getRegionCode();
$tax_amount=$order->getTaxAmount();
$total=$order->getGrandTotal();
It's work like a charm

Related

Issue when updating a product in magento 2 from command line

Update the product status in Magento 2
When updating the status of a product I get the following issue:
UpdateStatus.php
public function __construct(
ProductRepositoryInterface $productRepository,
SearchCriteriaBuilder $searchCriteriaBuilder,
Product $product,
Configurable $configurable,
StockItem $stockItem,
State $state
)
{
parent::__construct();
$this->productRepository = $productRepository;
$this->searchCriteriaBuilder = $searchCriteriaBuilder;
$this->_product = $product;
$this->configurable = $configurable;
$this->stockItem = $stockItem;
$this->state = $state;
}
protected function execute(InputInterface $input, OutputInterface $output): ?int
{
$this->state->setAreaCode(Area::AREA_ADMINHTML);
$product = $this->_product->loadByAttribute('sku', '46-50953763');
$product->setStatus(2);
$product->save();
return 0;
}
And also I tried using the repository:
$product = $this->productRepository->get('46-50953763');
$product->setStatus(2);
try {
$this->productRepository->save($product);
} catch (\Exception $e) {
var_dump($e->getMessage());
}
What is the way to update a magento product from command line?

Magento 2: change order status programmatically

I need to set in "canceled" all orders stucks in "pending" status.
The code that I used return this exception error:
[2022-12-03 08:00:53] main.CRITICAL: Please provide payment for the order.
Here the code:
use Magento\Sales\Model\Order;
protected $order;
public function __construct(Order $order)
{
$this->order = $order;
}
public function orderStatusChange()
{
$orderId = 9999;
$order = $this->order->load($orderId);
$order->setStatus("canceled");
$order->save();
}
Please create a new file on the magento2 root and add below code:
use Magento\Framework\App\Bootstrap;
require __DIR__ . '/app/bootstrap.php';
$params = $_SERVER;
$bootstrap = Bootstrap::create(BP, $params);
$obj = $bootstrap->getObjectManager();
$state = $obj->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
$orderId = '12345';
$order = $obj->create('\Magento\Sales\Model\OrderRepository')->get($orderId);
$order->setStatus("canceled");
$order->setState("canceled");
$order->save();
echo "Order updated";

Magento 2 - Newsletter subscription issue

I use Martfury theme. When I subscribe to newsletter, it redirects me to /newsletter/subscriber/new/ and there is this message (JSON): {"success":true,"message":"Thank you for your subscription.","redirect":false}
Image:
It should show only notification and not redirect to that URL. In Martfury theme demo it works well.
Code:
In your theme, please check the newsletter controller return. Debug execute function line by line.
controller path: module-newsletter/Controller/Subscriber/NewAction
Then you can check the below function:
/**
* New subscription action
*
* #return Redirect
*/
public function execute()
{
if ($this->getRequest()->isPost() && $this->getRequest()->getPost('email')) {
$email = (string)$this->getRequest()->getPost('email');
try {
$this->validateEmailFormat($email);
$this->validateGuestSubscription();
$this->validateEmailAvailable($email);
$websiteId = (int)$this->_storeManager->getStore()->getWebsiteId();
/** #var Subscriber $subscriber */
$subscriber = $this->_subscriberFactory->create()->loadBySubscriberEmail($email, $websiteId);
if ($subscriber->getId()
&& (int)$subscriber->getSubscriberStatus() === Subscriber::STATUS_SUBSCRIBED) {
throw new LocalizedException(
__('This email address is already subscribed.')
);
}
$storeId = (int)$this->_storeManager->getStore()->getId();
$currentCustomerId = $this->getCustomerId($email, $websiteId);
$subscriber = $currentCustomerId
? $this->subscriptionManager->subscribeCustomer($currentCustomerId, $storeId)
: $this->subscriptionManager->subscribe($email, $storeId);
$message = $this->getSuccessMessage((int)$subscriber->getSubscriberStatus());
$this->messageManager->addSuccessMessage($message);
} catch (LocalizedException $e) {
$this->messageManager->addComplexErrorMessage(
'localizedSubscriptionErrorMessage',
['message' => $e->getMessage()]
);
} catch (\Exception $e) {
$this->messageManager->addExceptionMessage($e, __('Something went wrong with the subscription.'));
}
}
/** #var Redirect $redirect */
$redirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
// phpcs:ignore Magento2.Legacy.ObsoleteResponse
$redirectUrl = $this->_redirect->getRedirectUrl();
return $redirect->setUrl($redirectUrl);
}

Why doesn't this class that I called inside the method run?

I called a method from one class in another method but my class in not running.
My problem is the line that says sms::dispatch.
I will also make sure that all lines are executed, that is, both inside if and inside foreach.
The queries are also executed.
public function handle()
{
$custoemrsBirthDays = DB::table("customers")->pluck("birth_day");
foreach ($custoemrsBirthDays as $custoemrBirthDay) {
$getMonthAndDay = date('m-d', strtotime($custoemrBirthDay . "+1 day"));
if ($getMonthAndDay == Carbon::now()->format('m-d')) {
$customer = DB::table("customers")
->where("birth_day", $custoemrBirthDay)
->first();
$coupon = new Coupon();
$coupon->coupon = 'birthday' . rand(1, 1000) . '';
$coupon->discount = 13;
$coupon->save();
$coupon->customers()->attach($customer->id);
$customerMobileNumber = DB::table("mobile_numbers")
->where("customer_id", $customer->id)
->where(['is_default' => 1])
->first();
$mobileNumber = $customerMobileNumber->mobile_number;
$SMSText = "سلام خوشتیپ تولدت مبارک با این کوپن حتما یه سری به آرایشگاهمون بزن : " . $coupon->coupon . "";
SMSLog::dispatch($SMSText, $mobileNumber);
}
}
return "no birth day";
}
This is from my class :
class SMSLog implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/**
* Create a new job instance.
*
* #return void
*/
protected $sms_text;
protected $mobileNumber;
public function __construct($sms_text, $mobileNumber)
{
$this->sms_text = $sms_text;
$this->mobileNumber = $mobileNumber;
}
/**
* Execute the job.
*
* #return void
*/
public function handle()
{
log::info("send sms message ($this->sms_text) to $this->mobileNumber");
}
}

using Zend_Service_Ebay_Finding to retrieve sellers items

I wish to retrieve all sellers items using the findItemsAdvanced call of Zend_Service_Ebay_Finding API. I'm a bit confused as to how to use it? has anyone got a example of how this method works? I tried
$response = $finding->findItemsAdvanced('seller=<SELLERNAME>');
But gives me nothing?
Would appreciate any help
In the end I overloaded the Zend_Service_Ebay_Finding API and added 2 methods to grab me all the seller info. Maybe this will help anyone else with the same issue.
/**
* Finds items for a specific seller
* and a page
*
* #param string $seller
* #param int $page
* #return Zend_Service_Ebay_Finding_Response_Items
*/
public function sellerItems($seller, $page = 1){
// prepare options
$options = array('itemFilter(0).name' => 'Seller', 'itemFilter(0).value(0)' => $seller, 'paginationInput.entriesPerPage' => 100);
// do request
return $this->_findItems($options, 'findItemsAdvanced');
}
/**
* Finds items for a specific seller - iterates through pages
* and a page
*
* #param string $seller
* #return array
*/
public function getAllSellerItems($seller) {
$page1 = $this->sellerItems($seller);
$pages = $page1->paginationOutput->totalPages;
$items = $page1->searchResult->item;
$full = array();
foreach($items as $item) {
$full[] = $item;
}
if($pages > 1) {
for($i = 2;$i <= $pages; $i ++) {
$results = $this->sellerItems($seller, $i);
$items = $results->searchResult->item;
foreach($items as $item) {
$full[] = $item;
}
}
}
return $full;
}