How to pass variables to view from controller in Laravel - php

When user place his order it redirects him to another page which check if he made his payment or no. Now The controller is ready and I need to initialize the box which make this and I need to took some variables.. I don't know how to implement this into payment.blade.php. This is what I tried and doesn't seems to work.
This is the controller
public function paymentView( $orderId, $userId ) {
$order = Session::all();
$order = Order::where('order_id', $orderId)->first();
if (!$order) {
App::abort(404);
}
$userID = $order['user_id'];
$orderID = $order['order_id'];
$options = array(
...
);
// 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
{
if (!$box->is_processed())
{
$message = "Thank you for order (order #".$orderID.", payment #".$box->payment_id()."). We will send soon";
$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);
return View::make('site.cart.payment', [
'order' => $order,
]);
}
Now I'm trying to put this in my view
#section('content')
#foreach($order->getOrderData(true) as $productId => $item)
<?php if (!$box->is_paid()) echo "<h2>Pay Invoice Now - </h2>"; else echo "<br><br>"; ?>
<?php echo $box->display_cryptobox(true, 580, 230); ?>
#endforeach
#endsection
When I run the page I've got error that box isn't defined.. How can I take this info in the view?

In the same way you've passed $order to the view. Replace the return at the bottom of you method with this return.
return View::make('site.cart.payment', [
'order' => $order,
'box' => $box
]);
The second argument passed to View::make() is an array of data that should be made available to the view.

Related

Laravel: Mollie - webhook failed with status code 500

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"
*/
}
}

Check if data exist in database using codeigniter

I have a scenario where i have 2 tables i.e users and request and i am asking the user to fill a form, in which along with other data he has to fill email also. Now i want that if the user enters an email it should simply add the data in users table and pick the last insert id and then go ahead and save the data+last inserted id in request table and display the message
Your account is created..
Till here i have done the coding, but the part where i am stuck is
I want that if the user enters an email that is already present in users table then the code should pick the id that is present against that email and store it along with form data in the request table and display the message
"Request is submitted but you already have an account, please login to
check furthur details "
users table
id name email
1 sam sam#gmail.com
2 demo_user demo#gmail.com
request table
id email userid
1 demo#gmail 2
Controller
public function submit()
{
$this->form_validation->set_rules('email','Email','trim|required');
if($this->form_validation->run() == FALSE)
{
$erdata = array
(
'error' => validation_errors()
);
$this->session->set_flashdata($erdata);
redirect('home/index');
}
else
{
if($this->user_model->instant_submit())
{
$this->session->set_flashdata('msg','Your account is created');
}
else
{
echo "failed";
}
redirect('home/index');
}
}
Model
public function instant_submit()
{
$userdata = array(
'email' => $this->input->post('email')
);
$insert_data = $this->db->insert('users', $userdata);
$lastid = $this->db->insert_id();
$reqdata = array(
'email' => $this->input->post('email'),
'userid' => $lastid,
'status'=>'pending'
);
$insert_request = $this->db->insert('request', $reqdata);
return $insert_data;
}
View
<?php if($this->session->flashdata('msg')): ?>
<?php echo $this->session->flashdata('msg'); ?>
<?php endif; ?>
<?php
$reg_attributes = array('id'=>'form','role'=>"form");
echo form_open('home/submit', $reg_attributes);
?>
<?php
$data = array(
'type'=>'text',
'name'=>'email',
'placeholder'=>'Email',
'class'=>'form-control',
'id'=>'form-email'
);
echo form_input($data);
?>
<?php
$data = array(
'type'=>'submit',
'class'=>'btn-primary',
'name'=>'submit',
'content'=>'Submit!'
);
echo form_button($data);
?>
<?php echo form_close(); ?>
is_unique Returns FALSE if the form element is not unique to the table and field name in the parameter.
Syntax :
is_unique[table.field]
Example :
$this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[users.email]');
This will solve your problem
In your controller before you call this $this->user_model->instant_submit() add one more condition to check if email id already exist or not like below.
Controller
public function submit()
{
$this->form_validation->set_rules('email','Email','trim|required');
if($this->form_validation->run() == FALSE)
{
$erdata = array
(
'error' => validation_errors()
);
$this->session->set_flashdata($erdata);
redirect('home/index');
}
else
{
if(!$this->user_model->check_user_exist($this->input->post('email'))) {
if($this->user_model->instant_submit())
{
$this->session->set_flashdata('msg','Your account is created');
}
else
{
echo "failed";
}
} else {
//do whatever operation you want to do if user is already exist;
$this->session->set_flashdata('msg','Request is submitted but you already have an account, please login to check furthur details ');
}
redirect('home/index');
}
}
Now in your model create a function which can check the data of user
public function check_user_exist($email_id) {
$this->db->select('id');
$this->db->where('email',$email_id);
$query = $this->db->get('users');
$data = $query->row();
if($query->num_rows() == 1) {
return $data->id;
} else {
return false;
}
}
Note : Remember it will send false if user not found so it will create a new entry of that user.

