LoginSignup
18
17

More than 5 years have passed since last update.

Guzzle を使用してHTTPS(POST)通信し、リクエストを送受信する

Last updated at Posted at 2016-10-30

環境

  • CentOS 7
  • PHP 7
  • Laravel 5.3

やりたいこと

curl -kv -d "email=hoge@gmail.com" https://hoge.com/registers

的なことを Laravel でやって、レスポンスを受け取りたい。

※実際にはフロントエンドからのリクエストをバックエンドに投げるBFF(Backend For Frontend)的なものを作りたい

方法

Guzzle(PHPのHTTPクライアントライブラリ)を使う。

インストール方法

AWSのSDKに Guzzle が入っているので、今回はそれを使用した。

composer.json
...

"aws/aws-sdk-php": "3.*"

...

実装方法

routes/web.php
Route::post('registers', 'RegistersController@apply');
app/Http/Controllers/RegistersController.php
use GuzzleHttp\Exception\RequestException;

class RegistersController extends Controller
{
    public function apply(Request $request)
    {
        $client = new \GuzzleHttp\Client(
            [\GuzzleHttp\RequestOptions::VERIFY => false]
        );

        $res = $client->request(
            'POST',

            // ここにはレスポンスを返却してくれるURL(API)を設定
            'https://hoge.com/registers',
            [
                'form_params' => [
                    'email' => request->get('email'),
                ]
            ]
        );

        return $res;
    }
}

解説

HTTPS通信できるようにする

[\GuzzleHttp\RequestOptions::VERIFY => false]

falseを指定することにより証明書の検証を回避できる。
(本番ではやらないけど)

POSTデータの指定

form_paramsを使えばPOSTするデータを定義できる。
オプション一覧

18
17
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
17