Laravel Paypal error when adding PayPal::details() in transaction - laravel-5

First time doing paypal integration in laravel. I'm trying to add details such as subtotal of items and totaltax, I have this controller.
$payer = PayPal::Payer();
$payer->setPaymentMethod('paypal');
$item1 = PayPal::item();
item1->setName('Item1 name')
->setDescription('item1 description')
->setCurrency('USD')
->setQuantity(1)
->setPrice(35);
$item2 = PayPal::item();
$item2->setName('Item2 name')
->setDescription('item2 description')
->setCurrency('USD')
->setQuantity(1)
->setPrice(300);
$itemList = PayPal::itemList();
$itemList->setItems(array($item1,$item2));
$details = PayPal::Details();
$details->setShipping(1);
$details->setTax(10);
$details->setSubtotal(17.5);
$amount = PayPal::Amount();
$amount->setCurrency('USD');
$amount->setTotal(335)
->setDetails($details);
$transaction = PayPal::Transaction();
$transaction->setAmount($amount);
$transaction->setItemList($itemList);
$transaction->setDescription('What are you selling?');
$redirectUrls = PayPal:: RedirectUrls();
$redirectUrls->setReturnUrl(action('paypal_Controller\paypalctr#getDone'));
$redirectUrls->setCancelUrl(action('paypal_Controller\paypalctr#getCancel'));
$payment = PayPal::Payment();
$payment->setIntent('sale');
$payment->setPayer($payer);
$payment->setRedirectUrls($redirectUrls);
$payment->setTransactions(array($transaction));
$response = $payment->create($this->_apiContext);
$redirectUrl = $response->links[1]->href;
return Redirect::to( $redirectUrl );
I got this error:
PayPalConnectionException in PayPalHttpConnection.php line 177:
Got Http response code 400 when accessing https://api.sandbox.paypal.com/v1/payments/payment.
But when I remove ->setDetails($details), it works but no subtotal.

I figured out that Paypal only accepts correct computation.
If you want to add totaltax u need to add ->setTax() per item.
$item1 = PayPal::item();
$item1->setName('Item1 Name')
->setDescription('Item1 Description')
->setCurrency('USD')
->setQuantity('2')
->setTax(2.0)
->setPrice('350');
$item2 = PayPal::item();
$item2->setName('Item2 Name')
->setDescription('Item2 Description')
->setCurrency('USD')
->setQuantity('1')
->setTax(0)
->setPrice('300');
Then computation must be correct.item1 tax =(2.0 * 2) + item2 tax = 0 totaltax = 4.0 item1 price = (350 * 2) + item2 price = 300 subtotal = 1000.
$details = PayPal::details();
$details->setShipping('0');
$details->setTax(4.0);
$details->setSubtotal('1000');
shipping + totaltax + subtotal = 1004.0
$amount = PayPal::Amount();
$amount->setCurrency('USD');
$amount->setTotal(1004.0);
$amount->setDetails($details);
Hope it will help someone. :)

Related

Laravel 5.5 Data is being inserted twice in database

This code enters multiple products in orders table, but what strange thing is happening is if i insert 2 products, data is being entered 4 times, if i insert 1 product it is being inerted 2 times. What is wrong with this code ?
foreach($request->product_id as $rpk => $rpv)
{
$data = new Order();
$data->user_id = $request->customer_id[$rpk];
$data->status = $request->status[$rpk];
$data->save();
Order::where('id', $data->id)->update(['order_number' => $data->id]);
// For OrderDetail
$detail = new OrderDetail();
$detail->customer_id = $request->customer_id[$rpk];
$detail->order_id = $data->id;
$detail->product_id = $request->product_id[$rpk];
$detail->price = $request->price[$rpk];
$detail->quantity = $request->quantity[$rpk];
$detail->total = $request->total[$rpk];
$detail->comment = $request->comment[0];
$detail->date = date('Y-m-d H:i:s');
$detail->bill_date = date('Y-m-d H:i:s');
//$detail->sales_tax = '13'; // Need to change this
$success = $detail->save();
}

Magento - Mage_Core_Exception: Please select a valid payment method