how to validate duplicate email in magento admin on edit and add in custom module

I need to validate duplicate email in magento on edit and add action. Basically on edit if i changed email id if that is available in database then i need to got message duplicate email.... if I add then i also want to validate duplicate email in magento.
my save function in admin
public function saveAction()
{
if ($this->getRequest()->getPost())
{
try {
$postData = $this->getRequest()->getPost();
$currentTimestamp = time();
$postData['updated_at']= $currentTimestamp;
$postData['seller_other_sale_sites'] = implode(',',$postData['seller_other_sale_sites']);
$sellerModel = Mage::getModel('seller/seller');
if( $this->getRequest()->getParam('id') <= 0 )
$sellerModel->setCreatedTime(
Mage::getSingleton('core/date')
->gmtDate()
);
$sellerModel
->addData($postData)
->setUpdateTime(
Mage::getSingleton('core/date')
->gmtDate())
->setId($this->getRequest()->getParam('id'))
->save();
Mage::getSingleton('adminhtml/session')
->addSuccess('successfully saved');
Mage::getSingleton('adminhtml/session')
->settestData(false);
$this->_redirect('*/*/');
return;
} catch (Exception $e){
Mage::getSingleton('adminhtml/session')
->addError($e->getMessage());
Mage::getSingleton('adminhtml/session')
->settestData($this->getRequest()
->getPost()
);
$this->_redirect('*/*/edit',
array('id' => $this->getRequest()
->getParam('id')));
return;
}
}
$this->_redirect('*/*/');
}
I need to validate that on save function
Create a function in helper class that takes $email as parameter
public function customerExists($email, $websiteId = null)
{
$customer = Mage::getModel('customer/customer');
$customer->setWebsiteId($websiteId);
$customer->loadByEmail($email);
if ($customer->getId()) {
return $customer;
}
return false;
}
Before you perform save operation, use the helper function this way.
Mage::helper('modulename')->customerExists($email, $websiteId);
If a customer is already there it will return the customer object and if it doesn't, it will return false. So you can write remaining code/throw exception/ set error message accordingly.
from Mage_Customer_Model_Resource_Customer this code checks for unique email _beforeSave before save (unless updating an existing customer in which case it checks for duplicates on just that customer).
This is within the Mage system, but doesn't use any models.
$adapter = $this->_getWriteAdapter();
$bind = array('email' => $customer->getEmail());
$select = $adapter->select()
->from($this->getEntityTable(), array($this->getEntityIdField()))
->where('email = :email');
if ($customer->getSharingConfig()->isWebsiteScope()) {
$bind['website_id'] = (int)$customer->getWebsiteId();
$select->where('website_id = :website_id');
}
if ($customer->getId()) {
$bind['entity_id'] = (int)$customer->getId();
$select->where('entity_id != :entity_id');
}
$result = $adapter->fetchOne($select, $bind);
if ($result) {
throw Mage::exception(
'Mage_Customer', Mage::helper('customer')->__('This customer email already exists'),
Mage_Customer_Model_Customer::EXCEPTION_EMAIL_EXISTS
);
}

One line way to find an attribute - Yii

