Laravel custom store mthod not working properly - php

I am intergrating paypal payment gateway on my application, before user first leave my site for paypal, I saved all the necessary information, and set payment_status to be 0, when user returns, if payment is sucessful, it returns to a new page where it gets the paymentId, and payerID, plus sets the paymentstatus to 1.
the thing is that if i set the database value for paymentID and PaymentId to null, it doesnt save.
if i dont set it to anything i.e leave it blank, it would save, but retruns an error:
Integrity constraint violation: 1048 Column 'PayerID' cannot be null (SQL: update `paypal_officers` set `paymentId` = , `PayerID` = , `updated_at` = 2018-07-15 07:29:21 where `id` = 1)
i cant seem to figure out what the problem is.
Here is the method that does the saving.
public function getPaymentStatus(Input $input)
{
/** Get the payment ID before session clear **/
$payment_id = Session::get('paypal_payment_id');
$insert_the_user_id = PaypalOfficer::findorFail(\session()->get('receivers_main_info_id'));
$insert_the_user_id->update([
'paymentId' => Input::get('paymentId'),
'PayerID' => Input::get('PayerID'),
'payment_status' => 1,
]);
$insert_the_user_id->save();
/** clear the session payment ID **/
Session::forget('paypal_payment_id');
if (empty(Input::get('PayerID')) || empty(Input::get('token'))) {
\Session::put('error', 'Payment failed');
return Redirect::to('account/send-money/paypal/send')->with('payer_id', $payment_id);;
}
$payment = Payment::get($payment_id, $this->_api_context);
$execution = new PaymentExecution();
$execution->setPayerId(Input::get('PayerID'));
/**Execute the payment **/
$result = $payment->execute($execution, $this->_api_context);
if ($result->getState() == 'approved') {
\Session::put('success', 'Payment success');
return Redirect::to('account/send-money/paypal/stagged/paypal')->with('payer_id', $result);
}
\Session::put('error', 'Payment failed');
return Redirect::to('account/send-money/paypal/send');
}
My Model
namespace App;
use Illuminate\Database\Eloquent\Model;
class PaypalOfficer extends Model
{
protected $fillable = [
'payment_status',
'paymentId',
'PayerID',
'user_id',
'amount',
'destination_account_number',
'destination_account_name',
'destination_bank_name',
'destination_phone_number',
'destination_country',
'destination_state',
'currency_symbol',
'receivers_name',
];
//
public function user(){
return $this->belongsTo(User::class);
}
}
Please what must i be missing in the code , anybody please!