I create order promatically with below code
function createSaleOrderForMagento()
{
$customer_id = $this->sale_lib->get_customer();
$items = $this->sale_lib->get_cart();
if($customer_id==-1)
{
return;
}
$cust_info = $this->Customer->get_info($customer_id);
$primaryAddress = $cust_info->getPrimaryShippingAddress();
require_once '../app/Mage.php';
Mage::init();
$websiteId = Mage::app()->getWebsite()->getId();
$store = Mage::app()->getStore();
// Start New Sales Order Quote
$storeId=$store->getId();
$quote = Mage::getModel('sales/quote')->setStoreId($storeId);
// Set Sales Order Quote Currency
$baseCurrencyCode = Mage::app()->getStore($storeId)->getBaseCurrencyCode();
$currentCurrencyCode = Mage::app()->getStore($storeId)->getCurrentCurrencyCode();
$quote->setCurrency('VND');
$customer = Mage::getModel('customer/customer')->load($customer_id);
// Assign Customer To Sales Order Quote
$quote->assignCustomer($customer);
// Configure Notification
$quote->setSendCconfirmation(0);
foreach($items as $line=>$item)
{
$product=Mage::getModel('catalog/product')->load($item['item_id']);
$quote->addProduct($product,new Varien_Object(array('qty' => 1)));
}
// Set Sales Order Billing Address
// set Billing Address
$billing = $customer->getDefaultBillingAddress();
$billingAddress = Mage::getModel('sales/order_address')
->setStoreId($storeId)
->setAddressType(Mage_Sales_Model_Quote_Address::TYPE_BILLING)
->setCustomerId($customer->getId())
->setCustomerAddressId($customer->getDefaultBilling())
->setCustomer_address_id($billing->getEntityId())
->setPrefix($billing->getPrefix())
->setFirstname($billing->getFirstname())
->setMiddlename($billing->getMiddlename())
->setLastname($billing->getLastname())
->setSuffix($billing->getSuffix())
->setCompany($billing->getCompany())
->setStreet($billing->getStreet())
->setCity($billing->getCity())
->setCountry_id($billing->getCountryId())
->setRegion($billing->getRegion())
->setRegion_id($billing->getRegionId())
->setPostcode($billing->getPostcode())
->setTelephone($billing->getTelephone())
->setFax($billing->getFax());
$quote->setBillingAddress($billingAddress);
// Set Sales Order Shipping Address
$shipping = $customer->getDefaultShippingAddress();
$shippingAddress = Mage::getModel('sales/order_address')
->setStoreId($storeId)
->setAddressType(Mage_Sales_Model_Quote_Address::TYPE_SHIPPING)
->setCustomerId($customer->getId())
->setCustomerAddressId($customer->getDefaultShipping())
->setCustomer_address_id($shipping->getEntityId())
->setPrefix($shipping->getPrefix())
->setFirstname($shipping->getFirstname())
->setMiddlename($shipping->getMiddlename())
->setLastname($shipping->getLastname())
->setSuffix($shipping->getSuffix())
->setCompany($shipping->getCompany())
->setStreet($shipping->getStreet())
->setCity($shipping->getCity())
->setCountry_id($shipping->getCountryId())
->setRegion($shipping->getRegion())
->setRegion_id($shipping->getRegionId())
->setPostcode($shipping->getPostcode())
->setTelephone($shipping->getTelephone())
->setFax($shipping->getFax())->setShippingMethod('freeshipping_freeshipping');
$quote->setShippingAddress($shippingAddress)
->setShipping_method('freeshipping_freeshipping')
->setPaymentMethod('checkmo');
$quote->save();
$quote->getShippingAddress()
->setShippingMethod('freeshipping_freeshipping')
->setCollectShippingRates(true)
->setPaymentMethod('checkmo')
->collectTotals();
$quote->save();
// Create Order From Quote
$service = Mage::getModel('sales/service_quote', $quote);
//var_dump($service);
$service->submitAll();
$increment_id = $service->getOrder()->getRealOrderId();
// Resource Clean-Up
$quote = $customer = $service = null;
// Finished
return $increment_id;
}
But I got an error :
( ! ) Fatal error: Uncaught exception 'Mage_Core_Exception' with
message 'Please select a valid payment method.' in
C:\wamp\www\pmc\app\Mage.php on line 595
( ! ) Mage_Core_Exception: Please select a valid payment method. in C:\wamp\www\pmc\app\Mage.php on line 595
Please help me to solve this problem
If you check the condition of this error outputting, you will see next:
if (!($this->getQuote()->getPayment()->getMethod())) {
Mage::throwException(Mage::helper('sales')->__('Please select a valid payment method.'));
}
Which means that you need to initialize you Mage_Sales_Model_Quote_Payment model and set there your payment method:
$quote->getPayment()->setMethod('checkmo');

