I am using the stripe/stripe package to capture payment for single product. Everything is working as expected however when the user is returned to the order-confirmation page, I would like to get the stripe payment id. How would i achieve this?
Im not sure if i need a webhook and if i would, how would i use this?
public function onCharge() {
$user = Auth::getUser();
$course = CourseMeta::where('id', $this->param('id'))->first();
$stripe = new \Stripe\StripeClient(env('STRIPE_SECRET'));
$product = $stripe->products->create([
'name' => $course->course->name . ' - ' . $course->date,
]);
$price = $stripe->prices->create([
'unit_amount' => $course->price * 120,
'currency' => 'gbp',
'product' => $product->id,
]);
$validator = Validator::make(
[
'user_id' => $user->id,
'coursemeta_id' => $course->id,
'course_id' => $course->course->id,
'stripe_id' => '1',
],
[
'user_id' => 'required',
'coursemeta_id' => 'required',
'course_id' => 'required',
'stripe_id' => 'required'
]
);
if ($validator->fails()) {
return Redirect::back()->withErrors($validator);
} else {
$order = new Order();
$order->user_id = $user->id;
$order->coursemeta_id = $course->id;
$order->stripe_id = '1';
$order->company = request()->get('company');
$order->company_firstname = request()->get('company_firstname');
$order->company_lastname = request()->get('company_lastname');
$order->company_email = request()->get('company_email');
$order->company_phone = request()->get('company_phone');
$order->citb_levy = request()->get('citb_levy');
$order->d_firstname = request()->get('d_firstname');
$order->d_lastname = request()->get('d_lastname');
$order->d_email = request()->get('d_email');
$order->d_phone = request()->get('d_phone');
$order->d_dob = request()->get('d_dob');
$order->d_ninumber = request()->get('d_ninumber');
$order->save();
}
$portal = $stripe->checkout->sessions->create([
'success_url' => env('APP_URL') . '/order-confirmation'.'?' . 'user=' . $user->id . '&' . 'course=' . $course->id,
'cancel_url' => env('APP_URL') . '/cancel',
'line_items' => [
[
'price' => $price->id,
'quantity' => 1
],
],
'mode' => 'payment',
]);
return redirect($portal->url);
}
You need to use the checkout session ID.
when you create success_url and cancel_url you can also pass {CHECKOUT_SESSION_ID} param with curly braces. when payment gateway will redirect to one of those URLs it will automatically replace {CHECKOUT_SESSION_ID} with the actual session ID.
In your case
$portal = $stripe->checkout->sessions->create([
// HERE ---------------------------------------------------\/----------\/
'success_url' => env('APP_URL') . '/order-confirmation'.'?session_id={CHECKOUT_SESSION_ID}&' . 'user='. $user->id . '&' . 'course=' . $course->id,
'cancel_url' => env('APP_URL') . '/cancel',
'line_items' => [
[
'price' => $price->id,
'quantity' => 1
],
],
'mode' => 'payment',
]);
Now when this page is called you can have session ID and you can retrieve all stuff from it.
// on success or cancel page you can use this code to get infos
$stripe = new \Stripe\StripeClient(env('STRIPE_SECRET'));
$session = \Stripe\Checkout\Session::retrieve(get('session_id'));
$customer = \Stripe\Customer::retrieve($session->customer);
$paymentIntent = \Stripe\PaymentIntent::retrieve($session->payment_intent);
// from this $session you can get customer/items/paymentIntent etc..
ref : https://stripe.com/docs/payments/checkout/custom-success-page
if any doubt please comment.
Related
I just want to save my image or file in the database as a URL that can easily get for the frontend. I tried it a lot but did not get a solution if anyone can get me out with this?
public function addPPQuestion(Request $pp_questions)
{
$validate = Validator::make($pp_questions->all(), [
'qual_cat_id' => 'required|exists:qualification_categories,qual_cat_id',
'year_id' => 'required|exists:years,year_id',
'course_id' => 'required|exists:courses,course_id',
'board_id' => 'required|exists:board_of__edus,board_id',
'paper' => 'required|mimes:pdf|max:2048',
]);
if ($validate->fails()) {
$messages = $validate->errors()->count() > 1 ? $validate->errors()->all() : $validate->errors()->first();
return response()->json(['code' => 400, 'message' => $messages], 400);
} else {
$paper = $pp_questions->paper;
$fileName = $paper->getClientOriginalName();
$pp_question = pp_question_answer::create([
'paper' => $pp_questions->paper->storeAs('', $fileName, ''),
'qual_cat_id' => $pp_questions->input('qual_cat_id'),
'year_id' => $pp_questions->input('year_id'),
'course_id' => $pp_questions->input('course_id'),
'board_id' => $pp_questions->input('board_id'),
]);
return response()->json(['code' => 201, 'message' => 'Question Created Successfully',
'object' => $pp_question], 201);
}
}
Step 1: Validate the files as you want in the api.
Content-Type: application/json
It will return JSON data as result.
$request->validate(['file' => 'required|mimes:jpeg,jpg,png,gif,svg,pdf,txt,doc,docx,application/octet-stream,audio/mpeg,mpga,mp3,wav|max:204800']);
Step 2: Make a file name & store it in the folder and get the URL of it.
$unique_id = strtolower(str_replace('.', '', uniqid('', true)) . time());
$photoFile = $request->file('paper');
$extension = $photoFile->getClientOriginalExtension();
$fileNameToStore = $unique_id . '.' . $extension;
$filepath = $photoFile->storeAs('photos', $fileNameToStore);
$pp_question = Model::create([
'paper' => $filepath,
'qual_cat_id' => $pp_questions->input('qual_cat_id'),
'year_id' => $pp_questions->input('year_id'),
'course_id' => $pp_questions->input('course_id'),
'board_id' => $pp_questions->input('board_id'),
]);
return response()->json([
'code' => 201,
'message' => 'Question Created Successfully',
'object' => $pp_question
], 201);
Step 3: To display data on the front-end side.
$imagePath = !empty($pp_question->pdf) && Storage::exists($pp_question->pdf) ? Storage::url($pp_question->pdf) : asset(Storage::url('default/pdf.png');
i am new for laravel, i am not able to save the files in database on update function can any one help me for this,I have two related tables where one is a ticekt table and the other a one a documents table. In the documents table are the columns id, doc_name,doc_path,user_id and service_id. I'm trying to edit multiple images when editing a service. documents table not updating remaining things update successful
Cread service code
public function store(Request $request)
{
$rules = [
'email' => 'required|string|max:255',
'typeofservice' => 'required',
'companyname' => 'required',
'representative'=> 'required',
'phone' => 'required',
'services' => 'required',
'applicant' => 'required',
//'document' => 'required',
//'document.*' => 'required',
'remark' => 'required',
];
$validator = Validator::make($request->all(),$rules);
if($validator->fails()){
return back()->with('warning','please Fill manadatory fields');
} else {
//$dates = ;
//dd($dates);
$ticket = new Ticket([
'user_id' => Auth::user()->id,
'ticket_id' => strtoupper(str_random(10)),
'email'=>$request->input('email'),
'typeofservice' => $request->input('typeofservice'),
'companyname' => $request->input('companyname'),
'representative' => $request->input('representative'),
'phone' => $request->input('phone'),
'services' => $request->input('services'),
'applicant' => $request->input('applicant'),
'remark' => $request->input('remark'),
'ticket_submit_date' => date('d-M-Y'),
'status' => "1",
]);
//dd($ticket);
$ticket->save();
$userId = Auth::id();
$last_id = DB::getPdo()->lastInsertId();
if($ticket) {
if($request->hasfile('documents')) {
foreach($request->file('documents') as $doc)
{
$name = $doc->getClientOriginalName();
$destinationPath = 'public/documets/';
$documentPath = date('YmdHis') . "." . $doc->getClientOriginalExtension();
$doc->move($destinationPath, $documentPath);
Document::create([
'doc_name' => $name,
'doc_path' => $documentPath,
'user_id' => $userId,
'ser_id' => $last_id,
]);
}
}
//return $last_id;
$ticket_details = DB::table('ticket')->where('id','=',$last_id)->first();
$users = User::where('id','=',$ticket_details->user_id)->first();
$ticketid = $ticket_details->ticket_id;
$username = $users->first_name.' '.$users->last_name;
$mdata = ['ticketid'=>$ticketid,'name'=>$username];
$user['to']= $users->email;
Mail::send('emails.user_create_application',$mdata,function($message) use ($user){
$message->to($user['to']);
$message->subject('User Create Application');
});
return back()->with("success","Service Requiest Created Successfully! your tracking id:#$ticket->ticket_id" );
}
}
}
For uddate function given below
public function udateuserticket(Request $request, $id){
$rules = [
'email' => 'required|string|max:255',
'typeofservice' => 'required',
'companyname' => 'required',
'representative'=> 'required',
'phone' => 'required',
'services' => 'required',
'applicant' => 'required',
//'document' => 'required',
//'document.*' => 'required',
'remark' => 'required',
];
$email = $request->email;
$typeofservice = $request->typeofservice;
$companyname = $request->companyname;
$representative = $request->representative;
$phone = $request->phone;
$services = $request-> services;
$applicant = $request->applicant;
$remark = $request->remark;
$updateuserticket = Ticket::where('id','=',$id)->update([
'email' => $email,'typeofservice' =>$typeofservice, 'companyname' => $companyname, 'representative' => $representative,'phone' => $phone,'services' => $services, 'applicant' => $applicant, 'remark' => $remark ]);
$userId = Auth::id();
$last_id = DB::getPdo()->lastInsertId();
if($updateuserticket){
if($request->hasfile('documents')) {
foreach($request->file('documents') as $doc)
{
$name = $doc->getClientOriginalName();
$destinationPath = 'public/documets/';
if(File::exists($destinationPath)){
File::delete($destinationPath);
}
$documentPath = date('YmdHis') . "." . $doc->getClientOriginalExtension();
$doc->move($destinationPath, $documentPath);
Document::create([
'doc_name' => $name,
'doc_path' => $documentPath,
'user_id' => $userId,
'ser_id' => $last_id,
]);
}
}
$ticket_details = DB::table('ticket')->where('id','=',$last_id)->first();
//$users = User::where('id','=',$ticket_details->user_id)->first();
//$ticketid = $ticket_details->ticket_id;
//$username = $users->first_name.' '.$users->last_name;
return redirect('showtickets')->with('success','Ticket Updated Successfully!');
}
}
for view
#foreach( $documents as $doc )
<div class="col-md-6">
<input id="documents" type="file" class="form-control" name="documents[]" value="" required>
<img src="{{ url('/') }}/public/documets/{{ $doc->doc_path }}" alt="user-img" class="img-width" style="width:30px;height:30px;">
</div>
#endforeach
This one update only details not able to update documents can you please guid anyone where i am wrong
I've a table of building in which there is building name in db.when i add building through blade if the building name exist then it can not added. instead of storing it to db i want to show some error.what should i do?
this is my validation
$validator = Validator::make(
$request->all(),
[
'b_name' => 'required|max:20',
],
[
'b_name.required' => '*please fill this field',
]
);
if ($validator->fails()) {
return Response::make([
'message' => trans('validation_failed'),
'errors' => $validator->errors(),
]);
}
if ($validator->passes()) {
$name = $request->input('b_name');
$description = $request->input('b_description');
$created_at = Carbon::now();
$updated_at = Carbon::now();
$array = array('name' => $name, 'description' => $description, 'created_at' => $created_at, 'updated_at' => $updated_at);
Building::insert($array);
$validator = Validator::make(
$request->all(),
[
'b_name' => 'required|max:20|unique:buildings,name',
],
[
'b_name.required' => '*please fill this field',
'b_name.unique' => ('*building name already exists'),
]
);
if ($validator->fails()) {
return Response::make([
'message' => trans('validation_failed'),
'errors' => $validator->errors(),
]);
}
if ($validator->passes()) {
$name = $request->input('b_name');
$description = $request->input('b_description');
$created_at = Carbon::now();
$updated_at = Carbon::now();
$array = array('name' => $name, 'description' => $description, 'created_at' => $created_at, 'updated_at' => $updated_at);
Building::insert($array);
return 1;
}
Response::json(['errors' => $validator->errors()]);
}
If b_name is your input for building name and name is your database field name for Building model then try this code in your validation.
'b_name' => 'required|max:20|unique:App\Building,name'
For more details visit : https://laravel.com/docs/6.x/validation#rule-unique
Your code shoulde be like
$input = $request->all();
$rules = ['b_name' => 'required|required|unique:table_name,b_name|max:20'];
$messages = [
'b_name.required' => '*please fill this field'
'b_name.unique' => 'building name already taken.'
];
$validator = Validator::make($input, $rules, $messages);
I am having 2 methods. In one of the method I am making a call to database, a pure and simple one Document::findOrFail($data->id). But this is always returning me null although a record is already persisted. Any idea how to get this simple thing sorted?
public function lockExport(Request $request){
$document = Document::create([
'user_id' => $this->userId(),
'extension' => $extension,
'name' => $filename,
'file_path' => $filepath,
'size' => File::size($filepath . $filename),
'received_at' => Carbon::now()->format('Y-m-d')
]);
$isAttachment = false;
Cache::put($token, ['file' => $document->file_path . $document->name . '.' . $document->extension, 'is_attachment' => $isAttachment, 'id' => $document->id], 3);
return $this->downloadlockExport($token);
}
public function downloadlockExport($token)
{
try {
$data = (object) Cache::get($token);
// dd I get the full $data as object
$document = Document::findOrFail($data->id);
// undefined. Above query did not execute.
// Thus, below query failed
$document->update(['downloads' => $document->downloads + 1]);
$content = Crypt::decrypt(File::get($data->file));
return response()->make($content, 200, array(
'Content-Disposition' => 'attachment; filename="' . basename($data->file) . '"'
));
} catch (\Exception $e) {
\App::abort(404);
}
}
What you probably would like to do is:
public function lockExport(Request $request){
$document = Document::create([
'user_id' => $this->userId(),
'extension' => $extension,
'name' => $filename,
'file_path' => $filepath,
'size' => File::size($filepath . $filename),
'received_at' => Carbon::now()->format('Y-m-d')
]);
$isAttachment = false;
$token = 'mytoken';
Cache::put($token, ['file' => $document->file_path . $document->name . '.' . $document->extension, 'is_attachment' => $isAttachment, 'id' => $document->id], 3);
return $this->downloadlockExport($token);
}
This way you will get your $token in your called function and you will get the $data correctly as I see.
And in the downloadlockExport() function you will have the ID like this:
$document = Document::findOrFail($data->mytoken['id']);
or you can use:
$document = Document::findOrFail($data->$token['id']);
similar with getting the File value:
$content = Crypt::decrypt(File::get($data->$token['file']));
I'm new to laravel. I get the following error when uploading a file:
Call to a member function move() on null
$file = $request->file('img');
$destinationPath = base_path('\public\img');
$file->move($destinationPath . $file->getClientOriginalName());
$dealer = new Dealer([
'firstname' => $request->get('firstname'),
'lastname' => $request->get('lastname'),
'email' => $request->get('email'),
'phoneno' => $request->get('phoneno'),
'img' => $request->get('img'),
]);
Why dont You Try it like this ?
if ($request->hasFile('img')) {
$image = $request->file('img');
$teaser_image = time().'.'.$image->getClientOriginalExtension();
$destinationPath = public_path('/images');
$image->move($destinationPath, $img);
} else {
dd('Request Has No File');
}
and For Your Store :
$dialer = Dialer::create([
'firstname' => $request->get('firstname'),
'lastname' => $request->get('lastname'),
'email' => $request->get('email'),
'phoneno' => $request->get('phoneno'),
'img' => $request->get('img') ?? null,
]);
You Can remove ??null for making sure that you get The image And store it in database but You can Even place It To make it Optional for the User To insert img or not . hope this helps
EDIT
According to your comment i guess you may have 2 problems :
first one be sure that you have and input that named 'img' that sends the image and the secound is that be sure to add the multi enctype to your form so that form can send image like below :
enctype="multipart/form-data"
so your form should be like this :
<form action="someRoute" method="post" enctype="multipart/form-data">
if ($request->hasFile('img')) {
$image = $request->file('img');
// print_r($image);
$image_name = time().'.'.$image->getClientOriginalExtension();
// echo $image;
// exit(0);
$destinationPath = base_path('Uploads');
$image->move($destinationPath, $image_name);
$dealer = new Dealer([
'firstname' => $request->get('firstname'),
'lastname' => $request->get('lastname'),
'email' => $request->get('email'),
'phoneno' => $request->get('phoneno'),
'img' => $image_name,
]);
$dealer->save();
Session::flash('msg','Data Added successfully');
Session::flash('type','success');
return redirect('dealer-master');
// // echo $image;
// // exit(0);
// $destinationPath = base_path(' Uploads');
// $image->move($destinationPath, $image_name);
}
else {
Session::flash('msg','Please Check the data');
Session::flash('type','fail');
return redirect('dealer-master');
// echo $request;
}
I Findout my mistake This is working good Thank U Guys...!
It's work form me
if($request->img){
$fileName = time() . '.' . $request->img->extension();
$request->img->move(storage_path('app/public/img'), $fileName);
}
$dealer = new Dealer([
'firstname' => $request->get('firstname'),
'lastname' => $request->get('lastname'),
'email' => $request->get('email'),
'phoneno' => $request->get('phoneno'),
'img' => $fileName ?? null,
]);
$dealer->save();