How to handle incoming POST data from external server in Laravel

核能气质少年 提交于 2019-12-10 19:21:57

问题


I have a route for handling incoming POST data in laravel:

Route::get('/sendgrid/api', 'SendGrid\EmailEventsController@parse');

Here's my controller:

namespace App\Http\Controllers\SendGrid;

use App\Http\Controllers\Controller;
use App\Models\SendGrid\EmailEvents;

class EmailEventsController extends Controller
{
    public function parse()
    {
        $contents = file_get_contents("php://input");
        $requests = json_decode($contents);

        $data = array();

        foreach ($requests as $request)
        {
            array_push($data, array(
                'email' => $request->email,
                'event' => $request->event,
                'category' => $request->category
            ));
        }

        EmailEvents::insert($data);
    }
}

But still doesn't work. What did I do wrong?


回答1:


First, you can change your route looks like this

Route::any('/sendgrid/api', 'SendGrid\EmailEventsController@parse');

And then, you must ignore for not used csrf in Middleware > VerifyCsrfToken

And add your code looks like this

protected $except = [
     '/sendgrid/api',
];

And you can used and change

$contents = file_get_contents("php://input");

to

$contents = $request->getContent();

i hope this code can help your problems. thanks




回答2:


Like you said, it's a POST request, then receive it using POST

Route::post('/sendgrid/api', 'SendGrid\EmailEventsController@parse');


来源:https://stackoverflow.com/questions/46045179/how-to-handle-incoming-post-data-from-external-server-in-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!