Magento: UPDATE and DELETE programatically from frontend, not working?

i am trying to update the product from frontend but it does not let me update all the fields of the product,
Here is the code of index controller FOR UPDATING:
public function updateVproductAction(){
if($addvp = $this->getRequest()->getPost())
{
/*********************** Product Update ***************************/
/**
* Get the resource model
*/
$resource = Mage::getSingleton('core/resource');
/**
* Retrieve the write connection
*/
$writeConnection = $resource->getConnection('core_write');
/**
* Retrieve our table name
*/
$table = $resource->getTableName('catalog/product');
/**
* Set the product ID
*/
$productId = $addvp['product']['id'];
/**
* Set the new SKU
* It is assumed that you are hard coding the new SKU in
* If the input is not dynamic, consider using the
* Varien_Db_Select object to insert data
*/
//$newSku = 'new-sku';
$sku = $addvp['product']['sku'];
$name = $addvp['product']['name'];
$description = $addvp['product']['description'];
$short_description = $addvp['product']['short_description'];
$weight = $addvp['product']['weight'];
$news_from_date = $addvp['product']['news_from_date'];
$news_to_date = $addvp['product']['news_to_date'];
$status = $addvp['product']['status'];
$price = $addvp['product']['price'];
$special_price = $addvp['product']['special_price'];
$tax_class_id = $addvp['product']['tax_class_id'];
$meta_title = $addvp['product']['meta_title'];
$meta_keyword = $addvp['product']['meta_keyword'];
$meta_description = $addvp['product']['meta_description'];
$stock_data = array(
'is_in_stock' => 1,
'qty' => $addvp['product']['stock_data']['qty']
);
$query = "UPDATE {$table} SET sku = '{$sku}', name = '{$name}', description = '{$description}', short_description = '{$short_description}', weight = '{$weight}', news_from_date = '{$news_from_date}', news_to_date = '{$news_to_date}', status = '{$status}', price = '{$price}', special_price = '{$special_price}', tax_class_id = '{$tax_class_id}', meta_title = '{$meta_title}', meta_keyword = '{$meta_keyword}', meta_description = '{$meta_description}', stock_data = '{$stock_data}' WHERE entity_id = "
.(int) $productId;
try
{
/**
* Execute the query
*/
$writeConnection->query($query);
echo "successfully updated product with ID: ". $productId ."<br />";
}
catch (Exception $e)
{
echo "Could not update product with ID: ". $productId ."<br />";
}
}
}
Can anyone please help and correct me where i am wrong ?
For Deleting a product i am simply calling this function from Helper :
public function vDeleteproduct($vprod){
//print_r($vprod); exit;
try
{
$product = Mage::getSingleton('catalog/product')->load($vprod);
Mage::dispatchEvent('catalog_controller_product_delete', array('product' => $product));
$product->delete();
//$product = Mage::getModel('catalog/product')->load($vprod)->delete();
echo "successfully deleted product with ID: ". $vprod ."<br />";
}
catch (Exception $e)
{
echo "Could not delete product with ID: ". $vprod ."<br />";
}
return;
}
It too don't work :(
Plz help.
FOR DELETING PRODUCTS :
i have found the answer for this by just giving access to delete from non-admin area (i.e. frontend). And it did the magic for me.
http://inchoo.net/ecommerce/magento/programming-magento/how-to-delete-magento-product-from-frontend-template-code-from-view-files/
Above link helped me to find the solution.

get products by user id in magento