Error occurs when Input::get('PayerID') is empty or null. You must be firstly check all required field exists in input, then try to update PaypalOfficer. Also in eloquent model use ->update method that case ->save does not need. Fix this part
public function getPaymentStatus(Input $input)
{
// firstly check PayerID and paymentId input exist
if (empty(Input::get('PayerID')) || empty(Input::get('paymentId')) || empty(Input::get('token'))) {
\Session::put('error', 'Payment failed');
return Redirect::to('account/send-money/paypal/send')->with('payer_id', $payment_id):
}
/** Get the payment ID before session clear **/
$payment_id = Session::get('paypal_payment_id');
$insert_the_user_id = PaypalOfficer::findorFail(\session()->get('receivers_main_info_id'));
$insert_the_user_id->update([
'paymentId' => Input::get('paymentId'),
'PayerID' => Input::get('PayerID'),
'payment_status' => 1,
]);
/** clear the session payment ID **/
Session::forget('paypal_payment_id');

Related

Laravel - Authorization to patch function

i have this PATCH function but i need to add some form of authorization to ensure you can only edit/update a film that is associated with the current user, can i get some help on how to add this
controller function:
public function update(string $id)
{
$this->user = Auth::user();
$this->film = film:findOrFail($id);
return $this->film->toJson();
}
I've looked at the laravel docs at the validation section and seen this example
$validatedData = $request->validate([
'title' => 'required|unque:posts|max:255',
'body' => 'required',
]);
i then added my own validation at the top of the file
protected $validation = [
'name' => 'string',
'description' => 'new description'
];
im a little lost on how i implement authorization to ensure only a current user can update a film?
What you're looking for is not a form validation, but a User Authorization (as in the comments). So you should have a look at the official documentation. In your case you should write a FilmPolicy that may look like to this (I will skip the registration part... It can be easily understood from the docs):
class FilmPolicy {
/**
* Determine if the given film can be updated by the user.
*
* #param \App\User $user
* #param \App\Post $post
* #return bool
*/
public function update(User $user, Film $film)
{
return $user->id === $film->user_id; // Or whatever is your foreign key
}
}
Then you should update your controller in order to handle the authorization as follow:
public function update(string $id)
{
$this->film = film::findOrFail($id);
$this->authorize('update', $this->film);
return $this->film->toJson();
}
Since this method simply throws an exception, you can have a more elaborate response as explained in the docs
Ok basically, to enable what you need in a simple way, what you can do is this;
First pass the 'user_id' to the controller.
public function update(string $id, $userid)
{
$user = Auth::user();
$id = $user->id;
if($id == $userid)
{
$this->user = Auth::user();
$this->film = film::findOrFail($id);
return $this->film->toJson();
}else{
return "Not Authorized";
}
}
If im not misunderstanding your question, this basically allows only the user who is logged in to update his film. if he goes into any other profile, the id's would mismatch and thus return a not authorized prompt.

100% discount on a one off charge with Stripe [Laravel]

In my Laravel application I have a page where users must pay £150 for a membership fee. To process this payment I chose Stripe.
I store all of the charges in a payments table, along with a user's ID.
Payments table
Schema::create('payments', function (Blueprint $table) {
$table->increments('id');
$table->uuid('user_id');
$table->string('transaction_id');
$table->string('description');
$table->string('amount');
$table->string('currency');
$table->datetime('date_recorded');
$table->string('card_brand');
$table->string('card_last_4', 4);
$table->string('status');
$table->timestamps();
});
I also implemented a voucher system of my own as I am not using subscriptions.
Voucher table
Schema::create('vouchers', function (Blueprint $table) {
$table->increments('id');
$table->string('code');
$table->integer('discount_percent');
$table->dateTime('expires_on');
$table->timestamps();
});
Payment Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Carbon\Carbon;
use App\User;
use App\Payment;
use App\Voucher;
use App\Mail\User\PaymentReceipt;
use App\Mail\Admin\UserMembershipPaid;
use Log;
use Mail;
use Validator;
use Stripe;
use Stripe\Error\Card;
class PaymentController extends Controller
{
/**
* Set an initial amount to be used by the controller
*
* #var float
*/
private $amount = 150.00;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
$this->middleware('verified');
$this->middleware('is_investor');
$this->middleware('is_passive_member');
}
/**
* Display a form allowing a user to make a payment
*
* #return void
*/
public function showPaymentForm()
{
return view('user.payment');
}
/**
* Handle an entered voucher code by the user
* Either calculate a discount or skip the payment form
*
* #param [type] $request
* #return void
*/
public function processVoucher(Request $request)
{
$rules = [
'code' => 'required|exists:vouchers',
];
$messages = [
'code.required' => 'You submitted a blank field',
'code.exists' => 'This voucher code is not valid'
];
Validator::make($request->all(), $rules, $messages)->validate();
$entered_voucher_code = $request->get('code');
$voucher = Voucher::where('code', $entered_voucher_code)->where('expires_on', '>', Carbon::now())->first();
// If the voucher exists
if ($voucher) {
$discount_percent = $voucher->discount_percent;
$new_amount = $this->amount - ($discount_percent / 100 * $this->amount);
// As Stripe won't handle charges of 0, we need some extra logic
if ($new_amount <= 0.05) {
$this->upgradeAccount(auth()->user());
Log::info(auth()->user()->log_reference . " used voucher code {$voucher->code} to get a 100% discount on their Active membership");
return redirect()->route('user.dashboard')->withSuccess("Your membership has been upgraded free of charge.");
}
// Apply the discount to this session
else {
Log::info(auth()->user()->log_reference . " used voucher code {$voucher->code} to get a {$voucher->discount_percent}% discount on their Active membership");
// Store some data in the session and redirect
session(['voucher_discount' => $voucher->discount_percent]);
session(['new_price' => $this->amount - ($voucher->discount_percent / 100) * $this->amount]);
return redirect()->back()->withSuccess([
'voucher' => [
'message' => 'Voucher code ' . $voucher->code . ' has been applied. Please fill in the payment form',
'new_price' => $new_amount
]
]);
}
}
// Voucher has expired
else {
return redirect()->back()->withError('This voucher code has expired.');
}
}
/**
* Handle a Stripe payment attempt from the Stripe Elements form
* Takes into account voucher codes if they are less than 100%
*
* #param Request $request
* #return void
*/
public function handleStripePayment(Request $request)
{
// Retreive the currently authenticated user
$user = auth()->user();
// Get the Stripe token from the request
$token = $request->get('stripeToken');
// Set the currency for your country
$currency = 'GBP';
// Set an initial amount for Stripe to use with the charge
$amount = $this->amount;
// A description for this payment
$description = "Newable Private Investing Portal - Active Membership fee";
// Initialize Stripe with given public key
$stripe = Stripe::make(config('services.stripe.secret'));
// Attempt a charge via Stripe
try {
Log::info("{$user->log_reference} attempted to upgrade their membership to Active");
// Check that token was sent across, if it wasn't, stop
if (empty($token)) {
return redirect()->back()->withErrors([
'error' => "Token error, do you have JavaScript disabled?"
]);
}
// Check whether a discount should be applied to this charge
if (session()->has('voucher_discount')) {
$discount_percentage = session()->pull('voucher_discount');
$discount = ($discount_percentage / 100) * $amount;
$amount = $amount - $discount;
session()->forget('new_price');
}
// Create a charge with an idempotent id to prevent duplicate charges
$charge = $stripe->idempotent(session()->getId())->charges()->create([
'amount' => $amount,
'currency' => $currency,
'card' => $token,
'description' => $description,
'statement_descriptor' => 'Newable Ventures',
'receipt_email' => $user->email
]);
//If the payment is successful, store the payment, send some emails and upgrade this user
if ($charge['status'] == 'succeeded') {
$this->storePayment($charge);
Mail::send(new PaymentReceipt($user));
Mail::send(new UserMembershipPaid($user));
$this->upgradeAccount($user);
return redirect()->route('user.dashboard')->withSuccess("Your payment was successful, you will soon recieve an email receipt.");
// If the payment was unsuccessful
} else {
$this->storePayment($charge);
Log::error("Stripe charge failed for {$user->log_reference}");
return redirect()->back()->withErrors([
'error' => "Unfortunately, your payment was unsuccessful."
]);
}
} catch (Exception $e) {
Log::error("Error attempting Stripe Charge for {$user->log_reference} - Exception - error details {$e->getMessage()}");
return redirect()->back()->withErrors([
'error' => $e->getMessage()
]);
} catch (\Cartalyst\Stripe\Exception\MissingParameterException $e) {
Log::error("Error attempting Stripe Charge for {$user->log_reference} - MissingParameterException - error details {$e->getMessage()}");
return redirect()->back()->withErrors([
'error' => $e->getMessage()
]);
} catch (\Cartalyst\Stripe\Exception\CardErrorException $e) {
Log::error("Error attempting Stripe Charge for {$user->log_reference} - CardErrorException - error details {$e->getMessage()}");
return redirect()->back()->withErrors([
'error' => $e->getMessage()
]);
} catch (\Cartalyst\Stripe\Exception\ApiLimitExceededException $e) {
Log::error("Error attempting Stripe Charge for {$user->log_reference} - ApiLimitExceededException - error details {$e->getMessage()}");
return redirect()->back()->withErrors([
'error' => $e->getMessage()
]);
} catch (\Cartalyst\Stripe\Exception\BadRequestException $e) {
Log::error("Error attempting Stripe Charge for {$user->log_reference} - BadRequestException - error details {$e->getMessage()}");
return redirect()->back()->withErrors([
'error' => $e->getMessage()
]);
} catch (\Cartalyst\Stripe\Exception\ServerErrorException $e) {
Log::error("Error attempting Stripe Charge for {$user->log_reference} - ServerErrorException - error details: {$e->getMessage()}");
return redirect()->back()->withErrors([
'error' => $e->getMessage()
]);
} catch (\Cartalyst\Stripe\Exception\UnauthorizedException $e) {
Log::error("Error attempting Stripe Charge for {$user->log_reference} - UnauthorizedException - error details: {$e->getMessage()}");
return redirect()->back()->withErrors([
'error' => $e->getMessage()
]);
}
}
/**
* Store a Stripe chargee in our database so we can reference it later if necessary
* Charges stored against users for cross referencing and easy refunds
*
* #return void
*/
private function storePayment(array $charge)
{
$payment = new Payment();
$payment->transaction_id = $charge['id'];
$payment->description = $charge['description'];
$payment->amount = $charge['amount'];
$payment->currency = $charge['currency'];
$payment->date_recorded = Carbon::createFromTimestamp($charge['created']);
$payment->card_brand = $charge['source']['brand'];
$payment->card_last_4 = $charge['source']['last4'];
$payment->status = $charge['status'];
auth()->user()->payments()->save($payment);
if ($payment->status === "succeeded") {
Log::info("Successful Stripe Charge recorded for {$user->log_reference} with Stripe reference {$payment->transaction_id} using card ending {$payment->card_last_4}");
} else {
Log::info("Failed Stripe Charge recorded for {$user->log_reference} with Stripe reference {$payment->transaction_id} using card ending {$payment->card_last_4}");
}
}
/**
* Handle a user account upgrade from whatever to Active
*
* #param User $user
* #return void
*/
private function upgradeAccount(User $user)
{
$current_membership_type = $user->member_type;
$user->member_type = "Active";
$user->save();
Log::info("{$user->log_reference} has been upgraded from a {$current_membership_type} member to an Active Member.");
}
}
processVoucher() takes a string entered by the user, checks to see if it exists in the vouchers table and then applies the discount percentage to the fee of 150.00.
It then adds the new value to the session and I use that in the Stripe Charge.
The issue
The issue is that Stripe's minimum chargable amount is 0.05, so to circumvent this issue I've just called a method that upgrades the account.
I should, in theory, store the free upgrades in the charges table but I would end up with multiple null values.
Is this a horrible solution?
In the User model I also have the following methods:
/**
* Relationship to payments
*/
public function payments()
{
return $this->hasMany(Payment::class, 'user_id', 'id');
}
/**
* Relationship to payments to get most recent payment
*
* #return void
*/
public function latest_payment()
{
return $this->hasOne(Payment::class, 'user_id', 'id')->latest();
}
These are used so I can calculate when a user last made a payment, as I needed to bill them annually without using subscriptions as users can also use 100% off vouchers to upgrade.
I made this console command:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Carbon\Carbon;
use App\User;
use App\Payment;
use Log;
class ExpireMembership extends Command
{
/**
* The name and signature of the console command.
*
* #var string
*/
protected $signature = 'membership:expire';
/**
* The console command description.
*
* #var string
*/
protected $description = 'Expire user memberships after 1 year of being Active.';
/**
* Create a new command instance.
*
* #return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* #return mixed
*/
public function handle()
{
//Retrieve all users who are an active member with their list of payments
$activeUsers = User::where('member_type', 'Active')->get();
//Get current date
$current_date = Carbon::now();
foreach($activeUsers as $user){
$this->info("Checking user {$user->log_reference}");
// If a user has at least one payment recorded
if($user->payments()->exists()){
//Get membership end date (latest payment + 1 year added)
$membership_end_date = $user->payments
->where('description', 'Newable Private Investing Portal - Active Membership fee')
->sortByDesc('created_at')
->first()->created_at->addYear();
}
// If the user has no payments but is an active member just check if they're older than a year
else{
$membership_end_date = $user->created_at->addYear();
}
//If the membership has gone over 1 year, expire the membership.
if ($current_date->lessThanOrEqualTo($membership_end_date)) {
$user->member_type = "Passive";
$user->save();
$this->info($user->log_reference . "membership has expired and membership status has been set to Passive.");
Log::info($user->log_reference . "membership has expired and membership status has been set to Passive.");
}
}
$this->info("Finished checking user memberships.");
}
}
Users who use vouchers do not have payments, so figuring out when to bill them automatically is tricky.