I've recently been using the controller to pass in a couple of values into my view. In my controller this is what it looks like when I pass in values from the controller to the view.
public function actionProcessPayment($id)
{
// if the account id was passed in
if(isset($_POST['listF']))
{
$account_id = $_POST['listF'];
// total due before payment
$totaldue = Recipient::model()->totaldue($id);
$result = Recipient::model()->MakePayment($id, $account_id);
if($result == 'not enough money')
{
Yii::app()->user->setFlash('not enough money', "This account does not have enough money
to make that transaction!");
$this->redirect(array('recipient/index', 'id' => $id));
}
else
$this->render('paysummary',array(
'id'=>$id,
'totaldue'=>$totaldue,
'numpeople'=>Paylist::model()->NumIndv($id),
'user_id'=>Login::model()->getUserId(),
'accountname'=>Account::model()->AccountName($account_id),
'accountbalance'=>Account::model()->AccountBalance($account_id),
''
));
}
Now, in order to get the account name (for example), I've created a function in the model called AccountName that takes in the account id as a parameter.
Like so
public function AccountName($id)
{
$model = Account::model()->findByPk($id);
return $name = $model->name;
}
This is working fine, but I feel like I am programming in a very roundabout way. Is there a way to change this to be one line of code? Is this how it should be called in the controller?
public function actionProcessPayment($id)
{
// if the account id was passed in
if(isset($_POST['listF']))
{
$account_id = $_POST['listF'];
// total due before payment
$totaldue = Recipient::model()->totaldue($id);
$result = Recipient::model()->MakePayment($id, $account_id);
$model = Account::model()->findByPk( $account_id );// <<---
if($result == 'not enough money')
{
Yii::app()->user->setFlash('not enough money', "This account does not have enough money
to make that transaction!");
$this->redirect(array('recipient/index', 'id' => $id));
}
else
$this->render('paysummary',array(
'id'=>$id,
'totaldue'=>$totaldue,
'numpeople'=>Paylist::model()->NumIndv($id),
'user_id'=>Login::model()->getUserId(),
'accountname'=>$model->name,// <<---
'accountbalance'=>$model->balance, // <<---
''
));
}
You can simply pass model to view as a param:
$account = Account::model()->findByPk($account_id);
$this->render('paysummary',array(
'id'=>$id,
'totaldue'=>$totaldue,
'numpeople'=>Paylist::model()->NumIndv($id),
'user_id'=>Login::model()->getUserId(),
'account'=>$account,
''
));
Then in the view:
<?php echo $account->name; ?>

why coinbase callback url not working?

i have the below code for button creation.
public function createButton($name, $price, $currency, $custom=null, $options=array(),$callback)
{
// $callback=$this->generateReceiveAddress("http://www.tgigo.com");
// print_r($callback);exit;
$params = array(
"name" => $name,
"price_string" => $price,
"price_currency_iso" => $currency,
"callback_url"=>"http://www.tgigo.com"
);
if($custom !== null) {
$params['custom'] = $custom;
}
foreach($options as $option => $value) {
$params[$option] = $value;
}
return $this->createButtonWithOptions($params);
}
public function createButtonWithOptions($options=array())
{
$response = $this->post("buttons", array( "button" => $options ));
if(!$response->success) {
return $response;
}
$returnValue = new stdClass();
$returnValue->button = $response->button;
$returnValue->embedHtml = "<div class=\"coinbase-button\" data-code=\"" . $response->button->code . "\"></div><script src=\"https://coinbase.com/assets/button.js\" type=\"text/javascript\"></script>";
$returnValue->success = true;
return $returnValue;
}
and i have the below response for above code.
{"success":true,"button":{"code":"675cda22e31b314db557f0538f8ad27e","type":"buy_now","style":"buy_now_large","text":"Pay With Bitcoin","name":"Your Order #1234","description":"1 widget at $100","custom":"my custom tracking code for this order","callback_url":"http://www.tgigo.com","price":{"cents":100000,"currency_iso":"BTC"}}}
using this code payment process completed,but not redirected to the call back url.
any one please help me.
Thanks in advance :)
The callback_url parameter is for a callback that receives a POST request behind the scenes when payment is complete. The user's browser is not redirected there. You probably want success_url.
https://coinbase.com/api/doc/1.0/buttons/create.html

Categories