Laravel: Mollie - webhook failed with status code 500 - php

I'm using the mollie developer setup to simulate payment offers. I've followed a tutorial by my teacher and he hasn't any problems. So what is going on?
Because Mollie is an online service, I'm using Ngrok to create a tunnel for the webhook and my localhost. I'll post my code below but know that I wrote a Log which gave as response:
[2022-07-26 18:22:54] local.ERROR: Method App\Http\Controllers\webHookController::handle does not exist. {"exception":"[object] (BadMethodCallException(code: 0): Method App\Http\Controllers\webHookController::handle does not exist. at C:\Users\stefv\SCHOOL\GENT\NMD\WEBDEV2\werkstuk---geboortelijst-Stef-Verniers\vendor\laravel\framework\src\Illuminate\Routing\Controller.php:68)
I have no clue what exact error this log is targeting so if anyone can point this out, it's much appreciated!
Because the webhook can't get to mollie my status inside my database can't be changed so it's on 'pending' forever...
So I'm looking for a way to fix the error so my webhook can reach Mollie and my payment is accepted so the payment status in my database can change to 'paid'.
This is my code:
My Controller which sets up Mollie:
public function additional(Request $r)
{
$articles = Article::all();
$categories = Category::all();
$websites = Website::all();
$session_id = request()->session()->getId();
$cartItems = Cart::session($session_id)->getContent();
$cartTotal = Cart::session($session_id)->getTotal();
$r->session()->put('cusnaam', 'Cas');
$r->session()->put('tel', 'Tel');
$r->session()->put('email', 'Email');
$r->session()->put('pb', 'pb');
return view('customer-info', compact('articles', 'categories', 'websites', 'cartItems', 'cartTotal'));
}
public function checkout(Request $r)
{
$session_id = request()->session()->getId();
$cartTotal = Cart::session($session_id)->getTotal();
$order = new Order();
$order->name = $r->input('Cus');
$order->note = $r->input('pb');
$order->total = $cartTotal;
$order->status = 'pending';
$order->save();
$mollie = new \Mollie\Api\MollieApiClient();
$mollie->setApiKey("test_6vGchNb62gynePtcsNsbm8dartsmjU");
$mollie->methods->allAvailable();
$session_id = request()->session()->getId();
$cartItems = Cart::session($session_id)->getContent();
$valuta = number_format($cartTotal, 2);
$webhookUrl = route('webhooks.mollie');
if(App::environment('local')) {
$webhookUrl = 'https://5d25-84-199-205-243.eu.ngrok.io/webhooks/mollie';
};
$payment = Mollie::api()->payments->create([
"amount" => [
"currency" => "EUR",
"value" => $valuta // You must send the correct number of decimals, thus we enforce the use of strings
],
"description" => "Bestelling op dag " . date('d-m-Y h:i'),
"redirectUrl" => route('success'),
"webhookUrl" => $webhookUrl,
"metadata" => [
"order_id" => $order->id,
"order_name" => $order->name
],
]);
return redirect($payment->getCheckoutUrl(), 303);
}
public function success()
{
return view('succes');
}
And this is the controller that handles the webhook:
public function handleWebhookNotification(Request $request)
{
$payment = Mollie::api()->payments->get($request->id);
$orderId = $payment->metadata->order_id;
if ($payment->isPaid() && ! $payment->hasRefunds() && ! $payment->hasChargebacks()) {
$order = Order::findOrFail($orderId);
$order->status = 'paid';
$order->save();
Log::alert('tis in de cachoche');
} elseif ($payment->isOpen()) {
/*
* The payment is open.
*/
} elseif ($payment->isPending()) {
/*
* The payment is pending.
*/
} elseif ($payment->isFailed()) {
/*
* The payment has failed.
*/
} elseif ($payment->isExpired()) {
/*
* The payment is expired.
*/
} elseif ($payment->isCanceled()) {
/*
* The payment has been canceled.
*/
} elseif ($payment->hasRefunds()) {
/*
* The payment has been (partially) refunded.
* The status of the payment is still "paid"
*/
} elseif ($payment->hasChargebacks()) {
/*
* The payment has been (partially) charged back.
* The status of the payment is still "paid"
*/
}
}

Related

Symfony 5 - A problem with the form to registrate a credit card with MangoPay

I'm trying to register a credit card with MangoPay.
I've installed the mangopay/php-sdk-v2 package.
To register a credit card, it needs three steps.
Create a token of the card
Post card info (using a url created by the token) that will render a string that start with data=
Add the registered card to the MangoPay user
// ProfilController.php
/**
* #Route("/payment/{id}", name="payment")
* * #param int $id
*/
public function payment(Request $request, ApiUser $ApiUser, $id): Response
{
$returnUrl = "";
$user = $this->userRepository->findOneBy(['id' => $id]);
$userId = $user->getIdMangopay();
$registration = $ApiUser->Registration($userId);
if($request->request->count() > 0){
$payment = new PaymentMethod();
$payment->setName($request->request->get('name'));
$payment->setCardNumber($request->request->get('cardNumber'));
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($payment);
$entityManager->flush();
$registrationCard = $ApiUser->RegistrationCard($registration, $request);
$returnUrl = 'http' . (isset($_SERVER['HTTPS']) ? 's' : '') . '://' . $_SERVER['HTTP_HOST'];
$returnUrl .= '/profil';
}
return $this->render('home/payment.html.twig', [
'CardRegistrationUrl' => $registration->CardRegistrationURL,
'Data' => $registration->PreregistrationData,
'AccessKeyRef' => $registration->AccessKey,
'returnUrl' => $returnUrl,
]);
}
The Registration and ResitrationCard functions come from the ApiUser file:
// ApiUser.php
public function Registration($UserId)
{
$CardRegistration = new \MangoPay\CardRegistration();
$CardRegistration->UserId = $UserId;
$CardRegistration->Currency = "EUR";
$CardRegistration->CardType = "CB_VISA_MASTERCARD";
$Result = $this->mangoPayApi->CardRegistrations->Create($CardRegistration);
$this->registrationInfo = $Result;
$this->CardRegistrationUrl = $Result->CardRegistrationURL;
return $Result;
}
public function RegistrationCard($CardInfo)
{
$cardRegister = $this->mangoPayApi->CardRegistrations->Get($CardInfo->Id);
$cardRegister->RegistrationData = $_SERVER['QUERY'];
$updatedCardRegister = $this->mangoPayApi->CardRegistrations->Update($cardRegister);
return $Result;
}
I'm able to create the token of the card and get the data= string, but the problem is that I cannot do the last step.
It seems that I cannot enter into the if statement, so it doesn't register the card on the database and I cannot update the card information (3rd step).
The returnUrl, I can simply put it outside of the if statement to make it works, but I want to change it only if the form is valid.
How can I fix the statement? Why doesn't it enter into the if?
Please try to use the regular form validation process of Symfony, and let me know if this helps.
To do this, you need to customize the input name attribute for it to match the payment API config.
In your Type class:
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
// ...
->add('new-input-name-goes-here', TextType::class, [
'property_path' => '[data]'
]);
}
public function getBlockPrefix()
{
return '';
}

