First time I've ever posted here for laravel help! I'm trying to get Broadcast events working on Laravel 5.4 with pusher
When I set the broadcast driver to 'log' I am successfully getting the details in the log so I know most things are working. However its the broadcasting that is the issue. When i set things to pusher I am getting a 404 File not found exception
BroadcastException
404 NOT FOUND
in PusherBroadcaster.php (line 106)
I have
"pusher/pusher-php-server": "^2.6",
in the composer.json
and all the keys etc are in the .env file
The method being called in PusherBroadcaster.php is
` public function broadcast(array $channels, $event, array $payload = [])
{
$socket = Arr::pull($payload, 'socket');
$response = $this->pusher->trigger(
$this->formatChannels($channels), $event, $payload, $socket, true
);
if ((is_array($response) && $response['status'] >= 200 && $response['status'] <= 299)
|| $response === true) {
return;
}
throw new BroadcastException(
is_bool($response) ? 'Failed to connect to Pusher.' : $response['body']
);
}`
and its the response['body'] which has the "404 FILE NOT FOUND" response so it looks like its something to do with connecting to pusher
This is my first broadcast with pusher so Im a newb as far as this is concerned.
Help ;-)
Related
I am adding CcAvenue gateway in laravel 5.3 on PHP 7.2, everything working fine till the payment page of CcAvenue, but after payment is done or payment canceled by the user, the return response URL is showing the following error
"Oops! An Error Occurred
The server returned a "405 Method Not Allowed".
Something is broken. Please let us know what you were doing when this error occurred. We will fix it as soon as possible. Sorry for any inconvenience caused."
My return URL is this: https:// www.domainname.com/booking/cancel/cc_checkout_gateway?c=f4b7d25d6e894a44725fff59adafcf82
Code in the Routes file
use Illuminate\Support\Facades\Route;
// Booking
Route::group(['prefix'=>config('booking.booking_route_prefix')],function(){
Route::post('/addToCart','BookingController#addToCart');
Route::post('/doCheckout','BookingController#doCheckout')->name('booking.doCheckout');
Route::get('/confirm/{gateway}','BookingController#confirmPayment');
Route::get('/cancel/{gateway}','BookingController#cancelPayment');
Route::get('/{code}','BookingController#detail');
Route::get('/{code}/checkout','BookingController#checkout');
Route::get('/{code}/check-status','BookingController#checkStatusCheckout');
//ical
Route::get('/export-ical/{type}/{id}','BookingController#exportIcal')->name('booking.admin.export-ical');
//inquiry
Route::post('/addEnquiry','BookingController#addEnquiry');
});
Route::group(['prefix'=>'gateway'],function(){
Route::get('/confirm/{gateway}','NormalCheckoutController#confirmPayment')->name('gateway.confirm');
Route::get('/cancel/{gateway}','NormalCheckoutController#cancelPayment')->name('gateway.cancel');
Route::get('/info','NormalCheckoutController#showInfo')->name('gateway.info');
});
Code in BookingController.php
public function cancelPayment(Request $request, $gateway)
{
$gateways = get_payment_gateways();
if (empty($gateways[$gateway]) or !class_exists($gateways[$gateway])) {
return $this->sendError(__("Payment gateway not found"));
}
$gatewayObj = new $gateways[$gateway]($gateway);
if (!$gatewayObj->isAvailable()) {
return $this->sendError(__("Payment gateway is not available"));
}
return $gatewayObj->cancelPayment($request);
}
Code in Gateway CcCheckoutGateway.php
public function cancelPayment(Request $request)
{
$c = $request->query('c');
$booking = Booking::where('code', $c)->first();
if (!empty($booking) and in_array($booking->status, [$booking::UNPAID])) {
$payment = $booking->payment;
if ($payment) {
$payment->status = 'cancel';
$payment->logs = \GuzzleHttp\json_encode([
'customer_cancel' => 1
]);
$payment->save();
// Refund without check status
$booking->tryRefundToWallet(false);
}
return redirect($booking->getDetailUrl())->with("error", __("You cancelled the payment"));
}
if (!empty($booking)) {
return redirect($booking->getDetailUrl());
} else {
return redirect(url('/'));
}
}
After too much R&D I found that my routes code is allowing method is GET & HEAD, but Ccavenue response URL is sending the response in POST method
I have tried every possible solution changed
Route::get('/cancel/{gateway}','BookingController#cancelPayment');
to
Route::post('/cancel/{gateway}','BookingController#cancelPayment');
and
Route::any('/cancel/{gateway}','BookingController#cancelPayment');
but after that it showing error 419: page expired
Please tell me how can I resolve the above issue.
I've been searching for this for hours, I hope someone here can help.
I built a subscription based site on Laravel and PayPal subscriptions using the PayPal PHP SDK.
Everything works perfectly except on thing:
I created a webhook for when a user cancels the payment on his end. I'm getting this error:
Got Http response code 400 when accessing https://api.sandbox.paypal.com/v1/notifications/verify-webhook-signature.{"name":"VALIDATION_ERROR","message":"Invalid data provided","debug_id":"7225cebfec35a","information_link":"https://developer.paypal.com/docs/api/webhooks/#errors","details":[{"field":"webhook_id","location":"body","issue":"Required field cannot be blank"}],"links":[]}
Here is my code:
public function webhook()
{
/**
* Receive the entire body that you received from PayPal webhook.
*/
$bodyReceived = file_get_contents('php://input');
// Receive HTTP headers that you received from PayPal webhook.
$headers = getallheaders();
/**
* Uppercase all the headers for consistency
*/
$headers = array_change_key_case($headers, CASE_UPPER);
$signatureVerification = new \PayPal\Api\VerifyWebhookSignature();
$signatureVerification->setWebhookId(env('PAYPAL_WEBHOOK_ID'));
$signatureVerification->setAuthAlgo($headers['PAYPAL-AUTH-ALGO']);
$signatureVerification->setTransmissionId($headers['PAYPAL-TRANSMISSION-ID']);
$signatureVerification->setCertUrl($headers['PAYPAL-CERT-URL']);
$signatureVerification->setTransmissionSig($headers['PAYPAL-TRANSMISSION-SIG']);
$signatureVerification->setTransmissionTime($headers['PAYPAL-TRANSMISSION-TIME']);
$webhookEvent = new \PayPal\Api\WebhookEvent();
$webhookEvent->fromJson($bodyReceived);
$signatureVerification->setWebhookEvent($webhookEvent);
$request = clone $signatureVerification;
try {
$output = $signatureVerification->post($this->apiContext);
} catch(\Exception $ex) {
//This is where it fails
print_r($ex->getMessage());
exit(1);
}
$verificationStatus = $output->getVerificationStatus();
$responseArray = json_decode($request->toJSON(), true);
$event = $responseArray['webhook_event']['event_type'];
if ($verificationStatus == 'SUCCESS')
{
switch($event)
{
case 'BILLING.SUBSCRIPTION.CANCELLED':
case 'BILLING.SUBSCRIPTION.SUSPENDED':
case 'BILLING.SUBSCRIPTION.EXPIRED':
case 'BILLING_AGREEMENTS.AGREEMENT.CANCELLED':
// $user = User::where('payer_id',$responseArray['webhook_event']['resource']['payer']['payer_info']['payer_id'])->first();
$this->updateStatus($responseArray['webhook_event']['resource']['payer']['payer_info']['payer_id'], 0,1);
break;
}
}
echo $verificationStatus;
exit(0);
}
And here is the $this->apiContext:
trait PayPalApiCredentialsTrait {
private $apiContext;
public function setCredentials()
{
$this->apiContext = new \PayPal\Rest\ApiContext(
new \PayPal\Auth\OAuthTokenCredential(
env('PAYPAL_CLIENT_ID'), // ClientID
env('PAYPAL_CLIENT_SECRET') // ClientSecret
)
);
$this->apiContext->setConfig(
array(
'mode' => env("PAYPAL_MODE"),
'log.LogEnabled' => true,
'log.FileName' => '../PayPal.log',
'log.LogLevel' => 'INFO', // PLEASE USE `INFO` LEVEL FOR LOGGING IN LIVE ENVIRONMENTS
)
);
}
}
This is the error I get from the paypal.log:
[01-09-2020 15:54:18] PayPal\Core\PayPalHttpConnection : INFO: POST https://api.sandbox.paypal.com/v1/oauth2/token
[01-09-2020 15:54:18] PayPal\Core\PayPalHttpConnection : INFO: Response Status : 200
[01-09-2020 15:54:18] PayPal\Core\PayPalHttpConnection : INFO: POST https://api.sandbox.paypal.com/v1/notifications/verify-webhook-signature
[01-09-2020 15:54:19] PayPal\Core\PayPalHttpConnection : INFO: Response Status : 400
[01-09-2020 15:54:19] PayPal\Core\PayPalHttpConnection : ERROR: Got Http response code 400 when accessing https://api.sandbox.paypal.com/v1/notifications/verify-webhook-signature. {"name":"VALIDATION_ERROR","message":"Invalid data provided","debug_id":"26b12ee43cddd","information_link":"https://developer.paypal.com/docs/api/webhooks/#errors","details":[{"field":"webhook_id","location":"body","issue":"Required field cannot be blank"}],"links":[]}
I must mention that everything else works fine.
Creating plans, agreements, cancelling the both, showing active plans, and more...
Everything works smoothly.
This is the only thing that I can't seem to fix.
If anyone could figure this out for me, I'd really appreciate it.
Thank you!
The PayPal-PHP-SDK is deprecated and no longer maintained; it should not be used for new integrations. Its implementation of billing plans and subscriptions is old, and not compatible with the current version of the Subscriptions API.
In its place, a direct HTTPS integration (no SDK) should be used for Subscriptions, and for verifying webhooks.
(For the one time payment use case, there is a new v2 Checkout-PHP-SDK https://developer.paypal.com/docs/api/rest-sdks/ )
I am working on a project. Where I am using laravel as back end and VueJS as front end. I called an API that requests laravel to insert a user. I want to check whether the back end validation is successfully done or not. for this, I'm sending an email that is already in the database. the validation response is all okay. But I want to log a message only instead of logging the whole response. somehow the message is not logging but the response is logging. I could not figure out what the problem is
API call
Response
I want to log the message, not the whole response
Chain the ```.catch(error => { console.log("Errors, error") }); on your ajax request.
I have written this small helper once. It can handle Laravel and also your custom messages returned from the backend. It's not perfect but can get your working in a good direction.
export function errorMessage(error) {
let errorResponse = error.response.data.errors ? error.response.data.errors : error.response.data;
let errors = [];
for (let key in errorResponse){
if(key === 'message'){
errors.push(errorResponse[key]);
}
else if (key !== 'exception' && key !== 'file' && key !== 'line' && key !== 'trace'){
for (let i = 0; i < errorResponse[key].length; i++){
errors.push(errorResponse[key][i]);
}
}
}
return errors;
}
You can use it in your catch block like let errors = errorMessage(error)). I fed my notification plugin with messages that displays on the top of the screen.
So the 422 is an error you will have to handle it in a .catch block
.then() // everything went good
.catch() // something went wrong
Something like this
.then(response => {
// great
})
.catch(error => {
if (error.response.status === 422) {
// do something here
}
}
I'm trying to create telegram bot on Laravel with php-telegram-bot. I have installed webhook and now I get a message:
{"ok": true,
"result": {
"url": "https://.../api/telegram/hook/",
"has_custom_certificate": true,
"pending_update_count": 15,
"last_error_date": 1549043620,
"last_error_message": "Wrong response from the webhook: 301 Moved Permanently",
"max_connections": 40
}
}
What does it mean? I know what is 301 error mean, but can't understand what steps needed to solve this problem.
My controller:
public function hook()
{
$commands_paths = [
app_path() . '/Services/Telegram/Bots/Bitbd_BOT/Commands',
];
try {
// Create Telegram API object
$telegram = new Telegram($this->bot_api_key, $this->bot_username);
TelegramLog::initErrorLog(storage_path() . "/{$this->bot_username}_error.log");
TelegramLog::initDebugLog(storage_path() . "/{$this->bot_username}_debug.log");
TelegramLog::initUpdateLog(storage_path() . "/{$this->bot_username}_update.log");
// Add commands paths containing your custom commands
$telegram->addCommandsPaths($commands_paths);
$telegram->enableLimiter();
// Handle telegram webhook request
$handle = $telegram->handle();
} catch (TelegramException $e) {
echo $e->getMessage();
}
}
API routes:
Route::group(['prefix' => 'telegram'], function () {
Route::get('hook/set', 'TelegramController#setWebhook');
Route::any('hook','TelegramController#hook');
});
Some interesting: /api/telegram/hook correctly works only with ANY or GET option, POST method return empty page with vue, and i don't know why.
You probably have a problem in your webhook url, please check it again, And make sure that is correct and exists in your server.
Even https://example.com/folder/ is different with https://example.com/folder and you have to use / at the end of the address (In my case, I gave that error because of /).
Create a middleware in app/Http/Middleware/PreflightResponse.php
And paste this code:
<?php
namespace App\Http\Middleware;
use Closure;
class PreflightResponse
{
public function handle($request, Closure $next )
{
if ($request->getMethod() === "OPTIONS") {
return response('');
}
return $next($request);
}
}
Then in app/Http/Kernel.php, add in the global variable $middleware:
protected $middleware = [
Middleware\PreflightResponse::class,
];
This is a general solution, but you can specify as a named middleware and using in your routes.
That happens because of CORS and its security measures.
I hope that could help :D
i have a very strange problem.
If i use laravel send mail everything works perfect.
but when i queue a mail it give a this error.
but the very strange part is, that yesterday my code did work!! without changing anything now
this works:
Mail::send('emails.empty',
$invoice, function ($m) use ($invoice) {
$m->from('hello#app.com', 'Your Application');
$m->to($invoice['customer_email'], $invoice['customer_name'])
->subject($invoice['email_subject']);
});
But this doesn't work
Mail::later(1, 'emails.empty',
$invoice, function ($m) use ($invoice) {
$m->from('hello#app.com', 'Your Application');
$m->to($invoice['customer_email'], $invoice['customer_name'])
->subject($invoice['email_subject']);
});
Also with the new 5.3 way it doesn't work
$user = new App\User();
$user = $user->find(1);
Mail::to($user)->queue(new EmailTest($user));
This is the faild job error:
Swift_TransportException: Expected response code 250 but got code "", with message "" in /private_html/dev1/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/AbstractSmtpTransport.php:383
Stack trace:
#0 .......................
I use mailtrap to send/catch my emails. with the same settings de SEND function works! so its not the settings