I have a problem about unusual return in my lumen app version 7.
My teammate who is using kotlin in his android try to execute my api with case task_id and id is correctly inputed, he always got
["success" => false, "message" => "File Bukan Milik Task", "status" => 400]
If he got that response, It shouldn't execute the code below, but the targeted file was deleted and file in my digital ocean space was also deleted so the code below the return was executed. And also, with case task_id and id correctly inputed, the above return was not supposed to be hit. But it was been hit and the below code also hit. In the mean time, every time i tried this api in postman, It worked normally. with output :
return ["success" => true, "message" => "Berhasil Menghapus File", "status" => 200];
This is my deleteFileTask function api code
public function deleteFileTask(Request $request)
{
try{
$task_id = $request->get('task_id', null);
$id = $request->get('id', null);
$task = Task::with('attachments')->find($task_id);
if($task === null) return ["success" => false, "message" => "Id Task Tidak Ditemukan", "status" => 400];
$search = $task->attachments->search(function ($item) use ($id) {
return $item->id == $id;
});
if($search === false) return ["success" => false, "message" => "File Bukan Milik Task", "status" => 400];
$fileService = new FileService;
$delete_file_response = $fileService->deleteFile($id);
if($delete_file_response['success']) return ["success" => true, "message" => "Berhasil Menghapus File", "status" => 200];
else return ["success" => false, "message" => $delete_file_response['message'], "status" => 400];
} catch(Exception $err){
return ["success" => false, "message" => $err, "status" => 400];
}
}
This is my deleteFile function in FileService class
public function deleteFile($id)
{
$file = File::find($id);
if($file === null) return ["success" => false, "message" => "File Tidak Ditemukan"];
$set_private = Storage::disk('do')->setVisibility($file->link, 'private');
if(!$set_private) return ["success" => false, "message" => "File Gagal Didelete dari Space"];
$file->delete();
$purge_response = $this->purgeLink($file->link);
if(!$purge_response) return ["success" => false, "message" => "Gagal Purge Data"];
return ["success" => true];
}
Anyone know what the cause is?
In laravel 9 with Inertiajs 3 I try to set flash_type when setting flash message in control :
return redirect(route('admin.dashboard.index'))
->with( 'flash', 'You have no access to currency listing')
->with('flash_type', 'error12');
In app/Http/Middleware/HandleInertiaRequests.php I added lines :
public function share(Request $request): array
{
\Log::info( varDump($request->session()->get('flash_type'), ' -1 HandleInertiaRequests $request->session()->get(\'flash_type\')::') ); // I SEE VALID 'error12' value
return array_merge(parent::share($request), [
'flash' => [
'message' => fn () => $request->session()->get('message')
],
'flash_type' => [
'message' => fn () => $request->session()->get('flash_type')
],
'auth' => function() {
$user = auth()->user();
But checking on client side I see that flash_type value not in this.$page.props.jetstream : https://prnt.sc/3PdFiF6Dzm7a
How to set flash_type corectly ?
Thanks !
really struggling to find the error where i missed. I am using Laravel (v8), Vue (v2) and Stripe(v3) for my e-commerce web-app. I implemented stripe in TEST mode successfully and it was working perfectly fine. And when I switched for live mode I am getting the following error: No such PaymentMethod: 'pm_1Yyl5xC4bpPAffpGV2p0ZL12'.
Front and backend scripts are as shown below.
async mounted(){
this.stripe = await loadStripe(process.env.MIX_STRIPE_KEY);
const elements = this.stripe.elements()
this.cardElement = elements.create('card', {
classes: {
base: 'bg-gray-100 rounded border border-gray-300 focus:border-indigo-500 text-base outline-none text-gray-700 p-3 leading-8 transition-colors duration-200 ease-in-out'
}
})
this.cardElement.mount('#card-element')
window.scrollTo(0, 0)
},
the method pay now method as follows:
async processPayment(){
//send the payment information to Laravel + Stripe
this.paymentProcessing = true
this.billingAddressValidations = {}
this.stripeErrors = null
const {paymentMethod, error} = await this.stripe.createPaymentMethod(
'card', this.cardElement, {
billing_details: {
name: this.card2.fullName,
},
}
)
if(error){
this.paymentProcessing = false
alert(error.message)
} else {
this.shippingAddress.payment_method_id = paymentMethod.id
this.shippingAddress.amount = this.cart.reduce((acc, item) => acc + this.itemPrice(item) * item.quantity, 0)
this.shippingAddress.cart = JSON.stringify(this.cart)
this.shippingAddress.isBillingAddress = this.isBillingAddress
this.shippingAddress.billingAddress = this.billingAddress
this.shippingAddress.orderDetails = this.orderDetails
const res = await this.apiCall('POST','/api/purchase', this.shippingAddress )
if(res.status === 200 || res.status === 201 ){
this.paymentProcessing = false
this.$store.commit('updateOrder', res.data)
await this.$store.dispatch('clearCart')
//this.orderConfirmation(response.data.transaction_id)
await this.$router.push({ name: 'order.summary' })
}
if(res.status === 206){
if(res.data.type === 'billing_address_error') {
this.billingAddressValidations = res.data
}
if(res.data.type === 'stripe_error') {
this.stripeErrors = res.data
}
this.paymentProcessing = false
}
}
},
and the Laravel/Cashier backend as follows:
public function purchase(Request $request)
{
$order_number = "JT2070215";
$user = User::firstOrCreate(
[
'email' => $request->input('email')
],
[
'password' => Hash::make(Str::random(12)),
'name' => $request->input('first_name') . ' ' . $request->input('last_name'),
'address' => $request->input('address'),
'city' => $request->input('city'),
'line2' => $request->input('line2'),
'zip_code' => $request->input('post_code'),
]
);
try {
$user->createOrGetStripeCustomer();
$user->addPaymentMethod($request->input('payment_method_id'));
$payment = $user->charge(
$request->input('amount'),
$request->input('payment_method_id'),[
'currency'=>'GBP',
'customer'=>$user->stripe_id
],
);
$payment = $payment->asStripePaymentIntent();
$order = $user->orders()
->create([
'transaction_id' => $payment->charges->data[0]->id,
'total' => $payment->charges->data[0]->amount,
'name' => $request->first_name." ".$request->last_name,
'email' => $request->email,
'address' => $request->address,
'city' => $request->city,
'country' => $request->country,
'post_code' => $request->postal_code,
'order_number'=>$order_number
]);
dispatch(new OrderConfirmationEmailJob($order->transaction_id));
return $order;
} catch (\Exception $e) {
return response()->json(['message' => $e->getMessage(), 'type'=>'stripe_error'], 206);
}
}
“No such...” errors are usually caused by either a mismatch in API keys (e.g. using a mixture of your test plus live keys) or by trying to access objects that exist on a different account (e.g. trying to perform an operation from your platform account on an object that was created on a connected account)
Hi you are trying to pass the payment_token used in creating the payment method. In order for you to get the id, you will need to retrieve it from the just created payment method.
So this should work.
$paymentMethod = $user->addPaymentMethod($request->input('payment_method_id'));
$paymentId = $paymentMethod->id // use this for the charge
Facing cURL Error: Operation timed out after 15001 milliseconds with 0 bytes received issues with Woocomerce API to create products.
I am using the Laravel package i.e https://github.com/Codexshaper/laravel-woocommerce
It was working fine and creating products but suddenly it stopped working and start throwing PHP errors.
Below are the method that I am using to create a book on Woocomerce from laravel Controller:
public function addProductToWC(Request $request)
{
set_time_limit(0);
$response = '';
if ($request->isMethod('post')){
if(!empty($request->get('book_id'))){
$book = Book::find($request->get('book_id'));
$coverImgPath = base_path('public/customize_book/'.Session::get('cover_image'));
if (file_exists($coverImgPath)) {
$imageurl = url('/public/customize_book/'.Session::get('cover_image'));
} else {
$imageurl = url('/images/'.$book->bookimage);
}
if(!empty($book->id)){
$data = [
'name' => $book->title,
'type' => 'simple',
'regular_price' => number_format($request->get('book_price')),
'description' => (!empty($book->description) ? $book->description :''),
'short_description' => 'Simple product short description.',
'categories' => [
[
'id' => 1
]
],
'images' => [
[
'src' => 'http://demo.woothemes.com/woocommerce/wp-content/uploads/sites/56/2013/06/T_2_front.jpg'
],
[
'src' => 'http://demo.woothemes.com/woocommerce/wp-content/uploads/sites/56/2013/06/T_2_back.jpg'
]
]
];
$product = Product::create($data);
if($product['id']){
$response = array('error' => false,'code' => '200', 'data' => array('product_id' => $product['id'], 'message' => 'Product created successfully.'));
}else{
$response = array('error' => true,'code' => '401', 'data' => array('product_id' => $product['id'], 'message' => 'Product syncing failed please try again later.'));
}
}else{
$response = array('error' => true,'code' => '401','message' => 'Invalid book detail please try again.');
}
}else{
$response = array('error' => true,'code' => '401','message' => 'Invalid book detail please try again.');
}
}else{
$response = array('error' => true,'code' => '401','message' => 'Invalid method please try again.');
}
// return response
return response()->json($response);
}
Looking at the composer.json at https://github.com/Codexshaper/laravel-woocommerce/blob/master/composer.json, I can see that they are using the woocommerce client "automattic/woocommerce": "^3.0" This defaults to a request timeout of 15 seconds, hence why set_time_limit(0); didn't fix the issue.
When using it directly you'd set the timeout in the options
$woocommerce = new Client(
env('MGF_WOOCOMMERCE_API_URL'), // Your store URL
env('MGF_WOOCOMMERCE_API_KEY'), // Your consumer key
env('MGF_WOOCOMMERCE_API_SECRET'), // Your consumer secret
[
'timeout' => 120, // SET TIMOUT HERE
'wp_api' => true, // Enable the WP REST API integration
'version' => 'wc/v3' // WooCommerce WP REST API version
]
);
Looking at the library source https://github.com/Codexshaper/laravel-woocommerce/blob/master/src/WooCommerceApi.php
$this->client = new Client(
config('woocommerce.store_url'),
config('woocommerce.consumer_key'),
config('woocommerce.consumer_secret'),
[
'version' => 'wc/'.config('woocommerce.api_version'),
'wp_api' => config('woocommerce.wp_api_integration'),
'verify_ssl' => config('woocommerce.verify_ssl'),
'query_string_auth' => config('woocommerce.query_string_auth'),
'timeout' => config('woocommerce.timeout'),
]
);
It looks like the timeout is coming from woocommerce.timeout in your Laravel config file.
For testing reasons, I want to make the following Post Request with the Laravel HTTP Client:
$test = Http::post(route('users.leads.store', ['user' => $user->id]), [
"company_name" => "TESTCOMPANY",
"zip" => "49685",
"city" => "BÜHREN",
"street" => "MÜHLENKAMP 3",
"contact_name" => "FABIANLUKASSEN",
"phone1" => "017691443785",
"email" => "FABIANLUKASSEN#TESTEN.DE",
"website" => "www.fabianlukassen.de",
"category" => "Hotel",
"closed_until" => now(),
"appointment_end" => now()->addDays(1),
"appointment_comment" => "HALLO ICH BIN FABIAN",
"additional_contacts" => "",
"phone2" => "",
"sub_category" => "",
"expert_status" => 0
]);
I know that the route is working just fine. However, with debugging in phpStorm, I can see that the $test variable contains a 419 error (unknown status). Does anyone know what's wrong?
(I'm using laravel 8)
I agree with #ElektaKode that the issue is likely due to lack of csrf token.
In order to disable CSRF middleware while testing,
switch off CSRF token for this route at /app/Http/Midddleware/VerifyCsrfToken.php, by updating:
protected $except = [ 'your-route-url' ];
Then you can use api authentication to follow it up.
The simplest way to use api authentication, follow this doc,
The other ways are either using Laravel passport or using jwt for api.(both will consume more time to set up, as you are using for testing using api authentication is your go to method.)
Usually in Laravel, 419 Page Expired error comes from CSRF middleware meaning there was a failure while validating CSRF token. Add your CSRF token to your test request or consider disabling CSRF middleware while testing.
Post Request with Laravels HTTP Client
$test = Http::post(route('users.leads.store', ['user' => $user->id]), [
"company_name" => "TESTCOMPANY",
"place_id" => null,
"street" => "MÜHLENKAMP 3",
"zip" => "49685",
"city" => "BÜHREN",
"title" => null,
"contact_name" => "FABIANLUKASSEN",
"additional_contacts" => null,
"phone1" => "+49 163 3006603",
"phone2" => null,
"email" => "FABIANLUKASSEN#TESTEN.DE",
"category" => "Hotel",
"sub_category" => null,
"website" => "www.fabianlukassen.de",
"status" => 1,
"expert_status" => 0,
"coordinates" => null,
"expert_id" => 1,
"agent_id" => null,
"blocked" => 0,
"important_note" => null,
]);
Route
Route::apiResource('users.leads', UserLeadController::class);
Store Method in the UserLeadController
public function store(User $user, CreateLeadRequest $request)
{
//TODO: Relocate validation to request class
if(!UserLeadController::isPhone("test", $request->phone1)) {
abort(400, "Keine gültige Telefonnummer!");
return;
}
if(!UserLeadController::isPhoneNumberUnique("test", $request->phone1)) {
abort(400, "Die Telefonnummer existiert bereits!");
return;
}
/**
* The logged in User
* #var User $agent
*/
$agent = Auth::user();
$phoneUtil = PhoneNumberUtil::getInstance();
$lead = new Lead();
$lead->fill($request->except(['appointment_end', 'appointment_comment']));
// Leads created by experts will be blocked
if ($user->id === $agent->id) {
$lead->blocked = true;
}
$numberProto = $phoneUtil->parse($lead->phone1, 'DE');
$lead->phone1 = $phoneUtil->format($numberProto, PhoneNumberFormat::INTERNATIONAL);
try {
$lead->save();
} catch (QueryException $e) {
//$message = 'Lead besteht bereits.';
//return Response::json(['errors' => $message], 422);
abort(422, "Lead besteht bereits!");
return;
}
if ($request->closed_until) {
$lead->closed_until = Carbon::create($request->closed_until);
$event_end = $request->appointment_end
? Carbon::parse($request->appointment_end)
: Carbon::parse($request->closed_until)->addMinutes(90);
$lead->calendarEvents()->save(new CalendarEvent([
'body' => $request->appointment_comment ?? "Wurde von {$this->roleDescriptor($agent->roles)}" . $agent->name . " angelegt.",
'type' => CalendarEventType::CALLCENTER_APPOINTMENT,
'event_begin' => $lead->closed_until,
'event_end' => $event_end,
]));
$lead->status = LeadState::APPOINTMENT;
$lead->expert_status = LeadExpertAcceptance::ACCEPTED;
} else {
$lead->status = LeadState::OPEN;
}
if (isset($request->agent)) {
$lead->agent_id = $request->agent;
}
try {
$user->leads()->save($lead);
$lead->comments()->save(new Comment([
'body' => "Wurde von {$this->roleDescriptor($agent->roles)}" . $agent->name . " angelegt.",
'user_id' => $agent->id,
'commentable_type' => 'lead',
'commentable_id' => $lead->id,
'reason' => 'CREATED',
'date' => now('Europe/Berlin'),
]));
if ($request->closed_until) {
$lead->comments()->save(new Comment([
'body' => "Termin wurde von {$this->roleDescriptor($agent->roles)}" . $agent->name . " vereinbart.",
'user_id' => $agent->id,
'commentable_type' => 'lead',
'commentable_id' => $lead->id,
'reason' => 'APPOINTMENT',
'date' => now('Europe/Berlin')->addMinute(),
]));
}
} catch (QueryException $e) {
//not sure if this works
$message = $e->getMessage();
abort(400, $message);
return;
}
if (empty($message)) {
return Response::json(['message' => 'Lead saved', 'lead' => new LeadSingleResource($lead)]);
} else {
return Response::json(compact('message'), 500);
}
}
//TODO: relocate function to rule object
protected static function isPhoneNumberUnique($attribute, $value) {
$withSpace = PhoneFormatter::formatInternational($value);
$withoutSpace = preg_replace('/ /', '', $withSpace);
$protos = [$withSpace, $withoutSpace]; // Necessary because legacy (25.06.2020).
$booleanTest = Company::query()->whereIn('phone', $protos)->doesntExist()
|| Lead::query()->whereIn('phone1', $protos)->orWhereIn('phone2', $protos)->doesntExist();
return $booleanTest;
}
//TODO: relocate function to rule object
protected static function isPhone($attribute, $value) {
if (!$value) {
return false;
}
$phoneUtil = \libphonenumber\PhoneNumberUtil::getInstance();
$test = $phoneUtil->isValidNumber($phoneUtil->parse($value, 'DE'));
return $test;
}
fillable variable in the Lead Model
protected $fillable = [
'company_name',
'place_id',
'street',
'zip',
'city',
'title',
'contact_name',
'additional_contacts',
'phone1',
'phone2',
'email',
'category',
'sub_category',
'website',
'status',
'expert_status',
'coordinates',
'expert_id',
'agent_id',
'blocked',
'important_note'
];
As mentioned before, I receive a 200 OK status. Also, in a Vue.js component, I have done the following axios post request, which also just works fine.
axios
.post(`/api/users/${this.user_id}/leads`, {
"company_name": this.companyName,
"zip": this.zipCode,
"city": this.city,
"street": this.streetAndHouseNumber,
"contact_name": this.contactPartner,
"phone1": this.contactPartnerPhoneNumber,
"email": this.contactPartnerEmail,
"website": this.website,
"category": this.category,
"closed_until": this.appointmentStart,
"appointment_end": this.appointmentEnd,
"appointment_comment": this.comment,
//not used but needed (don't know the purpose)
"additional_contacts": "",
"phone2": "",
"sub_category": "",
"expert_status":this.expert_status,
}).then(() => {
window.location.href = this.routeSuccess;
}).catch((error) => {
this.showErrorAlert = true;
this.errorAlertMessage = error.response.data.message;
});
}