What parameters do I pass to doExpressCheckouPaymentt()?

I have this controller that is supposed to perform PayPal payments. The payment function is working well but on getting to success function I am getting an error Illegal string offset 'total' . I am passing $this->productData($request) as suggested in this question. I tried creating a variable $total = $response['AMT'] which is the response from setCheckoutDetails but I still got the same error. How do I go about it?
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Srmklive\PayPal\Services\ExpressCheckout;
class PayPalController extends Controller
{
private function projectData(Request $request){
// dd($request->all());
$item = [];
$datat = array_map(function($item){
return [
'name'=>$request->project_id,
'price'=>$request->budget,
'desc'=>'Deposit',
'qty'=>1
];
}, $item);
$data = [
'items'=>$datat,
'invoice_id' => uniqid(),
'invoice_description' => "Payment for Project No.".$request->project_id." Amount ".$request->budget,
'return_url' => route('payment.success'),
'cancel_url' => route('payment.cancel'),
'total'=>$request->budget
];
// dd($data);
return $data;
}
/**
* Responds with a welcome message with instructions
*
* #return \Illuminate\Http\Response
*/
public function payment(Request $request) {
$data = $this->projectData($request);
$provider = new ExpressCheckout;
$response = $provider->setExpressCheckout($data);
// dd($response);
// $response = $provider->setExpressCheckout($data, true);
return redirect($response['paypal_link']);
}
/**
* Responds with a welcome message with instructions
*
* #return \Illuminate\Http\Response
*/
public function cancel()
{
dd('Your payment is canceled. You can create cancel page here.');
}
/**
* Responds with a welcome message with instructions
*
* #return \Illuminate\Http\Response
*/
public function success(Request $request)
{
$provider = new ExpressCheckout;
$response = $provider->getExpressCheckoutDetails($request->token);
$token = $response['TOKEN'];
$payerId = $response['PAYERID'];
$total = $response['AMT'];
// dd($response);
if (in_array(strtoupper($response['ACK']), ['SUCCESS', 'SUCCESSWITHWARNING'])) {
// dd('Payment successful');
//Performing transaction
$payment_status = $provider->doExpressCheckoutPayment($token, $payerId, $this->projectData($request));
dd($payment_status);
}
dd('Something is wrong.');
}
}
You have to pass three parameters
data, token, PAYERID
Data can service information like
$data = array(
'total' => Total amount,
'invoice_id' => Invoicen number,
'invoice_description' => invoice descrption
);
And items as well which will contain name, price, desc and qty

