hysryt / wiki

https://hysryt.github.io/wiki/
0 stars 0 forks source link

Google reCAPTCHA v2 #71

Open hysryt opened 6 years ago

hysryt commented 6 years ago

https://developers.google.com/recaptcha/intro

hysryt commented 6 years ago

用意するもの

登録の際のドメイン名には reCAPTCHA を表示するページのドメインを指定する。 ローカルでやる場合は localhost や IPアドレス など。

フォーム側HTML

<html>
  <head>
    <title>reCAPTCHA demo: Simple page</title>
    <script src="https://www.google.com/recaptcha/api.js" async defer></script>
  </head>
  <body>
    <form action="?" method="POST">
      <div class="g-recaptcha" data-sitekey="your_site_key"></div>
      <br/>
      <input type="submit" value="Submit">
    </form>
  </body>
</html>

サーバー側

POSTパラメータとしてg-recaptcha-response が送られてくるのでその値を検証する。 検証にはGoogleで用意されている検証用APIを使用する。

https://www.google.com/recaptcha/api/siteverify

キー 説明
secret APIシークレットキー
response 送られてきた g-recaptcha-response
remoteip ユーザのIPアドレス。オプション

検証用API に対して POST で上のデータを合わせて送ると以下のような結果が返ってくる

{
  "success": true|false,
  "challenge_ts": timestamp,  // timestamp of the challenge load (ISO format yyyy-MM-dd'T'HH:mm:ssZZ)
  "hostname": string,         // the hostname of the site where the reCAPTCHA was solved
  "error-codes": [...]        // optional
}

"success" が true の場合、g-recaptcha-response が正しいということになる。

"error-codes" はエラー時のみ送られてくる。

Error code 説明
missing-input-secret "secret" パラメータがない
invalid-input-secret "secret" パラメータが不正
missing-input-response "response" パラメータがない
invalid-input-response "response" パラメータが不正
bad-request リクエストが不正

検証時の処理は PHP で書く場合以下のような感じ

function verifyRecaptchaResponse($recaptcha_response) {
    $params = http_build_query([
        "secret" => "your_secret_key",
        "response" => $recaptcha_response
    ]);

    $options = [
        "http" => [
            "method" => "POST",
            "header" => "Content-type: application/x-www-form-urlencoded",
            "content" => $params
        ]
    ];

    $context = stream_context_create($options);

    return json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify", false, $context));
}

$recaptcha_response = $_POST["g-recaptcha-response"];
$response = verifyRecaptchaResponse($recaptcha_response);