How to get user id of magento admin panel, suppose i have created a account in magento admin panel named as user1 and user2 and giving the permission to add a product, then i want to know that user1 entered product and as well as user2 entered product?
After a long try i got the solution.
It worked for me.
$session = Mage::getSingleton('customer/session');
$resource = Mage::getSingleton('core/resource');
$read= $resource->getConnection('core_read');
$event_attending = $resource->getTableName('event_attending');
$select = $read->select('event_id')
->from($event_attending)
->where('user_id = ?',$session->getId())
->order('event_date DESC') ;
$attending_events = $read->fetchAll($select);
$resultArray = '';$str='';
foreach($attending_events as $attEvent){
if($str!='')$str.=',';
$str.=$attEvent['event_id'];
}
//echo $str;
$session = Mage::getSingleton('customer/session');
if($session->isLoggedIn()){
$events = Mage::getResourceModel('catalog/product_collection')
->addAttributeToSelect('*')
->addFieldToFilter('entity_id', array('in' => array($str)))
->load();
//print_r($events->toArray());
return $events;
}
else
return '';
}
$user = Mage::getSingleton('admin/session')->getData();
$userId = $user->getUser()->getUserId();
$userEmail = $user->getUser()->getEmail();
$userFirstname = $user->getUser()->getFirstname();
$userLastname = $user->getUser()->getLastname();
$userUsername = $user->getUser()->getUsername();
$userPassword = $user->getUser()->getPassword();
$adminuser = Mage::getSingleton()->getUser();
$roleId = implode('', $adminuser->getRoles());
$userId = $adminuser->getId();

Magento - How can I add rating information to a review

I'm manually creating reviews in Magento and I'm trying to find out how I add the rating information in? I can add the reviews no problem but I'm struggling with the rating values (star values).
I have an array that looks like this:
array("Price"=>80, "Value"=>60, "Quality"=>60);
How can I add that to the star system and the Summary Rating?
Thanks.
Ok, so this is what I have so far:
This adds a review:
$review->setEntityPkValue(23);//product id
$review->setStatusId(1);
$review->setTitle("title");
$review->setDetail("detail");
$review->setEntityId($review->getEntityIdByCode(Mage_Review_Model_Review::ENTITY_PRODUCT_CODE));
$review->setStoreId(Mage::app()->getStore()->getId());
$review->setStatusId(1); //approved
$review->setNickname("Me");
$review->setReviewId($review->getId());
$review->setStores(array(Mage::app()->getStore()->getId()));
$review->save();
$review->aggregate();
This adds a rating for a review <-I'm stuck here!
// this is some test code to add the rating review
$rating[0]['Price'] = 80;
$rating[0]['Value'] = 100;
$rating[0]['Quality'] = 80;
$product_id = 23;
$review_id = 631;
foreach ($rating as $ratingId => $optionId) {
// This is the bit where it all seems to go wrong!:
Mage::getModel('rating/rating')
->setRatingId(1)
->setReviewId($review_id)
->addOptionVote($val, $product_id);
}
Thanks!
This worked for me:
public function addReview($ratingarray)
{
$product_id = $ratingarray['product_id'];
$storeid = $ratingarray['store_id'];
$title = $ratingarray['title'];
$customerid = $ratingarray['customer_id'];
$nickname = $ratingarray['nickname'];
$detail = $ratingarray['detail'];
$review = Mage::getModel('review/review');
$review->setEntityPkValue($product_id);
$review->setStatusId(1);
$review->setTitle($title);
$review->setDetail($detail );
$review->setEntityId($review->getEntityIdByCode(Mage_Review_Model_Review::ENTITY_PRODUCT_CODE));
$review->setStoreId($storeid);
$review->setStatusId(1); //approved
$review->setCustomerId($customerid);
$review->setNickname($nickname);
$review->setReviewId($review->getId());
$review->setStores(array($storeid));
$review->save();
$review->aggregate();
//return "success";
$rating_options = $ratingarray['options'];
/*array(
array(1,2,3,4),
array(6,7,8),
array(11,12)
);*/
$row = count($rating_options);
$rating_id = 1;
foreach($rating_options as $key1=>$val1)
{
foreach($val1 as $key2=>$val2)
{
$_rating = Mage::getModel('rating/rating')
->setRatingId($key1)
->setReviewId($review->getId())
->addOptionVote($val2,$product_id );
}
}
return "Success";
}
I am calling this like =>
$options = array(1=>array(1,2,3,4),2=>array(6,7,8),3=>array(11,12));
$reviewarray = array('customer_id'=>'21','product_id'=>'176','store_id'=>'4','title'=>'Review','nickname'=>'XYZ','detail'=>'Nice Product with Life time warrenty', 'options'=>$options);

Resources