Yii2 paypal payment integration

I am using this https://www.yiiframework.com/extension/bitcko/yii2-bitcko-paypal-api#usage With yii2 to enable payments my code looks like this.
public function actionMakePayment(){
if(!Yii::$app->user->getIsGuest()){
// Setup order information array
$params = [
'order'=>[
'description'=>'Payment description',
'subtotal'=>45,
'shippingCost'=>0,
'total'=>45,
'currency'=>'USD',
]
];
// In case of payment success this will return the payment object that contains all information about the order
// In case of failure it will return Null
Yii::$app->PayPalRestApi->processPayment($params);
}else{
Yii::$app->response->redirect(Url::to(['site/signup'], true));
}
Everything is went as per my expectation this call is returning somthing like this to dom.
{ "id": "PAYID-LTKUAVA8WK14445NN137182H", "intent": "sale", "state": "approved", "cart": "9RE74926AX5730813", "payer": { "payment_method": "paypal", "status": "UNVERIFIED", "payer_info": { "first_name": "Susi", "last_name": "Flo", "payer_id": "KWPDGYRP2KCK4", "shipping_address": { "recipient_name": "Susi Flo", "line1": "Suso", "line2": "bldg", "city": "Spring hill", "state": "FL", "postal_code": "34604", "country_code": "US" }, "phone": "3526003902", "country_code": "US" } }, "transactions": [ { "amount": { "total": "45.00", "currency": "USD", "details": { "subtotal": "45.00", "shipping": "0.00", "insurance": "0.00", "handling_fee": "0.00", "shipping_discount": "0.00" } }, "payee": { "merchant_id": "NHN6S6KT4FF6N", "email": "arunwebber2-facilitator#gmail.com" }, "description": "Payment description", "invoice_number": "5cd5404d624a9", "soft_descriptor": "PAYPAL *TESTFACILIT", "item_list": { "items": [ { "name": "Item one", "price": "45.00", "currency": "USD", "tax": "0.00", "quantity": 1 } ], "shipping_address": { "recipient_name": "Susi Flo", "line1": "Suso", "line2": "bldg", "city": "Spring hill", "state": "FL", "postal_code": "34604", "country_code": "US" } }, "related_resources": [ { "sale": { "id": "6LN25215GP1183020", "state": "completed", "amount": { "total": "45.00", "currency": "USD", "details": { "subtotal": "45.00", "shipping": "0.00", "insurance": "0.00", "handling_fee": "0.00", "shipping_discount": "0.00" } }, "payment_mode": "INSTANT_TRANSFER", "protection_eligibility": "ELIGIBLE", "protection_eligibility_type": "ITEM_NOT_RECEIVED_ELIGIBLE,UNAUTHORIZED_PAYMENT_ELIGIBLE", "transaction_fee": { "value": "2.43", "currency": "USD" }, "receipt_id": "3896118010137330", "parent_payment": "PAYID-LTKUAVA8WK14445NN137182H", "create_time": "2019-05-10T09:30:10Z", "update_time": "2019-05-10T09:30:10Z", "links": [ { "href": "https://api.sandbox.paypal.com/v1/payments/sale/6LN25215GP1183020", "rel": "self", "method": "GET" }, { "href": "https://api.sandbox.paypal.com/v1/payments/sale/6LN25215GP1183020/refund", "rel": "refund", "method": "POST" }, { "href": "https://api.sandbox.paypal.com/v1/payments/payment/PAYID-LTKUAVA8WK14445NN137182H", "rel": "parent_payment", "method": "GET" } ], "soft_descriptor": "PAYPAL *TESTFACILIT" } } ] } ], "create_time": "2019-05-10T09:11:48Z", "update_time": "2019-05-10T09:30:10Z", "links": [ { "href": "https://api.sandbox.paypal.com/v1/payments/payment/PAYID-LTKUAVA8WK14445NN137182H", "rel": "self", "method": "GET" } ] }
How can I store this to my database? for a specefi user id i can get user id with this.
echo Yii::$app->user->id;
I want to store this value along with the user id how can I do that? And a payment success message to the user :)
Update
Looks like the component class needs to be fully copied and edited before it can correctly override the checkOut() method as the property $apiContext accessed in the method is private rather than being $protected so either you copy that whole component and place it in you frontend/components directory and change it accordingly and then use.
Above all that class is poorly designed and written too, it would be better if you use the following component that i have been using in my Yii2 projects. I havent removed the extra code and have pasted the file as is in the answer. you can remove/comment the part related to the BalanceHistory TransactionHistory and the email part. you need to install paypal checkout sdk via composer or add below in your composer.json
"paypal/paypal-checkout-sdk": "1.0.1"
Paypal Component
<?php
namespace frontend\components;
use Yii;
use common\models\{
User,
BalanceHistory,
TransactionHistory
};
use yii\base\Component;
use common\components\Helper;
use PayPalCheckoutSdk\Core\{
PayPalHttpClient,
SandboxEnvironment,
ProductionEnvironment
};
use PayPalCheckoutSdk\Orders\{
OrdersGetRequest,
OrdersCreateRequest,
OrdersCaptureRequest
};
class Paypal extends Component
{
/**
* The Pyapal Client Id
*
* #var mixed
*/
public $clientId;
/**
* The Paypal client Secret
*
* #var mixed
*/
public $clientSecret;
/**
* API context object
*
* #var mixed
*/
private $httpClient; // paypal's http client
/**
* #var mixed
*/
private $user_id;
/**
* Override Yii's object init()
*
* #return null
*/
public function init()
{
$this->httpClient = new PayPalHttpClient(
Yii::$app->params['paypal']['mode'] == 'sandbox' ?
new SandboxEnvironment($this->clientId, $this->clientSecret) :
new ProductionEnvironment($this->clientId, $this->clientSecret)
);
$this->user_id = Yii::$app->user->id;
Yii::info("User: {$this->user_id} Init PayPal", 'paypal');
}
/**
* Returns the context object
*
* #return object
*/
public function getClient()
{
return $this->httpClient;
}
/**
* Set the payment methods and other objects necessary for making the payment
*
* #param decimal $price the amount to be charged
*
* #return string $approvalUrl
*/
public function createOrder($price)
{
//create order request
$request = new OrdersCreateRequest();
$request->prefer('return=representation');
setlocale(LC_MONETARY, 'en_US.UTF-8');
$price = sprintf('%01.2f', $price);
Yii::info("User: {$this->user_id} Setting payment for amount: {$price}", 'paypal');
//build the request body
$requestBody = [
'intent' => 'CAPTURE',
'purchase_units' =>
[
0 =>
[
'amount' =>
[
'currency_code' => 'USD',
'value' => $price,
],
],
],
'application_context' => [
'shipping_preference' => 'NO_SHIPPING'
]
];
$request->body = $requestBody;
//call PayPal to set up a transaction
$client = $this->getClient();
$response = $client->execute($request);
return json_encode($response->result, JSON_PRETTY_PRINT);
}
/**
* #param $orderId
*/
public function getOrder($orderId)
{
// 3. Call PayPal to get the transaction details
$request = new OrdersGetRequest($orderId);
$client = $this->getClient();
$response = $client->execute($request);
return json_encode($response->result, JSON_PRETTY_PRINT);
}
/**
* Retrieves Order Capture Details for the given order ID
*
* #param string $orderId the payment id of the transaction
*
* #return mixed
*/
public function captureOrder($orderId)
{
$request = new OrdersCaptureRequest($orderId);
//Call PayPal to capture an authorization
$client = $this->getClient();
$transaction = Yii::$app->db->beginTransaction();
try {
$response = $client->execute($request);
//get payment variables for email
$paymentId = $response->result->id;
$paymentStatus = $response->result->status;
$paypalTransaction = $response->result->purchase_units[0]->payments->captures[0];
$payedAmount = $paypalTransaction->amount->value;
$txnId = $paypalTransaction->id;
$userId = $this->user_id;
//get the user
$model = User::findOne($userId);
$profile = $model->businessProfile;
$prevBalance = $profile->balance;
if ($paymentStatus == 'COMPLETED') {
Yii::info("User: {$userId} payment amount:{$payedAmount} approved updating balance.", 'paypal');
//update balance
$newBalance = $profile->updateBalance($payedAmount);
Yii::info("User: {$userId} balance updated.", 'paypal');
$data = [
'amount' => $payedAmount,
'type' => TransactionHistory::BALANCE_ADDED,
'description' => "Funds added to account",
'user' => [
'id' => $userId,
'balance' => $newBalance,
],
];
Yii::info("User: {$userId} adding transaction history.", 'paypal');
TransactionHistory::add($data);
//update subscription status if required
if ($profile->subscription_status !== 'active') {
$profile->updateStatus('active');
}
Yii::info("User: {$userId} adding balance history:{$payedAmount}.", 'paypal');
//send the success email to the user and admin
$this->sendNotification($model, $response->result);
//set session flash with success
Yii::$app->session->setFlash(
'success',
'Your Payment is processed and you will receive an email with the details shortly'
);
} else {
Yii::warning("User: {$userId} payment amount:{$payedAmount} NOT approved.", 'paypal');
//send the error email to the user and admin
$this->sendNotification($model, $response->result, 'error');
//set session flash with error
Yii::$app->session->setFlash(
'danger',
'Your Payment was not approved, an email has been sent with the details.'
);
}
//update balance history
BalanceHistory::add(
$profile->user_id,
$prevBalance,
$payedAmount,
$paymentId,
$paymentStatus,
$txnId,
$response
);
//commit the transaction
$transaction->commit();
Yii::info(
"User: {$userId} payment Success prevBalance: {$prevBalance} payedAmount:{$payedAmount}.",
'paypal'
);
return json_encode($response->result, JSON_PRETTY_PRINT);
} catch (\Exception $e) {
//roll back the transaction
$transaction->rollBack();
Yii::error("ERROR EXCEPTION", 'paypal');
Yii::error($e->getMessage(), 'paypal');
Yii::error($e->getTraceAsString(), 'paypal');
//send error email to the developers
Helper::sendExceptionEmail(
"TC : Exception on PayPal Balance",
$e->getMessage(),
$e->getTraceAsString()
);
//set session flash with error
Yii::$app->session->setFlash('danger', $e->getMessage());
}
}
/**
* Sends Success Email for the transaction
*
* #param \common\models\User $model the user model object
* #param $response the paypal Order Capture object
* #param string $type the type of the notification to be sent
*
* #return null
*/
public function sendNotification(
\common\models\User $model,
$response,
$type = 'success'
) {
Yii::info("User: {$this->user_id} Sending notifications type:{$type}", 'paypal');
$paymentId = $response->id;
$paymentStatus = $response->status;
$paypalTransaction = $response->purchase_units[0]->payments->captures[0];
$payedAmount = $paypalTransaction->amount->value;
//payment creation time
$paymentCreateTime = new \DateTime(
$paypalTransaction->create_time,
new \DateTimeZone('UTC')
);
//payment update time
$paymentUpdateTime = new \DateTime(
$paypalTransaction->update_time,
new \DateTimeZone('UTC')
);
//payer/billing info for email
$payerInfo = $response->payer;
$payerEmail = $payerInfo->email_address;
$payerFirstName = $payerInfo->name->given_name;
$payerLastName = $payerInfo->name->surname;
$billingInfo = [
'billing_info' => [
'email' => $payerEmail,
'full_name' => "$payerFirstName $payerLastName",
],
];
if (property_exists($response->purchase_units[0], 'shipping')) {
$payerAddress = property_exists($response->purchase_units[0]->shipping->address, 'address_line_1');
$isStateAvailable = property_exists($response->purchase_units[0]->shipping->address, 'admin_area_1');
$isPostCodeAvailable = property_exists($response->purchase_units[0]->shipping->address, 'postal_code');
$iscountryCodeAvailable = property_exists($response->purchase_units[0]->shipping->address, 'country_code');
//#codingStandardsIgnoreStart
$payerState = $isStateAvailable ? $response->purchase_units[0]->shipping->address->admin_area_1 : 'NA';
$payerPostalCode = $isPostCodeAvailable ? $response->purchase_units[0]->shipping->address->postal_code : 'NA';
$payerCountryCode = $iscountryCodeAvailable ? $response->purchase_units[0]->shipping->address->country_code : 'NA';
//#codingStandardsIgnoreEnd
$billingInfo['billing_info'] = array_merge(
$billingInfo['billing_info'],
[
'address' => $payerAddress,
'state' => $payerState,
'country' => $payerCountryCode,
'post_code' => $payerPostalCode,
]
);
}
//email params
$data = [
'user' => [
'email' => $model->email,
'name' => $model->username,
],
'payment_id' => $paymentId,
'amount' => $payedAmount,
'status' => $paymentStatus,
'create_time_utc' => $paymentCreateTime,
'update_time_utc' => $paymentUpdateTime,
];
$data = array_merge($data, $billingInfo);
//check the notification email type and set params accordingly
if ($type == 'success') {
$txnId = $paypalTransaction->id;
$data['txn_id'] = $txnId;
$subject = Yii::$app->id . ': Your Account has been recharged.';
$view = '#frontend/views/user/mail/payment-complete';
} else {
$subject = Yii::$app->id . ': Transaction failed.';
$view = '#frontend/views/user/mail/payment-failed';
}
Yii::info("User: {$this->user_id} Sending email to user:{$model->email} type: {$type}", 'paypal');
//send email to user
$model->sendEmail($subject, $view, $data, $model->email);
//send notification to admin for Payment Received
$data['user']['email'] = Yii::$app->params['adminEmail'];
$subject = ($type == 'success') ?
Yii::$app->id . ': New Transaction in Account.' :
Yii::$app->user->id . ': A Transaction Failed for the user.';
Yii::info(
"User: {$this->user_id} Sending email to admin " . Yii::$app->params['adminEmail'] . " type: {$type}",
'paypal'
);
//send admin email
$model->sendEmail($subject, $view, $data, Yii::$app->params['adminEmail']);
}
}
Usage
You can call createOrder and then the captureOrder respectively. I was using it with ajax approach so i had separate actions defined like below
/**
* Displays fail message to the user
*
* #param string $token the cancel token
*
* #return mixed
* #throws \Exception
*/
public function actionPaymentCancel($token)
{
Yii::warning("Payment Cancel : token: {$token}.", 'paypal');
return $this->render(
'payment-cancelled',
[
'data' => $token,
]
);
}
/**
* Shows the payment details & success message to the user
*
* #param string $paymentId the payment id
*
* #return mixed
* #throws \Exception
*/
public function actionPaymentComplete($paymentId)
{
$history = BalanceHistory::findOne(['payment_id' => $paymentId]);
return $this->render(
'payment-complete',
[
'data' => $history,
]
);
}
/**
* Captures the Paypal order and verifies it
*
* #param string $orderId the Paypal order object's id
*
* #return mixed
*/
public function actionCaptureOrder($orderId)
{
$orderInfo = Yii::$app->paypal->captureOrder($orderId);
return $orderInfo;
}
/**
* Creates the order and
*
* #param string $amount the price of the order
*
* #return mixed
*/
public function actionCreateOrder($amount)
{
if (!Yii::$app->user->isGuest) {
$order = Yii::$app->paypal->createOrder($amount);
return $order;
}
throw new Exception("You are not logged in.", 404);
}
/**
* Executes the payement and checkouts to the paypal to confirm
*
* #param string $token the paypal token
*
* #return mixed
*/
public function actionPaymentExecute($orderId)
{
//get transaction details
$details = Yii::$app->paypal->getOrder($orderId);
$details = json_decode($details);
//added check for duplicate hits to return url from Paypal
if (null !== BalanceHistory::transactionExists($orderId)) {
//redirect to payment complete
return $this->redirect(['payment-complete', 'paymentId' => $orderId]);
}
if ($details->status == 'COMPLETED') {
//redirect to payment complete
return $this->redirect(['payment-complete', 'paymentId' => $orderId]);
} else {
//redirect to the payment failed page
return $this->redirect(['payment-failed', 'paymentId' => $orderId]);
}
}
ALso keep in mind that you need to declare a param with live and local ENV for the paypal gateway which turns sandbox environment ON/OFF.
params-local.php
<?php
'paypal'=>[
'sandbox'=>true
]
?>
params.php
<?php
'paypal'=>[
'sandbox'=>false
]
?>
Paypal PHP-SDK Provides you the setCustom() to add a custom field value, you can use it to send the user id and then retrieve it with the response in the transaction object after the payment is executed.
What you are using is just a custom component using the Paypal SDK functions,you should extend the class bitcko\paypalrestapi\PayPalRestApi.php to override the function checkOut() and add the ->setCustom(Yii::$app->user->id) to the chain in this line, as it does not provide any way to set the custom field, so just copy the whole code of the method into your new class and add the above.
Your class should look like below.
NOTE: Add the file inside common/components folder.
<?php
namespace common\components;
use bitcko\paypalrestapi\PayPalRestApi as PayPalBase;
use PayPal\Api\Amount;
use PayPal\Api\Details;
use PayPal\Api\Item;
use PayPal\Api\ItemList;
use PayPal\Api\Payer;
use PayPal\Api\Payment;
use PayPal\Api\RedirectUrls;
use PayPal\Api\Transaction;
use PayPal\Exception\PayPalConnectionException;
use yii\helpers\Url;
use Yii;
class PaypalRestApi extends PayPalBase
{
public function checkOut($params)
{
$payer = new Payer();
$payer->setPaymentMethod($params['method']);
$orderList = [];
foreach ($params['order']['items'] as $orderItem) {
$item = new Item();
$item->setName($orderItem['name'])
->setCurrency($orderItem['currency'])
->setQuantity($orderItem['quantity'])
->setPrice($orderItem['price']);
$orderList[] = $item;
}
$itemList = new ItemList();
$itemList->setItems($orderList);
$details = new Details();
$details->setShipping($params['order']['shippingCost'])
->setSubtotal($params['order']['subtotal']);
$amount = new Amount();
$amount->setCurrency($params['order']['currency'])
->setTotal($params['order']['total'])
->setDetails($details);
$transaction = new Transaction();
$transaction->setAmount($amount)
->setItemList($itemList)
->setDescription($params['order']['description'])
->setCustom(Yii::$app->user->id)
->setInvoiceNumber(uniqid());
$redirectUrl = Url::to([$this->redirectUrl], true);
$redirectUrls = new RedirectUrls();
$redirectUrls->setReturnUrl("$redirectUrl?success=true")
->setCancelUrl("$redirectUrl?success=false");
$payment = new Payment();
$payment->setIntent($params['intent'])
->setPayer($payer)
->setRedirectUrls($redirectUrls)
->setTransactions(array($transaction));
try {
$payment->create($this->apiContext);
return \Yii::$app->controller->redirect($payment->getApprovalLink());
} catch (PayPalConnectionException $ex) {
// This will print the detailed information on the exception.
//REALLY HELPFUL FOR DEBUGGING
\Yii::$app->response->format = \yii\web\Response::FORMAT_HTML;
\Yii::$app->response->data = $ex->getData();
}
}
}
Now change your configurations for the PayPalRestApi component class in the common/config/main.php or frontend/config/main.php whichever you are using, to the new class you created
'components'=> [
...
'PayPalRestApi'=>[
'class'=>'common\components\PayPalRestApi',
]
...
]
so now you can get the same user id by using
$response = \yii\helpers\Json::decode( Yii::$app->PayPalRestApi->processPayment($params));
$user_id = $response['transactions'][0]['custom'];

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.

