PayPal Laravel 8 integration using srmklive error - php

I want to integrate PayPal into my Laravel website but I'm getting this error:
Argument 1 passed to Symfony\Component\HttpFoundation\RedirectResponse::__construct() must be of the type string, null given, called in C:\xampp\htdocs\Delta\vendor\laravel\framework\src\Illuminate\Routing\Redirector.php on line 233
Controller File
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Srmklive\PayPal\Services\ExpressCheckout;
class PayPalController extends Controller {
public function __construct() {
$this->provider = new ExpressCheckout();
}
public function payment() {
$data = [];
$data['items'] = [
[
'name' => 'codechief.org',
'price' => 100,
'desc' => 'Description goes herem',
'qty' => 1
]
];
$data['invoice_id'] = 1;
$data['invoice_description'] = "Order #{$data['invoice_id']} Invoice";
$data['return_url'] = route('payment.success');
$data['cancel_url'] = route('payment.cancel');
$data['total'] = 100;
$provider = new ExpressCheckout;
$response = $provider->setExpressCheckout($data);
$response = $provider->setExpressCheckout($data, true);
return redirect()->away($response['paypal_link']);
}
Please give me a solution!

Actually, your problem is that $response['paypal_link'] isn't returning a link. Replace line:
return redirect()->away($response['paypal_link']);
With the code below:
if($response['paypal_link'] == null){
// custom redirection
return redirect()->back()->with(['error'=>'paypal link no set'])
}
return redirect()->away($response['paypal_link']);
For more info visit laravel-paypal

Related

how to fix 500 internal server error in postman using laravel

service provider detail:
class ServiceProviderDetail extends Model {
protected $fillable = [
'working_status', 'booked', 'title', 'experience',
];
public function user()
{
return $this->belongsTo('App\User', 'user_id');
} }
add_booking:
class BookingController extends Controller {
public function addBooking(Request $request) {
//return $request;
$serviceman = ServiceProviderDetail::where('user_id', $request->service_provider_id)->first();
/********* Check if the serviceman is on duty ********/
if($serviceman->working_status !=1){
return response()->json([
'status'=> 0,
'message' => "Sorry pro has logged off duty",
'data' => []
], 200);
}
$serviceman->booked = '1';
if($request->input('subservice_id') == ''){
$service_id = $request->input('service_id');
} else {
$service_id = $request->input('subservice_id');
}
$booking = new Booking;
$booking->customer_id = $request->input('customer_id');
$booking->service_id = $service_id;
$booking->service_provider_id = $request->input('service_provider_id');
$booking->latitude = $request->input('latitude');
$booking->longitude = $request->input('longitude');
$booking->polyline = $request->input('polyline');
$booking->servicing_address = $request->input('servicing_address');
$booking->service_name = $request->input('service_name');
$booking->service_code = $request->input('service_code');
$booking->service_mobile = $request->input('service_mobile');
$booking->service_email = $request->input('service_email');
$booking->service_date = $request->input('service_date');
$booking->service_time = $request->input('service_time');
$booking->status = $request->input('status');
SendNotification::instance()->sendNotification('You have a new service request.',$booking->service_provider_id);
if($booking->save()) {
$serviceman->save();
return response()->json([
'status'=> 1,
'message' => 'Service booked successfully',
'data' => array(
$booking
),
], 200);
}
}
error_log:
emphasized textproduction.ERROR: Trying to get property 'working_status' of non-object {"exception":"[object] (ErrorException(code: 0): Trying to get property 'working_status' of non-object ...../BookingController.php:25)
[stacktrace]
$serviceman = ServiceProviderDetail::where('user_id', $request->service_provider_id)->first();
This is returning null. check if $serviceman is null before caling values

How can I redirect to the certain page when I clicked on my side-nav menu

I create a menu table and menu seeder inside my database. However when I tried to click on the company menu on my website it saying that $menu is undefined but when I tried to change to jobs.index(this the one which is working fine) for my route it works but it will goes to the job.blade.php not company.blade.php I do not know which part is wrong inside my code.
companycontroller.php
class CompanyController extends Controller
{
public function index()
{
$data = Company::latest()->paginate(5);
return view('company.index', compact('data'))
->with('i', (request()->input('page', 1) - 1) * 5);
}
public function insert_logo(Request $request)
{
$request->validate([
'company_logo' => 'required|image|max:2048',
'company_name' => 'required'
]);
$image_file = $request->company_logo;
$image = Company::make($image_file);
Response::make($image->encode('jpeg'));
$form_data = array(
'company_logo' => $image,
'company_name' => $request->company_name,
);
Company::create($form_data);
return redirect()->back();
}
public function fetch_logo($image_id)
{
$image = Company::findOrFail($image_id);
$image_file = Company::make($image->company_logo);
$response = Response::make($image_file->encode('jpeg'));
$response->header('Content-Type', 'image/jpeg');
return $response;
}

How to add my function and use it properly in controller?

I have 'sendsms' function which i used it in one of my controllers and worked fine. now what i need to know how i can make class reference of this code to use it in other controllers, instead of copy/paste whole code in all controllers.
In other Q/A they mentioned about only creating reference but i wanted to do it properly like using constructor or etc, not just doing things work, i want to do it like real-world project.
Here's the code in controller :
public function store(Request $request)
{
$this->validate($request,[
'title' => 'required|string|min:6',
'gametype' => 'required|string|min:3',
'description' => 'required|string|min:1|max:180',
'price' => 'required|numeric|min:4',
'buyyer_id' => 'required|numeric|min:1'
// 'seller_id' => 'required|numeric|min:1'
]);
// return RequestModel::create([
// 'title' => $request['title'],
// 'description' => $request['description'],
// 'gametype' => $request['gametype'],
// 'price' => $request['price'],
// 'buyyer_id' => $request['buyyer_id'],
// 'seller_id' => Auth::user()->id,
// ]);
//
$requestModel = new RequestModel;
// store
$requestModel->title = $request['title'];
$requestModel->description = $request['description'];
$requestModel->gametype = $request['gametype'];
$requestModel->price = $request['price'];
$requestModel->buyyer_id = $request['buyyer_id'];
$requestModel->seller_id = Auth::user()->id;
$requestModel->save();
return $this->sendSms($request['title'], $request['gametype']);
}
// I want to use this code in another class to use it in all controllers without copy/paste it.
function sendSms($reqid, $recgametype) {
//Send sms to getway
//implement later.
$otp_prefix = ':';
$response_type = 'json';
$textMSGATLAS = iconv("UTF-8", 'UTF-8//TRANSLIT',"req : ( " .$reqid. " ) for ( " .$recgametype. " ) submitted ");
ini_set("soap.wsdl_cache_enabled", "0");
try {
$client = new SoapClient("http://xxxx");
$user = "user";
$pass = "pass";
$fromNum = "+xxx";
$toNum = "+xxxx";
$messageContent = $textMSGATLAS;
$op = "send";
$client->SendSMS($fromNum,$toNum,$messageContent,$user,$pass,$op);
} catch (SoapFault $ex) {
echo $ex->faultstring;
}
}
I'm right now learning and I'm beginner at this so help to understand how to make it work properly. Thanks.
You can create a separate SMS class like :
<?php
namespace App;
class SMS {
private $reqid;
private $recgametype;
public function __construct($reqid, $recgametype)
{
$this->reqid = $reqid;
$this->recgametype = $recgametype;
}
public function send()
{
$otp_prefix = ':';
$response_type = 'json';
$textMSGATLAS = iconv("UTF-8", 'UTF-8//TRANSLIT',"req : ( " .$this->reqid. " ) for ( " .$this->recgametype. " ) submitted ");
ini_set("soap.wsdl_cache_enabled", "0");
try {
$client = new SoapClient("http://xxxx");
$user = "user";
$pass = "pass";
$fromNum = "+xxx";
$toNum = "+xxxx";
$messageContent = $textMSGATLAS;
$op = "send";
return $client->SendSMS($fromNum,$toNum,$messageContent,$user,$pass,$op);
} catch (SoapFault $ex) {
throw new \Exception('SMS sending failed')
}
}
}
And then inside controller or wherever you would need :
public function sendSms($reqid, $recgametype) {
$sms = new \App\SMS($reqid, $recgametype);
$sms->send();
}
You can also create custom exception like SMSSendingFailedException and throw it instead of standard \Exception inside send() function.
That will help you to send appropriate response in controller like :
public function sendSms($reqid, $recgametype) {
try{
$sms = new \App\SMS($reqid, $recgametype);
$sms->send();
return response()->json('message' => 'SMS sent successfully', 200);
}
catch(SMSSendingFailedException $e){
return response()->json('message' => 'SMS sending failed', 500);
}
}
Then to go one step further, you can use concept of laravel facade if you need it all over the project with a quick class alias.

Slim Payment controller

I followed a serie on creating a shopping cart on codecourse - and it was just what I was looking for.
In the series the payment happens on creating the order - but now my client says that they don't want the payment on creating order - first when they have processed the order - they want to send an email with payment or an link to a payment site.
I thought no big deal - just move the BraintreePayment par out of the create class - create a new class called payment and thats that - but no - so now I am stuck.
I am using swiftmailer to send the mail with the link and that works fine - but the payment part fails.
I am new to this MVC / Slim thing - so please can someone help me in the right direction.
The error it throws say:
Type: TypeError Message: Argument 1 passed to
Cart\Events\OrderWasCreated::__construct() must be an instance of
Cart\Models\Order, integer given, called in
/Applications/AMPPS/www/testshop.dev/cart/app/Controllers/OrderController.php
on line 160 File:
/Applications/AMPPS/www/testshop.dev/cart/app/Events/OrderWasCreated.php
Line: 17
My ordercontroller with the payment class - looks like this:
<?php
namespace Cart\Controllers;
use Slim\Router;
use Slim\Views\Twig;
use Cart\Basket\Basket;
use Cart\Models\Order;
use Cart\Models\Product;
use Cart\Models\Address;
use Cart\Models\Delivery;
use Cart\Models\Customer;
use Cart\Controllers\MailController;
use Cart\Validation\Contracts\ValidatorInterface;
use Cart\Validation\Forms\OrderForm;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Braintree_transaction;
class OrderController
{
protected $basket;
protected $mailcontroller;
protected $router;
protected $validator;
public function __construct(Basket $basket, Mailcontroller $mailcontroller, Router $router, ValidatorInterface $validator)
{
$this->basket = $basket;
$this->mailcontroller = $mailcontroller;
$this->router = $router;
$this->validator = $validator;
}
public function index(Request $request, Response $response, Twig $view)
{
$this->basket->refresh();
if (!$this->basket->subTotal()) {
return $response->withRedirect($this->router->pathFor('cart.index'));
}
return $view->render($response, 'order/index.twig');
}
public function show($hash, Request $request, Response $response, twig $view, Order $order)
{
$order = $order->with('address', 'products')->where('hash', $hash)->first();
$this->mailcontroller->mailLisbeth($hash);
if (!$order) {
return $response->withRedirect($this->router->pathFor('home'));
}
return $view->render($response, 'order/show.twig', [
'order' => $order,
]);
}
public function create(Request $request, Response $response, Customer $customer, Address $address, Delivery $delivery, Order $order)
{
$this->basket->refresh();
$validation = $this->validator->validate($request, OrderForm::rules());
if (!$this->basket->subTotal()) {
return $response->withRedirect($this->router->pathFor('cart.index'));
}
if ($validation->fails()) {
return $response->withRedirect($this->router->pathFor('order.index'));
}
$hash = bin2hex(random_bytes(32));
$customer = $customer->firstOrCreate([
'email' => $request->getParam('email'),
'name' => $request->getParam('name'),
]);
$delivery = $delivery->firstOrCreate([
'delivery' => $request->getParam('delivery'),
'deliverydate' => $request->getParam('deliverydate'),
'deliverytime' => $request->getParam('deliverytime'),
]);
$address = $address->firstOrCreate([
'address1' => $request->getParam('address1'),
'address2' => $request->getParam('address2'),
'city' => $request->getParam('city'),
'postal_code' => $request->getParam('postal_code'),
]);
$order = $customer->orders()->create([
'hash' => $hash,
'accepted' => "2",
'paid' => false,
'total' => $this->basket->subTotal() + 150,
]);
$address->order()->save($order);
$delivery->order()->save($order);
$allItems = $this->basket->all();
$order->products()->saveMany(
$allItems,
$this->getQuantities($allItems)
);
$event = new \Cart\Events\OrderWasCreated($order, $this->basket);
$event->attach([
// new \Cart\Handlers\MarkOrderPaid,
// new \Cart\Handlers\RecordSuccessfulPayment($result->transaction->id),
new \Cart\Handlers\UpdateStock,
new \Cart\Handlers\Emptybasket,
]);
$event->dispatch();
return $view->render($response, 'order/show.twig', [
'order' => $order,
]);
}
//
public function payment($slug, Request $request, Response $response, twig $view, Customer $customer, Address $address, Delivery $delivery, Order $order)
{
$order = $order->with('address', 'products')->where('id', $slug)->first();
// var_dump($order);
// die();
// if (!$request->getParam('payment_method_nonce')) {
// return $response->withRedirect($this->router->pathFor('order.index'));
// }
$order = $customer->orders()->update([
'paid' => true,
]);
$result = Braintree_Transaction::sale([
'amount' => $this->basket->subTotal() + 150,
'paymentMethodNonce' => $request->getParam('payment_method_nonce'),
'options' => [
'submitForSettlement' => true,
]
]);
$event = new \Cart\Events\OrderWasCreated($order, $this->basket);
if (!$result->success) {
$event->attach(new \Cart\Handlers\RecordFailedPayment);
$event->dispatch();
return $response->withRedirect($this->router->pathFor('order.index'));
}
$event->attach([
new \Cart\Handlers\MarkOrderPaid,
new \Cart\Handlers\RecordSuccessfulPayment($result->transaction->id),
// new \Cart\Handlers\UpdateStock,
// new \Cart\Handlers\Emptybasket,
]);
}
protected function getQuantities($items)
{
$quantities = [];
foreach ($items as $item) {
$quantities[] = ['quantity' => $item->quantity];
}
return $quantities;
}
}
The error occures on line 160:
$event = new \Cart\Events\OrderWasCreated($order, $this->basket);
because you invoke Cart\Events\OrderWasCreated constructor, which requires instance of Cart\Models\Order class as first argument. Instead your first argument ($order) is integer.
Now latest assignment of $order is on line 147:
$order = $customer->orders()->update([
'paid' => true,
]);
I'll have a guess and say that this is an operation that returns integer as result (be that a simple 1/0 success/fauilure or the id of the order being updated). Are you sure that you need that? Asking because:
You are assigning $order a value on line 138:
$order = $order->with('address', 'products')->where('id', $slug)->first();
And you're passing $order as an argument to the OrderController::payment.
So, my guess is: you want to remove lines 138 and 147.

CakePHP change DATABASE_CONFIG variables, based on user input for custom datasource

I am looking for a way to access and change the DATABASE_CONFIG variables, based on user input. Using CakePHP I created a custom datasource, based on the one provided in the docs, to access an external API. The API returns a JSON string containing the 12 most recent objects. I need to be able to change the page number in the API request to get the next 12 results, as well as accept a free text query entered by the user.
app/Config/Database.php
class DATABASE_CONFIG {
public $behance = array(
'datasource' => 'BehanceDatasource',
'api_key' => '123456789',
'page' => '1',
'text_query' => 'foo'
);
}
app/Model/Datasource/BehanceDataSource.php
App::uses('HttpSocket', 'Network/Http');
class BehanceDatasource extends DataSource {
public $description = 'Beehance datasource';
public $config = array(
'api_key' => '',
'page' => '',
'text_query' => ''
);
public function __construct($config) {
parent::__construct($config);
$this->Http = new HttpSocket();
}
public function listSources($data = null) {
return null;
}
public function describe($model) {
return $this->_schema;
}
public function calculate(Model $model, $func, $params = array()) {
return 'COUNT';
}
public function read(Model $model, $queryData = array(), $recursive = null) {
if ($queryData['fields'] === 'COUNT') {
return array(array(array('count' => 1)));
}
$queryData['conditions']['api_key'] = $this->config['api_key'];
$queryData['conditions']['page'] = $this->config['page'];
$queryData['conditions']['page'] = $this->config['text_query'];
$json = $this->Http->get('http://www.behance.net/v2/projects', $queryData['conditions']);
$res = json_decode($json, true);
if (is_null($res)) {
$error = json_last_error();
throw new CakeException($error);
}
return array($model->alias => $res);
}
}
Is there anyway to access and change the $behance array, or is there another way to go about accessing an external API with cakePHP that I am totally missing?

Categories