Related
I have decided to upgrade the Laravel framework version to resolve the critical security flaws. I have successfully upgraded from 5.8 to 6 and then to 6.20 (exploit fixed).
But unfortunately I have encountered an error starting from Laravel framework 6.19.0 which throws an exception in my class (BuyWidget.php) which is related to BoundMethod.php. I have checked through the internet and found out they implemented check for non specified types in BoundMethod.php (Illuminate\Container\BoundMethod).
I tried to change all the functions in BuyWidget.php accordingly: public function run($listing) to public function run(Listing $listing) etc.
BuyWidget.php
<?php
namespace App\Widgets\Order;
use Arrilot\Widgets\AbstractWidget;
use App\Models\Listing;
class BuyWidget extends AbstractWidget
{
protected $config = [];
public function calculate_price($listing, $params) {
$fee_percentage = setting('marketplace_percentage_fee');
$fee_transaction = setting('marketplace_transaction_fee');
$quantity = isset($params['quantity'])?$params['quantity']:1;
$variants = isset($params['variant'])?$params['variant']:null;
$shipping = isset($params['shipping_option'])?$params['shipping_option']:null;
$additional_options = isset($params['additional_option'])?$params['additional_option']:[];
$additional_options_meta = isset($params['additional_options_meta'])?$params['additional_options_meta']:[];
$listing_price = $listing->price;
#calculate additional variant cost
$selected_variant = null;
$error = false;
$user_choice = [];
$user_choice[] = ['group' => 'general', 'name' => 'quantity', 'value' => $quantity];
if($variants) {
$variant_pricing = $listing->variants;
foreach($variants as $k => $v) {
$variant_pricing = $variant_pricing->where("meta.$k", $v);
$user_choice[] = ['group' => 'variant', 'name' => $k, 'value' => $v];
}
if($variant_pricing->count() == 1) {
$selected_variant = $variant_pricing->first();
$listing_price += $selected_variant->price;
if($quantity > $selected_variant->stock) {
$error = __('Insufficient stock. Please lower the quantity.');
}
if($selected_variant->stock < 1) {
$error = __('Out of Stock');
}
}
}
#calculate shipping cost
$selected_shipping_price = null;
if(!is_null($shipping)) {
$selected_shipping_method = $listing->shipping_options->firstWhere('id', $shipping)?:null;
if($selected_shipping_method) {
$selected_shipping_price = $selected_shipping_method->price;
}
$user_choice[] = ['group' => 'shipping', 'name' => 'Shipping', 'value' => $selected_shipping_method->name, 'price' => $selected_shipping_method->price];
}
#additional pricing
$additional_options_price = $listing->additional_options->reduce(function ($carry, $item) use($additional_options, $additional_options_meta) {
if(in_array($item->id, array_keys($additional_options))) {
$price = $item->price;
$quantity = 1;
if(in_array($item->id, array_keys($additional_options_meta)) && isset($additional_options_meta[$item->id]['quantity'])) {
$quantity = (int) $additional_options_meta[$item->id]['quantity'];
}
return $carry + ($price*$quantity);
}
return $carry;
}, 0);
$number = 0;
foreach($listing->additional_options as $k => $item) {
if(in_array($item->id, array_keys($additional_options))) {
$number++;
$user_choice[] = ['group' => 'additional_options', 'name' => 'Option '.($k+1), 'value' => $item->name, 'price' => $item->price];
}
}
//date, time, qty
$subtotal = ($quantity * $listing_price) + $additional_options_price;
$service_fee_percentage = $subtotal * ($fee_percentage/100);
$service_fee = (float) $service_fee_percentage + (float) $fee_transaction;
$total = $subtotal + $service_fee + $selected_shipping_price;
if($quantity > $listing->stock) {
$error = __('Insufficient stock. Please lower the quantity.');
}
if($listing->stock < 1) {
$error = __('Out of Stock');
}
//now check if we have any slots left for this time
$price_items = [
[
'key' => 'price',
'label' => __(':price x :quantity :unit_label', ['price' => format_money($listing_price, $listing->currency), 'quantity' => $quantity, 'unit_label' => $listing->unit]),
'price' => ($quantity * $listing_price)
]
];
if($selected_shipping_price) {
$price_items[] = [
'key' => 'service',
'label' => __('Shipping'),
'price' => $selected_shipping_price,
];
}
if($additional_options_price) {
$price_items[] = [
'key' => 'additional',
'label' => __('Additional options'),
'price' => $additional_options_price,
];
}
if($service_fee > 0) {
$price_items[] = [
'key' => 'service',
'label' => __('Service fee'),
'price' => $service_fee,
'notice' => __('This fee helps cover the costs of operating the website'),
];
}
return [
'user_choice' => $user_choice,
'error' => $error,
'total' => $total,
'service_fee' => $service_fee,
'price_items' => $price_items,
];
}
public function decrease_stock($order, $listing)
{
$quantity = $order->listing_options['quantity'];
$listing->decrement( 'stock', $quantity );
if(isset($order->listing_options['variant'])) {
$variants = $order->listing_options['variant'];
$listing_variants = $listing->variants;
foreach($variants as $k => $v) {
$listing_variants = $listing_variants->where("meta.$k", $v);
}
if($listing_variants->count() == 1) {
$listing_variant = $listing_variants->first();
$listing_variant->decrement( 'stock', $quantity );
}
}
}
public function validate_payment($listing, $request)
{
$result = $this->calculate_price($listing, request()->all());
return $result;
}
/**
* Treat this method as a controller action.
* Return view() or other content to display.
*/
public function run($listing)
{
//
$total = 0;
$quantity = request('quantity', 1);
$result = $this->calculate_price($listing, request()->all());
return view('listing.widgets.buy_widget', [
'config' => $this->config,
'listing' => $listing,
'qs' => http_build_query(request()->all()),
'error' => $result['error'],
'total' => $result['total'],
'service_fee' => $result['service_fee'],
'price_items' => $result['price_items'],
]);
}
}
However after applying these changes the app does not work properly, the parameters are always empty and the product is shown as Out Of Stock.
The initial exception has been thrown at sidebar.twig file which builds up the widget based on the listing type.
"An exception has been thrown during the rendering of a template ("Unable to resolve dependency [Parameter #0 [ $listing ]] ")
sidebar.twig
{% if listing.pricing_model %}
{{ Widget.run('Order.'~(listing.pricing_model.widget)~'Widget', {}, listing) | raw }}
{% endif %}
Code works flawlessly on any other versions before Laravel 6.19.0. If I manually revert the changes from file BoundMethod.php the code works as expected even on never vesions. I would like to find another solution to avoid modifying vendor files, since it's not the best approach.
web.php
include "admin.php";
include "payments.php";
Route::get('/cp', function () {
if(env('DEMO_PANEL')) {
\Auth::loginUsingId(1, true);
return redirect("/panel");
}
});
Route::group(['prefix' => LaravelLocalization::setLocale(), 'middleware' => 'jailBanned'], function()
{
Auth::routes();
Route::get('email-verification', 'Auth\EmailVerificationController#sendEmailVerification')->name('email-verification.send');
Route::get('email-verification/error', 'Auth\EmailVerificationController#getVerificationError')->name('email-verification.error');
Route::get('email-verification/check/{token}', 'Auth\EmailVerificationController#getVerification')->name('email-verification.check');
Route::get('/', 'HomeController#index')->name('home');
Route::get('/browse', 'BrowseController#listings')->name('browse');
Route::get('/categories', 'BrowseController#categories')->name('categories');
Route::get('/pages/{slug?}', 'PageController#index')->name('page');
Route::get('/contact', 'ContactController#index')->name('contact');
Route::post('/contact', 'ContactController#postIndex')->name('contact.post');
Route::get('/profile/{user}', 'ProfileController#index')->name('profile'); //PROFILE
Route::get('/profile/{user}/follow', 'ProfileController#follow')->name('profile.follow'); //PROFILE
//LISTINGS
Route::group(['prefix' => 'listing'], function()
{
Route::get('/{listing}/{slug}', 'ListingController#index')->name('listing');
Route::get('/{listing}/{slug}/card', 'ListingController#card')->name('listing.card');
Route::get('/{listing}/{slug}/spotlight', 'ListingController#spotlight')->middleware('auth.ajax')->name('listing.spotlight');
Route::get('/{listing}/{slug}/verify', 'ListingController#verify')->middleware('auth.ajax')->name('listing.verify');
Route::get('/{listing}/{slug}/star', 'ListingController#star')->middleware('auth.ajax')->name('listing.star');
Route::get('/{listing}/{slug}/edit', 'ListingController#edit')->name('listing.edit');
#Route::get('/{listing}/{slug}/availability', 'AvailabilityController#availability')->name('listing.availability');
Route::any('/{id}/update', 'ListingController#update')->name('listing.update');
});
//ACCOUNT
Route::group(['middleware' => ['auth', 'isVerified'], 'prefix' => 'account', 'as' => 'account.', 'namespace' => 'Account'], function()
{
Route::get('/', function () {
return redirect(route('account.edit_profile.index'));
});
Route::resource('change_password', 'PasswordController');
Route::resource('edit_profile', 'ProfileController');
Route::resource('purchase-history', 'PurchaseHistoryController');
Route::resource('favorites', 'FavoritesController');
Route::resource('listings', 'ListingsController');
Route::resource('orders', 'OrdersController');
Route::get('payments/{id}/unlink', 'BankAccountController#unlink')->name('payments.unlink');
Route::resource('bank-account', 'BankAccountController');
Route::get('paypal/connect', 'PayPalController#connect')->name('paypal.connect');
Route::get('paypal/callback', 'PayPalController#callback')->name('paypal.callback');
});
//REQUIRES AUTHENTICATION
Route::group(['middleware' => ['auth', 'isVerified']], function () {
//INBOX
Route::resource('inbox', 'InboxController')->middleware('talk'); //Inbox
Route::get('/inbox/messages/{id}', 'InboxController#messages')->name('inbox.messages');
//CREATE LISTING
Route::resource('create', 'CreateController');
Route::any('/create/{listing}/session', 'CreateController#session')->name('create.session');
Route::get('/create/{listing}/images', 'CreateController#images')->name('create.images');
Route::get('/create/{listing}/additional', 'CreateController#additional')->name('create.additional');
Route::get('/create/{listing}/pricing', 'CreateController#pricing')->name('create.pricing');
Route::get('/create/{listing}/times', 'CreateController#getTimes')->name('create.times');
Route::post('/create/{listing}/times', 'CreateController#postTimes')->name('create.times');
Route::get('/create/{listing}/boost', 'CreateController#boost')->name('create.boost');
Route::post('/create/{listing}/uploads', 'CreateController#upload')->name('create.upload');
Route::delete('/create/{listing}/image/{uuid?}', 'CreateController#deleteUpload')->name('create.delete-image');
//CHECKOUT
Route::get('/checkout/error', 'CheckoutController#error_page')->name('checkout.error');
Route::get('/checkout/{listing}', 'CheckoutController#index')->name('checkout');
Route::post('/checkout/{listing}', 'CheckoutController#store')->name('checkout.store');
Route::get('/checkout/{session}/callback', 'CheckoutController#callback')->name('checkout.callback');
Route::any('/checkout/process/{listing}', 'CheckoutController#process')->name('checkout.process');
#Route::any('/checkout/test', 'CheckoutController#test')->name('checkout.test');
#Route::resource('stripe', 'StripeController');
#Route::any('/stripe/connect', 'StripeController#connect')->name('stripe.connect');
Route::any('/paypal/{listing}/start', 'PaypalController#start')->name('paypal.start');
Route::any('/paypal/cancel', 'PaypalController#cancel')->name('paypal.cancel');
Route::any('/paypal/callback', 'PaypalController#callback')->name('paypal.callback');
Route::any('/paypal/confirm', 'PaypalController#confirm')->name('paypal.confirm');
#Route::any('/paypal/create_agreement', 'PaypalController#create_agreement')->name('paypal.create_agreement');
});
//REQUIRES AUTHENTICATION
Route::group(['middleware' => ['auth']], function () {
Route::get('email-verification', 'Auth\EmailVerificationController#index')->name('email-verification.index');
Route::get('resend-verification', 'Auth\EmailVerificationController#resend')->name('email-verification.resend');
Route::get('email-verified', 'Auth\EmailVerificationController#verified')->name('email-verification.verified');
});
Route::get('login/facebook', 'Auth\LoginController#redirectToProvider');
Route::get('login/facebook/callback', 'Auth\LoginController#handleProviderCallback');
});
#errors
Route::get('/suspended',function(){
return 'Sorry something went wrong.';
})->name('error.suspended');
public function run(Listing $listing)
And you included a class in that namespace that matches Listing? Or is it available through service providers?
Remove parameter from function:
public function run();
and add the following line to the function:
$listing = func_get_arg(0);
I'm new to PHP and I'm building API for wishlist, for both guest users and logged-in users in Laravel Lumen. Here I'm using TrailManagerService as session manager
It saves data as
- for logged in users
Array
(
[trail_id] => 4b19bd9d-f2da-431b-8aba-d181d7eca736
[inception_time] => 1599813465
[last_used] => 1600762156
[customer_id] => 106210
[customer_data.customer_id] => 106210
[customer_data.firstname] => XXXX
[customer_data.lastname] => YYYY
[customer_data.gender] => Male
[customer_data.dob] => 1999-10-19
[customer_data.email] => xx#yy.com
[customer_data.mobile] => 2245436547
[customer_data.referral_code] => HRI11489
-for guest users
Array
(
[trail_id] => 8b7e6931-6ad3-48a0-af61-4caaab85cf20
[inception_time] => 1600761357
[last_used] => 1600761391
I want to add wishlist items to trailData and save it to DB if user does login and then emptytraildata after it get saved to DB. Also, if user doesnt login wishlist data should be saved in trailData for current session.
Code for WishlistControllerService
<?php
namespace App\Http\Services\v1\Products;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Redis;
use Illuminate\Http\Request;
use App\Services\SOA\TrailManagerService;
use App\Repositories\WishlistRepository;
class WishlistControllerService
{
public function __construct(WishlistRepository $wishlistRepository)
{
$this->wishlistRepository = $wishlistRepository;
}
public function showList(Request $request){
$trailData = TrailManagerService::getAllTrailData('customer_id');
$trailCustomerId = TrailManagerService::getTrailData('customer_id');
$headerCustomerId = (int) $request->header('X-Customer-ID', 0);
$responseData = [];
$trailCustomerId = $trailData['customer_id'] ?? 0;
print_r($trailData);exit;
if($trailCustomerId === $headerCustomerId) {
// print_r("hi");exit;
$wishlistData = $this->wishlistRepository->getWishlist($trailCustomerId);
$responseData = [
'identifier' => 'wishlist',
'data' => [
'list' => $wishlistData
]
];
} else if($trailCustomerId === 0) {
// print_r("bye");exit;
// $tempWishlistItem = [
// // 'guestUserID' => $,
// 'productID' => $request->input('product_id'),
// 'sizeID' => $trailData['size_id'],
// 'productQuantity' => $request->input('quantity'),
// 'shippingPin' => $request->input('postal_code'),
// 'shippingCity' => $request->input('city_name'),
// ];
$responseData = [
'identifier' => '',
'data' => [
'list' => []
]
];
} else {
// print_r("why");exit;
$responseData = [
'status' => 403,
'message' => 'Access Forbidden'
];
}
return $responseData;
}
public function store($request, $productId){
$trailData = TrailManagerService::getAllTrailData();
$responseData = [];
$headerCustomerId = (int) $request->header('X-Customer-ID', 0);
$trailCustomerId = $trailData['customer_id'] ?? 0;
$tempWishlistItem =
[
// 'siteUserID`' => $customerId ?? $trailCustomerId,
'productID' => $productId,
'sizeID' => $request->input('size_id'),
'productQuantity' => $request->input('quantity'),
'currency' => strtoupper($request->input('currencyCode')),
];
$tempData[] =
array_push($trailData, $tempWishlistItem);
TrailManagerService::setTrailData($trailData);
print_r($trailData);exit;
// if($trailCustomerId === $customerId) {
$wId = $this->wishlistRepository->create($wishlistModelData);
$responseData = ['data' => ['userWID' => $wId]];
$wishlistModelData = [
'siteUserID' => $customerId,
'productID' => $productId,
'sizeID' => $request->input('size_id'),
'productQuantity' => $request->input('quantity'),
'currency' => strtoupper($request->input('currencyCode')),
];
// print_r($wishlistModelData);exit;
$wishlistItem = $this->wishlistRepository
->findWhere(['status' => 1, 'siteUserID' => $customerId, 'productID' =>
$productId]);
if(empty($wishlistItem[0]) === false) {
$responseData = [
'status' => 403,
'message' => 'Forbidden, Item already in Wishlist'
];
} else {
$wId = $this->wishlistRepository->create($wishlistModelData);
$responseData = ['data' => ['userWID' => $wId]];
}
} else {
// $tempWishlistData = [];
$tempWishlistItem =
[
// 'siteUserID' => $customerId ?? $trailCustomerId,
'productID' => $productId,
'sizeID' => $request->input('size_id'),
'productQuantity' => $request->input('quantity'),
'currency' => strtoupper($request->input('currencyCode')),
];
$tempWishlistData = array_merge($trailData, [$tempWishlistItem]);
print_r($tempWishlistData);exit;
$trailDataTemp = TrailManagerService::setTrailData(
$tempWishlistData
);
print_r($trailDataTemp);exit;
if($customerId === $trailData['customerID']){
foreach($tempWishlistData as $item) {
$wId = $this->wishlistRepository->create($wishlistModelData);
$responseData = ['data' => ['userWID' => $wId]];
}
TrailManagerService::emptyTrailData();
}
return $responseData;
}
I want to add wishlist items to trailData and save it to DB if user does login and then emptytraildata after it get saved to DB. Also, if user doesnt login wishlist data should be saved in trailData for current session.
Code for Wishlist Controller
<?php
namespace App\Http\Controllers\v1\Products;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Services\v1\Products\WishlistControllerService;
use Validator;
use App\Helpers\Utilities;
use App\Services\SOA\TrailManagerService;
use Illuminate\Support\Facades\Route;
class WishlistController extends Controller
{
private $controllerService;
public function __construct(WishlistControllerService $controllerService)
{
// $request = app(Request::class);
// $customerId = $request->header('X-Customer-ID', 0);
// TrailManagerService::authorize($customerId);
$this->controllerService = $controllerService;
}
public function index(Request $request)
{
$responseData = $this->controllerService->showList($request);
$httpStatus = $responseData['status'] ?? 200;
return $this->response($responseData, $httpStatus);
}
public function store(Request $request, int $productId){
$requestParams = $request->all();
// $requestParams['productId'] = $request->header('product_id');
$validator = Validator::make($requestParams,
[
'product_id' => 'integer',
'size_id' => 'integer',
'quantity' => 'required|integer|digits_between:1,2',
'currencyCode' => 'required|string|in:INR,EUR,USD,AUD,CAD,SGD,HKD'
],
[
'product_id.integer'=> 'Parameter product_id is mandatory',
'size_id.integer' => 'Invalid value for parameter size_id',
],
);
if ($validator->fails()) {
$messages = $validator->errors();
$responseData = Utilities::requestValiationResponse($messages);
} else {
// print_r($productId);exit;
$responseData = $this->controllerService->store($request, $productId);
}
$httpStatus = $responseData['status'] ?? 200;
return $this->response($responseData, $httpStatus);
}
public function remove(Request $request, int $productId)
{
$responseData = $this->controllerService->remove($request, $productId);
$httpStatus = $responseData['status'] ?? 200;
return $this->response($responseData, $httpStatus);
}
}
Code for Wishlist Repo
<?php
namespace App\Repositories;
use Prettus\Repository\Eloquent\BaseRepository;
use App\Models\MxUserWishlist;
use Illuminate\Support\Facades\DB;
use App\Helpers\Utilities;
class WishlistRepository extends BaseRepository
{
/**
* Specify Model class name
*
* #return string
*/
public function model()
{
return MxUserWishlist::class;
}
/**
* #param int $customerId
* #return array
*/
public function getWishlist($trailCustomerId): array
{
$wishlistData = [];
$query = "SELECT W.userWID, W.siteUserID, W.productID,P.productTitle, PSI.imageName,
W.sizeID, S.sizeTitle, D.designerName,P.designerID, P.categoryID,
PS.productPrice, PS.discountPercent,PS.filterPrice,P.seoUri
FROM mx_user_wishlist W
INNER JOIN mx_product P ON P.productID = W.productID
INNER JOIN mx_product_set PS ON (W.productID = PS.productID AND W.sizeID = PS.sizeID)
INNER JOIN mx_product_set_images PSI ON PSI.productID = W.productID
INNER JOIN mx_size S ON S.sizeID = W.sizeID
INNER JOIN mx_designer D ON P.designerID = D.designerID
WHERE W.siteUserID = $trailCustomerId";
$wishlistCollection = DB::select($query, ['siteUserID' => $trailCustomerId]);
if(empty($wishlistCollection) === false) {
foreach ($wishlistCollection as $key => $wishlist) {
$productId = 0;
$productUrl = '';
$productUrl = '/products/'.$wishlist->seoUri.'/'.$wishlist->productID;
$wishlistItems = [
'id' => $wishlist->productID,
'name' => $wishlist->productTitle,
'image' => config('global.cdni_url').'/tr:w-317/uploads/product/'.$wishlist->imageName,
'product_url' => $productUrl,
'sizes' => [
'id' => $wishlist->productID,
'name' => $wishlist->sizeTitle
],
'designer_name' => $wishlist->designerName,
'category_id' => $wishlist->categoryID,
'mrp' => $wishlist->productPrice,
'discount_percentage' => $wishlist->discountPercent,
'you_pay' => $wishlist->filterPrice,
];
}
return $wishlistItems;
} else {
$responseData = [];
return $responseData;
}
// return $responseData;
}
I had developed the E-Program Website on the Laravel 7 Framework. I had integrated my CC Avenue payment Gateway with the help of indipay softon, package but on payment successful I am getting error i.e POST Method is not supported.. supported method is GET, HEAD
.env file
INDIPAY_MERCHANT_ID=26XXXX
INDIPAY_ACCESS_CODE=AVPXXXXXXXXXXXXXXXX
INDIPAY_WORKING_KEY=77XXXXXXXXXXXXXXXXXXXXXXX
INDIPAY_REDIRECT_URL="http://eprogram.lfwproducts.com/checkoutResponse"
INDIPAY_CANCEL_URL="http://eprogram.lfwproducts.com/cart"
INDIPAY_CURRENCY="INR"
INDIPAY_LANGUAGE="EN"
controller File
public function checkout(Request $request)
{
if (Auth::check()) {
$courseId = $request->post('courseId');
$courseTicket = $request->post('courseTicket');
$userId = $request->post('uid');
$total = $request->post('total');
$letters = "LFW-EP";
$digits = "1234567890";
$randomString = "";
for ($i = 0; $i < 3; $i++) {
$randomString .= $digits[rand(0, strlen($digits) - 1)];
}
$orderId = $letters . $randomString;
$parameters = [
'merchant_id' => 26XXXX,
'currency' => 'INR',
'redirect_url' => 'http://eprogram.lfwproducts.com/checkoutResponse',
'cancel_url' => 'http://eprogram.lfwproducts.com/cart',
'language' => 'EN',
'order_id' => $orderId,
'amount' => $total,
'merchant_param1' => $userId,
'merchant_param2' => $courseId[0],
'merchant_param3' => $courseTicket[0],
];
$order = Indipay::gateway('CCAvenue')->prepare($parameters);
return Indipay::process($order);
} else {
return \view('auth.login');
}
}
public function myPaymentResponse(Request $request)
{
// For default Gateway
$response = Indipay::response($request);
// For Otherthan Default Gateway
$response1 = Indipay::gateway('CCAvenue')->response($request);
dd($response);
}
verifycsrftoken file
protected $except = [
'https://secure.ccavenue.com/transaction/transaction.do?command=initiateTransaction',
'http://eprogram.lfwproducts.com/checkoutResponse',
'*/checkoutResponse',
'ccavenue/*'
];
web.php file
Route::get('/checkoutResponse', 'CartController#myPaymentResponse')->name('checkoutResponse');
Error
Code below
public function PayCCAvenue(Request $request)
{
$parameters = [
'tid' => '1233221223322',
'order_id' => '1232212',
'amount' => '1200.00',
'firstname'=>'test',
'email'=>'email#fffm.com',
'phone'=>'7736190194',
'productinfo'=>'sfszgvfsg'
];
// gateway = CCAvenue
$order = Payment::gateway('CCAvenue')->prepare($parameters);
//dd(Payment::process($order));
return Payment::process($order);
}
After return Payment::process($order); page goes blank. dd(Payment::process($order)); giving result.
tried different laravel packages. same issue
Old Code
public function payment(Request $request)
{
if ($request->payment_method == 1) {
$this->paypalPAyment($request);
} else if($request->payment_method == 1){
$this->PayCCAvenue($request);
}
}
public function PayCCAvenue(Request $request)
{
$parameters = [
'tid' => '1233221223322',
'order_id' => '1232212',
'amount' => '1200.00',
'firstname'=>'test',
'email'=>'email#fffm.com',
'phone'=>'7736190194',
'productinfo'=>'sfszgvfsg'
];
// gateway = CCAvenue
$order = Payment::gateway('CCAvenue')->prepare($parameters);
//dd(Payment::process($order));
return Payment::process($order);
}
Working code
public function payment(Request $request)
{
if ($request->payment_method == 1) {
$this->paypalPAyment($request);
} else if($request->payment_method == 1){
$parameters = [
'tid' => '1233221223322',
'order_id' => '1232212',
'amount' => '1200.00',
'firstname'=>'test',
'email'=>'email#fffm.com',
'phone'=>'7736190194',
'productinfo'=>'sfszgvfsg'
];
// gateway = CCAvenue
$order = Payment::gateway('CCAvenue')->prepare($parameters);
//dd(Payment::process($order));
return Payment::process($order);
}
}
No idea why laravel page redirection was not worked when the code was
in
separate function.
I'm developing this to store users "Orders" in a batch.
My doubt is: How do I request user data inside the OrderController store()
I already debugged this and $id_user is null, probably because I'm already using Request::get for the form data.
I could pass the $id_user from the form inputs, but I guess it's not secure.
public function store(Request $request)
{
$quantities = Request::get('quantity');
$products = Request::get('id_product');
$hash_card = Request::get('hash_card');
$user = Request::user();
$id_user = $user->id_user;
$total_products = count($products);
for($i=0;$i<$total_products;$i++){
if($quantities[$i]>0){
$id_product = $products[$i];
$quantity = $quantities[$i];
$product=Product::find($id_product);
$product_price=$product->price;
$order_data[] = [
'id_user' => $id_user,
'id_product' => $id_product,
'quantity' => $quantity,
'product_price' => $product_price,
'hash_card' => $hash_card
];
}
}
Order::insert($order_data);
return redirect('pedidos?add&card='.$hash_card);
}
Any help is welcome!
Do you have debugging on, by any chance? Because this script shouldn't run at all. You shouldn't be able to call the method statically.
Try this:
public function store(Request $request)
{
$quantities = $request->quantity;
$products = $request->id_product;
$hash_card = $request->hash_card;
$id_user = $request->user()->id;
$total_products = count($products);
for($i=0;$i<$total_products;$i++){
if($quantities[$i]>0){
$id_product = $products[$i];
$quantity = $quantities[$i];
$product=Product::find($id_product);
$product_price=$product->price;
$order_data[] = [
'id_user' => $id_user,
'id_product' => $id_product,
'quantity' => $quantity,
'product_price' => $product_price,
'hash_card' => $hash_card
];
}
}
Order::insert($order_data);
return redirect('pedidos?add&card='.$hash_card);
}