paypal success url error laravel

I'm using laravel Omni plugin for transactions. Once payment has been done , I'm getting error for success url.
public function checkOut(Request $request)
{
$params = array(
'cancelUrl' => 'http://localhost/vis/public/cancel_order',
'returnUrl' => 'http://localhost/vis/public/payment_success',
'name' => 'Meal',
'description' => 'Casper',
'amount' => '1.00',
'currency' => 'USD'
);
Session::put('params', $params);
Session::save();
$gateway = Omnipay::create('PayPal_Express');
$gateway->setUsername('un');
$gateway->setPassword('pwd');
$gateway->setSignature('signature');
$gateway->setTestMode(true);
$response = $gateway->purchase($params)->send();
if ($response->isSuccessful()) {
print_r($params);
redirect('payment_success/' . $this->orderNo);
// payment was successful: update database
print_r($response);
} elseif ($response->isRedirect()) {
// redirect to offsite payment gateway
$response->redirect();
} else {
// payment failed: display message to customer
echo $response->getMessage();
}
}
public function getSuccessPayment()
{
$gateway = Omnipay::create('PayPal_Express');
$gateway->setUsername('un');
$gateway->setPassword('pwd');
$gateway->setSignature('signature');
$gateway->setTestMode(true);
$params = Session::get('params');
$response = $gateway->completePurchase($params)->send();
$paypalResponse = $response->getData(); // this is the raw response object
if(isset($paypalResponse['PAYMENTINFO_0_ACK']) && $paypalResponse['PAYMENTINFO_0_ACK'] === 'Success') {
// Response
print_r($params);
// print_r($paypalResponse);
} else {
//Failed transaction
}
// return View('result');
print_r($params);
print_r($paypalResponse);
}
I'm getting following error
Not Found
HTTP Error 404. The requested resource is not found.
http://localhost/vis/public/payment_success?token=EC-1R845179Asss493N&PayerID=swdw3BS9REA4AN
It looks like you may have forgotten to add that route in the routes.php, Make sure you have something like this in routes.php
Route::get('/payment_success', 'StoreController#getSuccessPayment');
Change StoreController to the name of the controller this function is in.

Categories