Implementing Payment Gataway in Laravel based shop

I need a little help with implementing payment getaway in Laravel shop.
Payment I use is https://gourl.io/ and I can't understand how to take needed information. So I have set the files database table, database connection and all.. Now I'm trying to redirect user to payment.php page after order form is submitted. This is my CartController.php orderSubmit function
public function orderSubmit() {
$cart = Session::get(self::CART_SESSION_KEY, array());
if (count($cart) < 1) {
return Redirect::to('/');
}
$validatorRules = array(
'captcha' => 'required|captcha',
'shipping_address' => 'required|min:10',
'shipping_method' => 'required|in:' . implode(',', [Settings::SETTINGS_SHIPPING_NORMAL, Settings::SETTINGS_SHIPPING_EXPRESS])
);
Input::merge(array_map('trim', Input::all()));
$validator = Validator::make(Input::all(), $validatorRules);
if ($validator->fails()) {
return Redirect::to('/cart/order?_token=' . csrf_token())->withErrors($validator->errors())->withInput(Input::except(['captcha']));
}
$shipping = array(
'quantity' => 1,
'image' => '/img/noimage.png',
'description' => '',
'title' => 'FIX ME', // this should never occur,
'price' => 100000 // this should never occur
);
switch (Input::get('shipping_method')) {
case Settings::SETTINGS_SHIPPING_NORMAL:
$shipping['title'] = 'Normal Delivery';
$shipping['price'] = 0;
break;
case Settings::SETTINGS_SHIPPING_EXPRESS:
$shipping['title'] = sprintf('Express Delivery - $%.2f', Settings::getOption('express_shipping_cost'));
$shipping['price'] = doubleval(Settings::getOption('express_shipping_cost'));
break;
}
$cart['shipping'] = $shipping;
$order = new Order();
$order->user_id = self::$user->user_id;
$order->data = json_encode($cart);
$order->address = Input::get('shipping_address');
$order->pgp_key = Input::get('gpgkey');
$order->info = Input::get('additional_info');
$order->save();
Session::put(self::CART_SESSION_KEY, array());
return Redirect::to('payment.php')->with('message_success', 'Order created! We will contact you shortly to confirm your order and payment details.');
}
and this is payment.php
require_once( "../cryptobox.class.php" );
/**** CONFIGURATION VARIABLES ****/
$userID = ""; // place your registered userID or md5(userID) here (user1, user7, uo43DC, etc).
// you don't need to use userID for unregistered website visitors
// if userID is empty, system will autogenerate userID and save in cookies
$userFormat = ""; // save userID in cookies (or you can use IPADDRESS, SESSION)
$orderID = "";
$amountUSD = 20;
$period = "NOEXPIRY";
$def_language = "en";
$public_key = "mypublickey";
$private_key = "myprivatekey";
/** PAYMENT BOX **/
$options = array(
"public_key" => $public_key, // your public key from gourl.io
"private_key" => $private_key, // your private key from gourl.io
"webdev_key" => "", // optional, gourl affiliate key
"orderID" => $orderID, // order id or product name
"userID" => $userID, // unique identifier for every user
"userFormat" => $userFormat, // save userID in COOKIE, IPADDRESS or SESSION
"amount" => 0, // product price in coins OR in USD below
"amountUSD" => $amountUSD, // we use product price in USD
"period" => $period, // payment valid period
"language" => $def_language // text on EN - english, FR - french, etc
);
// Initialise Payment Class
$box = new Cryptobox ($options);
// coin name
$coinName = $box->coin_name();
// Successful Cryptocoin Payment received
if ($box->is_paid())
{
if (!$box->is_confirmed()) {
$message = "Thank you for payment (payment #".$box->payment_id()."). Awaiting transaction/payment confirmation";
}
else
{ // payment confirmed (6+ confirmations)
// one time action
if (!$box->is_processed())
{
// One time action after payment has been made/confirmed
$message = "Thank you for order (order #".$orderID.", payment #".$box->payment_id()."). We will send soon";
// Set Payment Status to Processed
$box->set_status_processed();
}
else $message = "Thank you. Your order is in process"; // General message
}
}
else $message = "This invoice has not been paid yet";
$languages_list = display_language_box($def_language);
My question is how to take the correct info in the payment.php? How to take userID, userFormat, orderID and so on?
First of all, I would suggest you use Laravel as the framework it is intended for. In Laravel you define controllers to handle your http-requests. Make a new PaymentController and put the code from payment.php into this controller. Then make a route to that controller-method.
Also put your configuration settings in Laravels config-folder.
And the require_once( "../cryptobox.class.php" ); can be replaced by a dependency injection in your controllers constructor.
Now back to your question.
$userID is where you put your registered Laravel user ID. (If you dont have any registered users, leave it blank). Why you should put your user's id in this variable? -It helps to keep track of which users have done which payments. You can later save this information in your database if you want to keep track of payment history.
$orderID This is where you put your internal order id. Why should you use an internal order id? -Again its to keep track of which purchases of which products have been done by which users. You can store your order-id in your database together with user-id and product-id to get a purchase history log.
$userFormat This is how you wish to store your user information, session, cookie, etc. Because when the purchase is executed, the payment gateway needs a way to access this information, and therefor it must be stored in the session or in a cookie.
I would use $_SESSION['$value'] if you use session for your users!

