Google reCAPTCHA v2

CAPTCHA คือ

CAPTCHA สำหรับ web developer หลายๆ คนคงรู้ความหมายอยู่แล้ว ผมขอสรุปสั่นๆ แล้วกันครับ

CAPTCHA คือเครื่องมือช่วยป้องกัน spam หรือ bot ของ website ครับ ซึ่งไม่นานมานี้ Google ได้พัฒนา reCAPTCHA ให้ใช้งานได้ง่ายขึ้น(จริงข่าวออกมาซักพักละ) โดย reCAPTCHA version ใหม่ตัวนี้ผู้ใช้ไม่จำเป็นต้องพิมพ์ตัวอักษรตามที่เห็นอีกต่อไป เปลี่ยนเป็นการติ๊กถูกว่าเราไม่ใช้ bot ซึ่งการตรวจสอบนั้นทาง Google จะประเมินความเสี่ยงและแยกแยะเองว่าเป็นมนุษย์จริงๆ หรือไม แต่ถึงอย่างนั้นหากระบบไม่สามารถแยกแยะได้ว่าเป็นมนุษย์หรือ bot ระบบก็จะแสดงตัวอักษรมาให้พิมพ์ตามเดิม ดูแล้วน่าจะสะดวกกับผู้ใช้มากขึ้น

สมัครใช้ reCAPTCHA v2

การใช้งาน reCAPTCHA ของ Google นั้นต้อง register ก่อนนะครับเพื่อขอรับ Site Key และ Secret Key ในการนำไปใช้ วิธีการนั้นก็ง่ายๆ ครับตามนี้เลย

1. เข้าไปยังเว็บ https://www.google.com/recaptcha/about/

2. Login เข้าใช้งานด้วย Gmail account ที่ต้องการ

3. คลิกที่ปุ่ม

4. คลิกที่ปุ่ม + ด้านขวา หรือกด link 👉https://www.google.com/recaptcha/admin/create

5. กรอกข้อมูลลงไปตามรายละเอียดที่เราจะใช้งาน เพื่อให้ได้

กรณีต้องการ Test เราจำเป็นต้องมี domain จริงๆ ด้วยนะครับ ใช้ localhost ไม่ได้นะ

6. ติ๊กยอมครับ Accept the reCAPTCHA Terms of Service แล้วคลิก "Submit"

7. จากนั้นเราจะได้ Key มา 2 ตัว คือ

  • Site key ตัวนี้เราจะ copy และนำไปใช้ที่ client side (html เรา)

  • Secret key ตัวนี้เราจะ copy และนำไปใช้ก server side (ในตัวอย่างนี้คือ python เรา)

8. ทุกอย่างที่ต้องเตรียมเรียบร้อย เริ่ม coding กันเลย

เริ่ม coding กันเลย

ตัวอย่างนี้จะใช้ python Flask ดูแลในส่วน server side และมี page เดียวเลยคือ index.html ง่ายๆ ไป

/google-recaptcha
- /templates
--- index.html
--- success.html
--- fail.html
- main.py

เริ่มจาก index.html จุดสำคัญเลยคือ

  • line ที่ 8 เราต้องเพิ่ม lib ของ google recaptcha

  • line ที่ 16 สำหรับแสดง reCAPTCHA ให้ user บอกว่าตัวเองนั้นไม่ใช่ bot นะ (อย่าลืม replace site key เป็นของคุณเองก่อน test นะ)

  • line 25 default เมื่อเปิด web เราแล้วหาก user ยังไม่ได้ verify ว่าเป็น bot หรือไมก็ควรจะยัง submit อะไรไม่ได้นะ

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
    <title>Google reCAPTCHA</title>
    <script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>

<body>
    <form action="/verify" method="POST">
        <center>
            <h2>Google reCAPTCHA v2</h2>
        </center>
        <center>
        <div class="g-recaptcha" data-sitekey="{Your Site Key}" data-callback="makeaction"></div>
        <br />
        <button id="btn_submit" type="submit" type="button" class="btn btn-outline-success" disabled>Verify</button>
    </center>
    </form
</body>

</html>
<script>
    var makeaction = function(){
        document.getElementById('btn_submit').disabled = false;
    }
</script>

success.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
    <title>Google reCAPTCHA</title>
</head>
<body>
    <center>
        <h2>success</h2>
    </center>
</body>
</html>

fail.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
    <title>Google reCAPTCHA</title>
</head>
<body>
    <center>
        <h2>fail</h2>
    </center>
</body>
</html>

ต่อด้วย main.py เราได้เพิ่ม reCAPTCHA ใน client side แล้ว แต่จะ verify แค่ client side อย่างเดียวนั้นไม่รอดแน่นอน เดี๋ยวนี้ทุก web broswer มี dev tool เทพๆ เยอะแยะ ดังนั้นเราควร verify ที่ server side ด้วยดีที่สุด

  • route 1 เมื่อเปิด web ด้วย url localhost:5000 จะ render index.html ขึ้นมา

  • route 2 (/verify) method POST เพื่อคลิก Verify จาก index.html จะเข้า route นี้ หากทำงานถูกต้องเราควรได้ reCAPTCHA token จาก client side มาด้วย จากนั้นเราจะนำ token ที่ได้ไป verify กับ google โดยตรงอีกครั้ง (line 14 - 22) หากได้ response กลับมาและมี value success เป็น True เราจะได้สรุปได้ว่า user ที่คลิก Verify มานั้นไม่ใช่ Bot แน่นอนครับ 🎉

from flask import Flask, render_template, jsonify, request, json

app = Flask(__name__)


@app.route('/',  methods=['GET'])
def index():
  return render_template("index.html")


@app.route('/verify', methods=['POST'])
def verify():

    # reCAPTCHAP server side
    recaptcha_url = 'https://www.google.com/recaptcha/api/siteverify'
    recaptcha_secret_key = '{ Your Secret Key}'
    payload = {
        'secret': recaptcha_secret_key,
        'response': request.form.get('g-recaptcha-response', ""), #token from client-side
        'remoteip': request.remote_addr,
    }
    verify_response = requests.post(recaptcha_url, data=payload)
    if verify_response.status_code != 200:
        return render_template("fail.html")
    else:
        result = verify_response.json()
        success = result['success']
        if success is True:
            return render_template("success.html")
        else:
            return render_template("fail.html")

if __name__ == "__main__":
  app.run(port=5000)

Example code

👉 https://github.com/nottfree/google-recaptcha

Reference

Last updated

Was this helpful?