I have migrated my Stripe checkout from legacy version to the new one. The payment does work, but the success redirect URL as well as the DB update does not work.
When I send the request I get redirected to my main page instead of the user subscription page.
Also I do get the error:
Could not determine the URL to request: StripeCustomer instance has invalid ID: (no ID)
I already did some research and also visited the migration documentation from Stripe:
https://stripe.com/docs/payments/checkout/migration
But I do not get the error.
My guess is it is between the lines:
//$payer_id = $customer->id;
$payer_email = $customer->email;
$updateTrx = $trx->update([
'total_price' => $total,
'payment_gateway_id' => $payment_gateway_id,
'payment_id' => $payment_id,
//'payer_id' => $payer_id,
'payer_email' => $payer_email,
'status' => 2,
]);
if ($updateTrx) {
CheckoutController::updateSubscription($trx);
toastr()->success(lang('Payment made successfully', 'checkout'));
return redirect()->route('user.subscription');
}
from:
<?php
namespace App\Http\Controllers\Frontend\Gateways;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Frontend\User\CheckoutController;
use Exception;
use Illuminate\Http\Request;
use Stripe\Checkout\Session;
use Stripe\Customer;
use Stripe\Stripe;
class StripeCheckoutController extends Controller
{
public static function process($trx)
{
if ($trx->status != 0) {
$data['error'] = true;
$data['msg'] = lang('Invalid or expired transaction', 'checkout');
return json_encode($data);
}
if ($trx->plan->interval == 0) {
$planInterval = '(Monthly)';
} elseif ($trx->plan->interval == 1) {
$planInterval = '(Yearly)';
} elseif ($trx->plan->interval == 2) {
$planInterval = '(Lifetime)';
}
$paymentName = "Payment for subscription " . $trx->plan->name . " Plan " . $planInterval;
$gatewayFees = ($trx->total_price * paymentGateway('stripe_checkout')->fees) / 100;
$totalPrice = round(($trx->total_price + $gatewayFees), 2);
$priceIncludeFees = str_replace('.', '', ($totalPrice * 100));
$paymentDeatails = [
'customer_email' => $trx->user->email,
'payment_method_types' => [
'card',
],
'line_items' => [[
'price_data' => [
'currency' => currencyCode(),
'unit_amount' => $priceIncludeFees,
'product_data' => [
'name' => settings('website_name'),
'description' => $paymentName,
],
],
'quantity' => 1,
]],
'mode' => 'payment',
'cancel_url' => route('user.subscription'),
'success_url' => route('ipn.stripe_checkout') . '?session_id={CHECKOUT_SESSION_ID}',
];
try {
Stripe::setApiKey(paymentGateway('stripe_checkout')->credentials->secret_key);
$session = Session::create($paymentDeatails);
if ($session) {
$trx->update(['fees_price' => $gatewayFees, 'payment_id' => $session->id]);
$data['error'] = false;
$data['redirectUrl'] = $session->url;
return json_encode($data);
}
} catch (\Exception $e) {
$data['error'] = true;
$data['msg'] = $e->getMessage();
return json_encode($data);
}
}
public function ipn(Request $request)
{
$session_id = $request->session_id;
try {
Stripe::setApiKey(paymentGateway('stripe_checkout')->credentials->secret_key);
$trx = \App\Models\Transaction::where([['user_id', userAuthInfo()->id], ['payment_id', $session_id], ['status', 1]])->first();
if (is_null($trx)) {
throw new Exception(lang('Invalid or expired transaction', 'checkout'));
}
$session = Session::retrieve($session_id);
//if ($session->payment_status == "paid") {
if ($session->payment_status == "paid") {
$customer = Customer::retrieve($session->customer);
$total = ($trx->total_price + $trx->fees_price);
$payment_gateway_id = paymentGateway('stripe_checkout')->id;
$payment_id = $session->id;
//$payer_id = $customer->id;
$payer_email = $customer->email;
$updateTrx = $trx->update([
'total_price' => $total,
'payment_gateway_id' => $payment_gateway_id,
'payment_id' => $payment_id,
//'payer_id' => $payer_id,
'payer_email' => $payer_email,
'status' => 2,
]);
if ($updateTrx) {
CheckoutController::updateSubscription($trx);
toastr()->success(lang('Payment made successfully', 'checkout'));
return redirect()->route('user.subscription');
}
} else {
throw new Exception(lang('Payment failed', 'checkout'));
}
} catch (\Exception $e) {
toastr()->error($e->getMessage());
return redirect()->route('home');
}
}
}
Related
I'm having a problem getting errors from the Rest API I created with codeigniter 3, or rather using the library from "https://github.com/chriskacerguis/codeigniter-restserver".
This problem occurs when I POST data to server via API.
When I try to post the same data as the data in the database. it will issue an error message data already exists. with status 409.
but I didn't get the error in the client application that I made. only displays "Null"
https://localhost/server/api/room
public function index_post()
{
try {
$input = json_decode(file_get_contents('php://input'), true);
if (empty($input['noroom'])) {
throw new Exception('Error: field not found, field must be named noroom');
return false;
}
$exists = $this->Roommodel->findRoomByNoroomAndHotel($input['noroom'], $input['hotel_code'])->num_rows();
if ($exists > 0) {
$message = [
'status' => 409,
'message' => 'Data already exists',
];
$this->response($message, REST_Controller::HTTP_CONFLICT);
} else {
$dataRoom = [
'hotel_code' => $input['hotel_code'],
'noroom' => $input['noroom'],
'room_type' => $input['room_type'],
'room_area' => $input['room_area'],
'description' => $input['description'],
];
$insert = $this->Roommodel->save($dataRoom);
if ($insert) {
$data = [
'hotel_code' => $input['hotel_code'],
'noroom' => $input['noroom'],
'room_type' => $input['room_type'],
'room_area' => $input['room_area'],
'description' => $input['description'],
'message' => 'Success created data'
];
$message = [
'status' => 200,
'message' => 'Success',
'data' => $data,
];
$this->response($message, REST_Controller::HTTP_OK);
} else {
$message = [
'status' => 400,
'message' => 'Bad Request'
];
$this->response($message, REST_Controller::HTTP_BAD_REQUEST);
}
}
} catch (Exception $e) {
$message = [
'status' => 500,
'message' => $e->getMessage()
];
$this->response($message, REST_Controller::HTTP_INTERNAL_SERVER_ERROR);
}
}
below is my coding on the client side, and I try to do var_dum() the result is "Null" when there is an error.
when I tried insomia, I got the error message.
var $API = "";
function __construct()
{
parent::__construct();
$this->API = "http://localhost/server";
$this->load->library('session');
$this->load->library('curl');
$this->load->helper('form');
$this->load->helper('url');
}
public function create()
{
if ($this->input->is_ajax_request()) {
$data = [
'hotel_code' => $this->input->post('hotel_code'),
'noroom' => $this->input->post('noroom'),
'room_type' => $this->input->post('room_type'),
'room_area' => $this->input->post('room_area'),
'description' => $this->input->post('description'),
];
$response = json_decode($this->curl->simple_post($this->API . '/api/room', json_encode($data), array(CURLOPT_BUFFERSIZE => 10)), true);
var_dump($response); die();
echo json_encode($response);
} else {
show_404();
}
}
if the post data is successful, it will send the success message. and managed to get the message.
please help me to solve this problem
I'm using Laravel i need to do update stock after order placed from a client/user app i used Http api for that but when i added stock update code in Http api file i'm getting internal server error in user app and also order is no placing if i remove stock update code from Http api it is taking order without error and stock update and the error i'm getting live.ERROR: Undefined variable: total_stock {"userId":1,"exception":"[object] (ErrorException(code: 0): Undefined variable: total_stock at /home/ttrr/domain/folder/app/Http/Controllers/Api/V1/OrderController.php:280) [stacktrace]
Here is my stock update code
$type = $c['variation'][0]['type'];
$var_store = [];
foreach (json_decode($product['variations'], true) as $var) {
if ($type == $var['type']) {
$var['stock'] -= $c['quantity'];
}
array_push($var_store, $var);
}
Product::where(['id' => $product['id']])->update([
'variations' => json_encode($var_store),
'total_stock' => $product['total_stock'] - $c['quantity'],
]);
Here is my ordercontroll.php
class OrderController extends Controller
{
public function track_order(Request $request)
{
$validator = Validator::make($request->all(), [
'order_id' => 'required'
]);
if ($validator->fails()) {
return response()->json(['errors' => Helpers::error_processor($validator)], 403);
}
$order = Order::with(['restaurant', 'delivery_man.rating'])->withCount('details')->where(['id' => $request['order_id'], 'user_id' => $request->user()->id])->first();
if($order)
{
$order['restaurant'] = $order['restaurant']?Helpers::restaurant_data_formatting($order['restaurant']):$order['restaurant'];
$order['delivery_address'] = $order['delivery_address']?json_decode($order['delivery_address']):$order['delivery_address'];
$order['delivery_man'] = $order['delivery_man']?Helpers::deliverymen_data_formatting([$order['delivery_man']]):$order['delivery_man'];
unset($order['details']);
}
else
{
return response()->json([
'errors' => [
['code' => 'schedule_at', 'message' => trans('messages.not_found')]
]
], 404);
}
return response()->json($order, 200);
}
public function place_order(Request $request)
{
$validator = Validator::make($request->all(), [
'order_amount' => 'required',
'payment_method'=>'required|in:cash_on_delivery,digital_payment',
'order_type' => 'required|in:take_away,delivery',
'restaurant_id' => 'required',
'distance' => 'required_if:order_type,delivery',
'address' => 'required_if:order_type,delivery',
'longitude' => 'required_if:order_type,delivery',
'latitude' => 'required_if:order_type,delivery',
]);
if ($validator->fails()) {
return response()->json(['errors' => Helpers::error_processor($validator)], 403);
}
$coupon = null;
$delivery_charge = null;
$schedule_at = $request->schedule_at?\Carbon\Carbon::parse($request->schedule_at):now();
if($request->schedule_at && $schedule_at < now())
{
return response()->json([
'errors' => [
['code' => 'order_time', 'message' => trans('messages.you_can_not_schedule_a_order_in_past')]
]
], 406);
}
$restaurant = Restaurant::with('discount')->whereTime('opening_time','<=',$schedule_at->format('H:i'))->whereTime('closeing_time','>=',$schedule_at->format('H:i'))->where('id', $request->restaurant_id)->first();
if(!$restaurant)
{
return response()->json([
'errors' => [
['code' => 'order_time', 'message' => trans('messages.restaurant_is_closed_at_order_time')]
]
], 406);
}
if($request->schedule_at && !$restaurant->schedule_order)
{
return response()->json([
'errors' => [
['code' => 'schedule_at', 'message' => trans('messages.schedule_order_not_available')]
]
], 406);
}
if ($request['coupon_code']) {
$coupon = Coupon::active()->where(['code' => $request['coupon_code']])->first();
if (isset($coupon)) {
$staus = CouponLogic::is_valide($coupon, $request->user()->id ,$request['restaurant_id']);
if($staus==407)
{
return response()->json([
'errors' => [
['code' => 'coupon', 'message' => trans('messages.coupon_expire')]
]
], 407);
}
else if($staus==406)
{
return response()->json([
'errors' => [
['code' => 'coupon', 'message' => trans('messages.coupon_usage_limit_over')]
]
], 406);
}
else if($staus==404)
{
return response()->json([
'errors' => [
['code' => 'coupon', 'message' => trans('messages.not_found')]
]
], 404);
}
if($coupon->coupon_type == 'free_delivery')
{
$delivery_charge = 0;
$coupon = null;
}
} else {
return response()->json([
'errors' => [
['code' => 'coupon', 'message' => 'not found!']
]
], 401);
}
}
$per_km_shipping_charge = (float)BusinessSetting::where(['key' => 'per_km_shipping_charge'])->first()->value;
$minimum_shipping_charge = (float)BusinessSetting::where(['key' => 'minimum_shipping_charge'])->first()->value;
$original_delivery_charge = ($request->distance * $per_km_shipping_charge > $minimum_shipping_charge) ? $request->distance * $per_km_shipping_charge : $minimum_shipping_charge;
if($request['order_type'] != 'take_away' && !$restaurant->free_delivery && $delivery_charge == null)
{
$delivery_charge = ($request->distance * $per_km_shipping_charge > $minimum_shipping_charge) ? $request->distance * $per_km_shipping_charge : $minimum_shipping_charge;
}
if($request->latitude && $request->longitude)
{
$point = new Point($request->latitude,$request->longitude);
$zone = Zone::where('id', $restaurant->zone_id)->contains('coordinates', $point)->first();
if(!$zone)
{
$errors = [];
array_push($errors, ['code' => 'coordinates', 'message' => trans('messages.out_of_coverage')]);
return response()->json([
'errors' => $errors
], 403);
}
}
$address = [
'contact_person_name' => $request->contact_person_name?$request->contact_person_name:$request->user()->f_name.' '.$request->user()->f_name,
'contact_person_number' => $request->contact_person_number?$request->contact_person_number:$request->user()->phone,
'address_type' => $request->address_type?$request->address_type:'Delivery',
'address' => $request->address,
'longitude' => (string)$request->longitude,
'latitude' => (string)$request->latitude,
];
$total_addon_price = 0;
$product_price = 0;
$restaurant_discount_amount = 0;
$order_details = [];
$order = new Order();
$order->id = 100000 + Order::all()->count() + 1;
$order->user_id = $request->user()->id;
$order->order_amount = $request['order_amount'];
$order->payment_status = 'unpaid';
$order->order_status = $request['payment_method']=='digital_payment'?'failed':'pending';
$order->coupon_code = $request['coupon_code'];
$order->payment_method = $request->payment_method;
$order->transaction_reference = null;
$order->order_note = $request['order_note'];
$order->order_type = $request['order_type'];
$order->restaurant_id = $request['restaurant_id'];
$order->delivery_charge = $delivery_charge??0;
$order->original_delivery_charge = $original_delivery_charge;
$order->delivery_address = json_encode($address);
$order->schedule_at = $schedule_at;
$order->scheduled = $request->schedule_at?1:0;
$order->otp = rand(1000, 9999);
$order->pending = now();
$order->created_at = now();
$order->updated_at = now();
foreach ($request['cart'] as $c) {
/*foreach (json_decode($product['variations'], true) as $var) {
if ($type == $var['type'] && $var['stock'] < $c['quantity']) {
$validator->getMessageBag()->add('stock', 'Stock is insufficient! available stock ' . $var['stock']);
}
}*/
if ($c['item_campaign_id'] != null) {
$product = ItemCampaign::find($c['item_campaign_id']);
if ($product) {
$type = $c['variation'][0]['type'];
foreach (json_decode($product['variations'], true) as $var) {
if ($type == $var['type'] && $var['stock'] < $c['quantity']) {
$validator->getMessageBag()->add('stock', 'Stock is insufficient! available stock ' . $var['stock']);
}
else {
$price = $product['price'];
}
}
/*if (count(json_decode($product['variations'], true)) > 0) {
$price = Helpers::variation_price($product, json_encode($c['variation']));
}*/
$product->tax = $restaurant->tax;
$product = Helpers::product_data_formatting($product);
$addon_data = Helpers::calculate_addon_price(\App\Models\AddOn::whereIn('id',$c['add_on_ids'])->get(), $c['add_on_qtys']);
$or_d = [
'food_id' => null,
'item_campaign_id' => $c['item_campaign_id'],
'food_details' => json_encode($product),
'quantity' => $c['quantity'],
'price' => $price,
'tax_amount' => Helpers::tax_calculate($product, $price),
'discount_on_food' => Helpers::product_discount_calculate($product, $price, $restaurant),
'discount_type' => 'discount_on_product',
'variant' => json_encode($c['variant']),
'is_stock_decreased' => 1,
'variation' => json_encode($c['variation']),
'add_ons' => json_encode($addon_data['addons']),
'total_add_on_price' => $addon_data['total_add_on_price'],
'created_at' => now(),
'updated_at' => now()
];
$order_details[] = $or_d;
$total_addon_price += $or_d['total_add_on_price'];
$product_price += $price*$or_d['quantity'];
$restaurant_discount_amount += $or_d['discount_on_food']*$or_d['quantity'];
} else {
return response()->json([
'errors' => [
['code' => 'campaign', 'message' => 'not found!']
]
], 401);
}
} else {
$product = Food::find($c['food_id']);
if ($product) {
if (count(json_decode($product['variations'], true)) > 0) {
$price = Helpers::variation_price($product, json_encode($c['variation']));
} else {
$price = $product['price'];
}
$product->tax = $restaurant->tax;
$product = Helpers::product_data_formatting($product);
$addon_data = Helpers::calculate_addon_price(\App\Models\AddOn::whereIn('id',$c['add_on_ids'])->get(), $c['add_on_qtys']);
$or_d = [
'food_id' => $c['food_id'],
'item_campaign_id' => null,
'food_details' => json_encode($product),
'quantity' => $c['quantity'],
'price' => $price,
'is_stock_decreased' => 1,
'tax_amount' => Helpers::tax_calculate($product, $price),
'discount_on_food' => Helpers::product_discount_calculate($product, $price, $restaurant),
'discount_type' => 'discount_on_product',
'variant' => json_encode($c['variant']),
'variation' => json_encode($c['variation']),
'add_ons' => json_encode($addon_data['addons']),
'total_add_on_price' => $addon_data['total_add_on_price'],
'created_at' => now(),
'updated_at' => now()
];
//stock update code
$type = $c['variation'][0]['type'];
$var_store = [];
foreach (json_decode($product['variations'], true) as $var) {
if ($type == $var['type']) {
$var['stock'] -= $c['quantity'];
}
array_push($var_store, $var);
}
Product::where(['id' => $product['id']])->update([
'variations' => json_encode($var_store),
'total_stock' => $product['total_stock'] - $c['quantity'],
]);
DB::table('order_details')->insert($or_d);
$total_addon_price += $or_d['total_add_on_price'];
$product_price += $price*$or_d['quantity'];
$restaurant_discount_amount += $or_d['discount_on_food']*$or_d['quantity'];
$order_details[] = $or_d;
} else {
return response()->json([
'errors' => [
['code' => 'food', 'message' => 'not found!']
]
], 401);
}
}
And tried mentioning variable like this 'total_stock' =>$total_stock but still not working
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 am using https://github.com/srmklive/laravel-paypal package and I try to use PayPal recurring method for monthly subscribes, it return error below:
Call to undefined method Srmklive\PayPal\Services\ExpressCheckout::createMonthlySubscription()
Code
//controller head
use Srmklive\PayPal\Services\ExpressCheckout;
use Srmklive\PayPal\Services\AdaptivePayments;
public function getExpressCheckout(Request $request)
{
$recurring = ($request->get('mode') === 'recurring') ? true : false;
$cart = $this->getCheckoutData($recurring);
try {
$response = $this->provider->setExpressCheckout($cart, $recurring);
return redirect($response['paypal_link']);
} catch (\Exception $e) {
$invoice = $this->createInvoice($cart, 'Invalid');
session()->put(['code' => 'danger', 'message' => "Error processing PayPal payment for Order $invoice->id!"]);
}
}
public function getExpressCheckoutSuccess(Request $request)
{
// dd($request->all());
$Itemm = Type::where('id', $request->input('type_id'))->first();
$recurring = ($request->get('mode') === 'recurring') ? true : false;
$token = $request->get('token');
$PayerID = $request->get('PayerID');
$cart = $this->getCheckoutData($recurring);
// Verify Express Checkout Token
$response = $this->provider->getExpressCheckoutDetails($token);
if (in_array(strtoupper($response['ACK']), ['SUCCESS', 'SUCCESSWITHWARNING'])) {
if ($recurring === true) {
$response = $this->provider->createMonthlySubscription($response['TOKEN'], $cart['item']['price'], $cart['subscription_desc']);
if (!empty($response['PROFILESTATUS']) && in_array($response['PROFILESTATUS'], ['ActiveProfile', 'PendingProfile'])) {
$status = 'Processed';
} else {
$status = 'Invalid';
}
} else {
// Perform transaction on PayPal
$payment_status = $this->provider->doExpressCheckoutPayment($cart, $token, $PayerID);
dd($payment_status);
$status = $payment_status['PAYMENTINFO_0_PAYMENTSTATUS'];
}
$invoice = $this->createInvoice($cart, $status);
if ($invoice->paid) {
session()->put(['code' => 'success', 'message' => "Order $invoice->id has been paid successfully!"]);
$user = Auth::user();
Mail::to($user->email)->send(new UserPlanActivated($user));
} else {
session()->put(['code' => 'danger', 'message' => "Error processing PayPal payment for Order $invoice->id!"]);
}
return redirect('/');
}
}
public function getAdaptivePay()
{
$this->provider = new AdaptivePayments();
$data = [
'receivers' => [
[
'email' => 'johndoe#example.com',
'amount' => 10,
'primary' => true,
],
[
'email' => 'janedoe#example.com',
'amount' => 5,
'primary' => false,
],
],
'payer' => 'EACHRECEIVER', // (Optional) Describes who pays PayPal fees. Allowed values are: 'SENDER', 'PRIMARYRECEIVER', 'EACHRECEIVER' (Default), 'SECONDARYONLY'
'return_url' => url('payment/success'),
'cancel_url' => url('payment/cancel'),
];
$response = $this->provider->createPayRequest($data);
dd($response);
}
public function notify(Request $request)
{
if (!($this->provider instanceof ExpressCheckout)) {
$this->provider = new ExpressCheckout();
}
$post = [
'cmd' => '_notify-validate',
];
$data = $request->all();
foreach ($data as $key => $value) {
$post[$key] = $value;
}
$response = (string) $this->provider->verifyIPN($post);
$ipn = new IPNStatus();
$ipn->payload = json_encode($post);
$ipn->status = $response;
$ipn->save();
// $user = Auth::user();
// Mail::to($user->email)->send(new UserPlanActivated($user));
}
protected function getCheckoutData($recurring = false)
{
$data = [];
$order_id = Invoice::all()->count() + 1;
$Itemm = Type::where('id', \Request::input('type_id'))->first();
// dd($Itemm['name']);
if ($recurring === true) {
$data['items'] = [
[
'name' => 'Monthly Subscription '.$Itemm['name'].' #'.$order_id,
'price' => $Itemm['price'],
'qty' => 1,
],
];
// $data['return_url'] = route('userec?mode=recurring');
$data['return_url'] = url('/paypal/ec-checkout-success?mode=recurring');
$data['subscription_desc'] = 'Monthly Subscription '.$Itemm['name'].' #'.$order_id;
} else {
$data['items'] = [
[
'name' => 'Monthly Subscription '.$Itemm['name'].' #'.$order_id,
'price' => $Itemm['price'],
'qty' => 1,
],
];
// $data['return_url'] = route('userec');
$data['return_url'] = url('/paypal/ec-checkout-success');
}
$data['invoice_id'] = $Itemm['name'].'_'.$order_id;
$data['invoice_description'] = "Order #$order_id Invoice";
$data['cancel_url'] = route('userpackages');
$total = 0;
foreach ($data['items'] as $item) {
$total += $item['price'] * $item['qty'];
}
$data['total'] = $total;
return $data;
}
protected function createInvoice($cart, $status)
{
$current = Carbon::now();
$expiredatetime = $current->addDays(30);
$invoice = new Invoice();
$invoice->user_id = Auth::user()->id;
$invoice->title = $cart['invoice_description'];
$invoice->price = $cart['total'];
$invoice->plan_expire = $expiredatetime->toDateTimeString();
collect($cart['items'])->each(function ($product) use ($invoice) {
$invoice->type_id = 3;
});
if (!strcasecmp($status, 'Completed') || !strcasecmp($status, 'Processed')) {
$invoice->paid = 1;
} else {
$invoice->paid = 0;
}
$invoice->save();
return $invoice;
}
Note
My error comes from this line in getExpressCheckoutSuccess function:
$response = $this->provider->createMonthlySubscription($response['TOKEN'], $cart['item']['price'], $cart['subscription_desc']);
I'm trying to use ignore method in laravel to apply validation on updating profile I have use ignore() for this but looks like I have gone somewhere wrong and ended up with this error can you help me out to find this here is my code. Thanks for your insights :)
User Controller
public function editProfile(Request $request) {
$userId=$request->userId;
$phoneNumber=$request->phoneNumber;
if(!$request){
$this->setMeta("422", "Nothing is there for update");
return response()->json($this->setResponse());
}
$validator =Validator::make($request->all(), [
'phoneNumber' => [
'max:10',
Rule::unique('users')->ignore($userId,'userId'),
],
]);
if ($validator->fails()) {
//$response['meta'] = array('code' => "422", 'message' => "Error, please try again");
$errors = $validator->errors();
if ($errors->first('phoneNumber')) {
$message = $errors->first('phoneNumber');
}
$this->setMeta("403", $message);
return response()->json($this->setResponse());
}
$homeTown = $request->homeTown;
$heightInCm=0;
/*$homeTownId= City::where('cityName', $homeTown)->first()->cityId;*/
if($request->userHeight) {
$userHeight=$request->userHeight;
$heightSplit = explode("'", $userHeight, 2);
$feet = $heightSplit[0];
$inches = $heightSplit[1];
$inch=($feet *12)+$inches;
$heightInCm=$inch*2.54;
}
$verticalInCm=0;
/*$homeTownId= City::where('cityName', $homeTown)->first()->cityId;*/
if($request->userVertical) {
$userVertical=$request->userVertical;
$verticalSplit = explode("'", $userVertical, 2);
$feet = $verticalSplit[0];
$inches = $verticalSplit[1];
$inch = ($feet *12)+$inches;
$verticalInCm = $inch*2.54;
}
$data= array(
'profilePic' => $request->profilePic,
'nickName' => $request->nickName,
'phoneNumber' => $request->phoneNumber,
'userHeight' => $heightInCm,
'userWeight' => $request->userWeight,
'userVertical' => $verticalInCm,
'userSchool' => $request->userSchool,
'homeTown' => $homeTown,
'cityId' => $request->cityId,
);
User::where('userId',$request->userId)->update($data);
}
Check if you specifying the correct key for the unique check. Your code says userId is the primary key to compare the given id with, is this correct? If the key is 'id' by default then you can ignore the parameter.
Rule::unique('users')->ignore($$request->userId),
'phoneNumber' => 'max:10|unique:users,id,'.$request->userId,
well after the hell of time spent I finally got the answer.
public function editProfile(Request $request) {
$userId=$request->userid;
$phoneNumber=$request->phoneNumber;
if(!$request){
$this->setMeta("422", "Nothing is there for update");
return response()->json($this->setResponse());
}
$validator = Validator::make(
array(
'phoneNumber' => $phoneNumber,
),
array(
'phoneNumber' =>'size:10', Rule::unique('users')->ignore($request->userId, 'userId'),
)
);
if ($validator->fails()) {
//$response['meta'] = array('code' => "422", 'message' => "Error, please try again");
$errors = $validator->errors();
if ($errors->first('phoneNumber')) {
$message = $errors->first('phoneNumber');
}
$this->setMeta("403", $message);
return response()->json($this->setResponse());
}
$homeTown = $request->homeTown;
$heightInCm=0;
/*$homeTownId= City::where('cityName', $homeTown)->first()->cityId;*/
if($request->userHeight) {
$userHeight=$request->userHeight;
$heightSplit = explode("'", $userHeight, 2);
$feet = $heightSplit[0];
$inches = $heightSplit[1];
$inch=($feet *12)+$inches;
$heightInCm=$inch*2.54;
}
$verticalInCm=0;
/*$homeTownId= City::where('cityName', $homeTown)->first()->cityId;*/
if($request->userVertical) {
$userVertical=$request->userVertical;
$verticalSplit = explode("'", $userVertical, 2);
$feet = $verticalSplit[0];
$inches = $verticalSplit[1];
$inch = ($feet *12)+$inches;
$verticalInCm = $inch*2.54;
}
$data= array(
'profilePic' => $request->profilePic,
'nickName' => $request->nickName,
'phoneNumber' => $request->phoneNumber,
'userHeight' => $heightInCm,
'userWeight' => $request->userWeight,
'userVertical' => $verticalInCm,
'userSchool' => $request->userSchool,
'homeTown' => $homeTown,
'cityId' => $request->cityId,
);
User::where('userId',$request->userId)->update($data);
$this->setMeta("200", "Profile Changes have been successfully saved");
$this->setData("userDetails", $data);
return response()->json($this->setResponse());
}