Check if laravel model got saved or query got executed

I've seen alot of people using this way to check if a laravel model got saved. So now I wonder if it is a safe way.
And also can I check if the queries bellow got executed like this
Check if model got saved
Eg:
$myModel = new User();
$myModel->firstname = Input::get('firstname');
$myModel->lastname = Input::get('lastname');
$myModel->save();
//Check if user got saved
if ( ! $myModel->save())
{
App::abort(500, 'Error');
}
//User got saved show OK message
return Response::json(array('success' => true, 'user_added' => 1), 200);
Is the above a safe way to check whenever my model got saved or not?
Check if query returned a result
Eg:
$UserProduct = Product::where('seller_id', '=', $userId)->first();
if (! $UserProduct)
{
App::abort(401); //Error
}
Does above return an error if no product where found?
Check if query got executed
Eg:
$newUser = User::create([
'username' => Input::get('username'),
'email' => Input::get('email')
]);
//Check if user was created
if ( ! $newUser)
{
App::abort(500, 'Some Error');
}
//User was created show OK message
return Response::json(array('success' => true, 'user_created' => 1), 200);
Does above check if a user was created?
Check if model got saved
save() will return a boolean, saved or not saved. So you can either do:
$saved = $myModel->save();
if(!$saved){
App::abort(500, 'Error');
}
Or directly save in the if:
if(!$myModel->save()){
App::abort(500, 'Error');
}
Note that it doesn't make sense to call save() two times in a row like in your example. And by the way, many errors or problems that would keep the model from being saved will throw an exception anyways...
Check if query returned a result
first() will return null when no record is found so your check works find. However as alternative you could also use firstOrFail() which will automatically throw a ModelNotFoundException when nothing is found:
$UserProduct = Product::where('seller_id', '=', $userId)->firstOrFail();
(The same is true for find() and findOrFail())
Check if query got executed
Unfortunately with create it's not that easy. Here's the source:
public static function create(array $attributes)
{
$model = new static($attributes);
$model->save();
return $model;
}
As you can see it will create a new instance of the model with the $attributes and then call save(). Now if save() where to return true you wouldn't know because you'd get a model instance anyways. What you could do for example is check for the models id (since that's only available after the record is saved and the newly created id is returned)
if(!$newUser->id){
App::abort(500, 'Some Error');
}
You can also check the public attribute $exists on your model.
if ($myModel->exists) {
// Model exists in the database
}
I would do such move to when I use Model::create method :
$activity = Activity::create($data);
if ($activity->exists) {
// success
} else {
// failure
}
As for the Save method it's easier because $model->save() returns Bool :
$category = new Category();
$category->category_name = $request->category_name;
$is_saved = $category->save();
if ($is_saved) {
// success
} else {
// failure
}
/**
* Store a newly created country in storage.
*
* #url /country
* #method POST
* #param Request $request
* #return \Illuminate\Http\JsonResponse
*/
public function store(Request $request)
{
# Filer & only get specific parameters.
$request = $request->only('code', 'name', 'status');
# Assign login user(Auth Control).
$request['created_by'] = Auth::user()->id;
# Insert data into `countries` table.
$country = Country::create($request);
if(!$country)
throw new Exception('Error in saving data.');
}

PHP: Return id of the updated row in Laravel 4

I am trying to return the last updated ID in my Laravel application. I have a payment inserted into the database. When there is refund from PayPal the IPN will update the payment_status to "Refunded". Now after updating this needs to return the id of the updated column. But I am getting null. Here is what I have tried.
1st method:
$is_updated = $this->whereTxnId($ipn_array['parent_txn_id'])
->update(array(
'payment_status' => $ipn_array['payment_status'],
'refund_txn_id' => $ipn_array['txn_id']
));
if($is_updated) {
return $this->id;
}
2nd method:
$txn_id_matching = $this->whereTxnId($ipn_array['parent_txn_id']);
$txn_id_matching->payment_status = $ipn_array['payment_status'];
$txn_id_matching->refund_txn_id = $ipn_array['txn_id'];
$is_updated = $txn_id_matching->save();
if($is_updated) {
return $txn_id_matching->id;
}
How can I retrieve the updated id?
With your second method use
$is_updated->id
I fixed it using the below code. I do not know if this code is efficient but it fixed my issue.
public function unlockIpnUpdate($ipn_array) {
$is_updated = $this->whereTxnId($ipn_array['parent_txn_id'])
->update(array(
'payment_status' => $ipn_array['payment_status'],
'refund_txn_id' => $ipn_array['txn_id']
));
$txn_id_matching = $this->whereTxnId($ipn_array['parent_txn_id'])->first();
if($is_updated) {
return $txn_id_matching->id;
}
return false;
}

Categories