เอกสารนี้จะอธิบายวิธีผสานรวม reCAPTCHA API จาก SafetyNet เข้ากับแอป
ข้อกำหนดในการให้บริการเพิ่มเติม
การเข้าถึงหรือใช้ reCAPTCHA API จะถือว่าคุณยอมรับข้อกำหนดในการให้บริการของ Google APIs และข้อกำหนดในการให้บริการ reCAPTCHA ต่อไปนี้
โปรดอ่านและทำความเข้าใจข้อกำหนดและนโยบายที่เกี่ยวข้องทั้งหมดก่อนเข้าถึง API
ข้อกำหนดในการให้บริการของ reCAPTCHA
คุณรับทราบและเข้าใจว่า reCAPTCHA API ทำงานโดยรวบรวมข้อมูลฮาร์ดแวร์และซอฟต์แวร์ เช่น ข้อมูลอุปกรณ์และแอปพลิเคชัน รวมถึงผลการตรวจสอบความสมบูรณ์ แล้วส่งข้อมูลดังกล่าวไปให้ Google วิเคราะห์
ตามส่วนที่ 3(ง) ของข้อกำหนดในการให้บริการของ Google APIs คุณยอมรับว่าหากคุณใช้ API ดังกล่าวก็จะต้องรับผิดชอบในการแจ้งเตือนหรือให้ความยินยอมที่จำเป็นในการรวบรวมและแชร์ข้อมูลนี้กับ Google
แพ็กเกจ: ระบุชื่อแพ็กเกจของแอปแต่ละแอปที่ใช้คีย์ API นี้ ชื่อแพ็กเกจที่คุณป้อนต้องตรงกับชื่อแพ็กเกจของแอปทุกประการเพื่อให้แอปใช้ API ได้ ป้อนชื่อแพ็กเกจแต่ละรายการในบรรทัดของตนเอง
ก่อนใช้ reCAPTCHA API ให้เพิ่ม SafetyNet API ลงในโปรเจ็กต์
หากคุณใช้ Android Studio ให้เพิ่มทรัพยากร Dependency นี้ลงในไฟล์ Gradle ระดับแอป โปรดดูข้อมูลเพิ่มเติมที่การตั้งค่า SafetyNet API
ใช้ reCAPTCHA API
ส่วนนี้อธิบายวิธีเรียก reCAPTCHA API เพื่อส่งคำขอยืนยัน CAPTCHA และรับโทเค็นคำตอบของผู้ใช้
funonClick(view:View){SafetyNet.getClient(this).verifyWithRecaptcha(YOUR_API_SITE_KEY).addOnSuccessListener(thisasExecutor,OnSuccessListener{response->// Indicates communication with reCAPTCHA service was// successful.valuserResponseToken=response.tokenResultif(response.tokenResult?.isNotEmpty()==true){// Validate the user response token using the// reCAPTCHA siteverify API.}}).addOnFailureListener(thisasExecutor,OnFailureListener{e->if(eisApiException){// An error occurred when communicating with the// reCAPTCHA service. Refer to the status code to// handle the error appropriately.Log.d(TAG,"Error: ${CommonStatusCodes.getStatusCodeString(e.statusCode)}")}else{// A different, unknown type of error occurred.Log.d(TAG,"Error: ${e.message}")}})}
Java
publicvoidonClick(Viewv){SafetyNet.getClient(this).verifyWithRecaptcha(YOUR_API_SITE_KEY).addOnSuccessListener((Executor)this,newOnSuccessListener<SafetyNetApi.RecaptchaTokenResponse>(){@OverridepublicvoidonSuccess(SafetyNetApi.RecaptchaTokenResponseresponse){// Indicates communication with reCAPTCHA service was// successful.StringuserResponseToken=response.getTokenResult();if(!userResponseToken.isEmpty()){// Validate the user response token using the// reCAPTCHA siteverify API.}}}).addOnFailureListener((Executor)this,newOnFailureListener(){@OverridepublicvoidonFailure(@NonNullExceptione){if(einstanceofApiException){// An error occurred when communicating with the// reCAPTCHA service. Refer to the status code to// handle the error appropriately.ApiExceptionapiException=(ApiException)e;intstatusCode=apiException.getStatusCode();Log.d(TAG,"Error: "+CommonStatusCodes.getStatusCodeString(statusCode));}else{// A different, unknown type of error occurred.Log.d(TAG,"Error: "+e.getMessage());}}});}
[null,null,["อัปเดตล่าสุด 2025-08-16 UTC"],[],[],null,["# SafetyNet reCAPTCHA API\n\n| **Warning:** In order to help you safely grow your business, Google builds tools to protect your Android apps and games from abuse. We evolve these solutions as the abuse landscape changes. Delivering on this promise, Google is replacing the SafetyNet reCAPTCHA API with [reCAPTCHA](https://cloud.google.com/recaptcha/docs/instrument-android-apps). reCAPTCHA offers superior protection for mobile applications. We plan to gradually turn down the SafetyNet reCAPTCHA API starting in the third quarter of 2025. Details can be found in the [reCAPTCHA deprecation and shutdown policy](https://cloud.google.com/recaptcha/docs/deprecation-policy-mobile).\n\nThe SafetyNet service includes a reCAPTCHA API that you can use to protect your\napp from malicious traffic.\n\nreCAPTCHA is a free service that uses an advanced risk analysis engine to\nprotect your app from spam and other abusive actions. If the service suspects\nthat the user interacting with your app might be a bot instead of a human, it\nserves a CAPTCHA that a human must solve before your app can continue executing.\n| **Note:** In order to use this API, your app must set `minSdkVersion` to `14` or higher in the `AndroidManifest.xml` file.\n\nThis document explains how to integrate the reCAPTCHA API from SafetyNet into\nyour app.\n\nAdditional terms of service\n---------------------------\n\nBy accessing or using the reCAPTCHA API, you agree to the [Google APIs Terms of\nService](https://developers.google.com/terms/) and to the following reCAPTCHA\nTerms of Service.\nPlease read and understand all applicable terms and policies before accessing\nthe APIs. \n\n### reCAPTCHA Terms of Service\n\nYou acknowledge and understand that the reCAPTCHA API works by collecting hardware and software information, such as device and application data and the results of integrity checks, and sending that data to Google for analysis. Pursuant to Section 3(d) of the Google APIs Terms of Service, you agree that if you use the APIs that it is your responsibility to provide any necessary notices or consents for the collection and sharing of this data with Google.\n\nRegister a reCAPTCHA key pair\n-----------------------------\n\nTo register a key pair for use with the SafetyNet reCAPTCHA API, navigate to the\n[reCAPTCHA Android signup site](https://www.google.com/recaptcha/admin/create),\nthen complete the following sequence of steps:\n\n1. In the form that appears, provide the following information:\n\n - **Label:** A unique label for your key. Typically, you use the name of your company or organization.\n - **reCAPTCHA type:** Select **reCAPTCHA v2** , then **reCAPTCHA Android**.\n - **Packages:** Provide the package name of each app that uses this API key. In order for an app to use the API, the package name that you enter must exactly match the app's package name. Enter each package name on its own line.\n - **Owners:** Add an email address for each individual in your organization who monitors your app's reCAPTCHA assessments.\n2. Select the **Accept the reCAPTCHA Terms of Service** checkbox.\n\n3. **Send alerts to owners:** Select this checkbox if you want to receive\n emails about the reCAPTCHA API, then click\n **Submit**.\n\n4. On the page that appears\n next, your public and private keys appear under **Site key** and **Secret\n key** , respectively. You use the site key when you [send the verify\n request](#send-request), and you use the secret key when you [validate the\n user response token](#validate-response).\n\nAdd the SafetyNet API dependency\n--------------------------------\n\nBefore using the reCAPTCHA API, add the SafetyNet API to your project.\nIf you are using Android Studio, add this dependency to your app-level Gradle\nfile. For more information, see [SafetyNet API setup](https://developer.android.com/training/safetynet#before-you-begin).\n\nUse the reCAPTCHA API\n---------------------\n\nThis section describes how to call the reCAPTCHA API to send a CAPTCHA\nverification request and receive the user response token.\n\n### Send the verify request\n\nTo invoke the SafetyNet reCAPTCHA API, you call the\n[`verifyWithRecaptcha()`](https://developers.google.com/android/reference/com/google/android/gms/safetynet/SafetyNetClient.html#verifyWithRecaptcha(java.lang.String))\nmethod. Usually, this method corresponds to the user's selecting a UI element,\nsuch as a button, in your activity.\n\nWhen using the\n`verifyWithRecaptcha()`\nmethod in your app, you must do the following:\n\n- Pass in your API site key as a parameter.\n- Override the [`onSuccess()`](https://developers.google.com/android/reference/com/google/android/gms/tasks/OnSuccessListener.html#onSuccess(TResult)) and [`onFailure()`](https://developers.google.com/android/reference/com/google/android/gms/tasks/OnFailureListener.html#onFailure(java.lang.Exception)) methods to handle both possible outcomes of the verification request task. In particular, if the API passes an instance of [`ApiException`](https://developers.google.com/android/reference/com/google/android/gms/common/api/ApiException) into `onFailure()`, you need to handle each possible status code that you can retrieve using [`getStatusCode()`](https://developers.google.com/android/reference/com/google/android/gms/common/api/ApiException#getStatusCode()).\n\nThe following code snippet shows how to invoke this method: \n\n### Kotlin\n\n```kotlin\nfun onClick(view: View) {\n SafetyNet.getClient(this).verifyWithRecaptcha(YOUR_API_SITE_KEY)\n .addOnSuccessListener(this as Executor, OnSuccessListener { response -\u003e\n // Indicates communication with reCAPTCHA service was\n // successful.\n val userResponseToken = response.tokenResult\n if (response.tokenResult?.isNotEmpty() == true) {\n // Validate the user response token using the\n // https://developers.google.com/recaptcha/docs/verify.\n }\n })\n .addOnFailureListener(this as Executor, OnFailureListener { e -\u003e\n if (e is ApiException) {\n // An error occurred when communicating with the\n // reCAPTCHA service. https://developers.google.com/android/reference/com/google/android/gms/safetynet/SafetyNetStatusCodes to\n // handle the error appropriately.\n Log.d(TAG, \"Error: ${CommonStatusCodes.getStatusCodeString(e.statusCode)}\")\n } else {\n // A different, unknown type of error occurred.\n Log.d(TAG, \"Error: ${e.message}\")\n }\n })\n}\n```\n\n### Java\n\n```java\npublic void onClick(View v) {\n SafetyNet.getClient(this).verifyWithRecaptcha(YOUR_API_SITE_KEY)\n .addOnSuccessListener((Executor) this,\n new OnSuccessListener\u003cSafetyNetApi.RecaptchaTokenResponse\u003e() {\n @Override\n public void onSuccess(SafetyNetApi.RecaptchaTokenResponse response) {\n // Indicates communication with reCAPTCHA service was\n // successful.\n String userResponseToken = response.getTokenResult();\n if (!userResponseToken.isEmpty()) {\n // Validate the user response token using the\n // https://developers.google.com/recaptcha/docs/verify.\n }\n }\n })\n .addOnFailureListener((Executor) this, new OnFailureListener() {\n @Override\n public void onFailure(@NonNull Exception e) {\n if (e instanceof ApiException) {\n // An error occurred when communicating with the\n // reCAPTCHA service. https://developers.google.com/android/reference/com/google/android/gms/safetynet/SafetyNetStatusCodes to\n // handle the error appropriately.\n ApiException apiException = (ApiException) e;\n int statusCode = apiException.getStatusCode();\n Log.d(TAG, \"Error: \" + CommonStatusCodes\n .getStatusCodeString(statusCode));\n } else {\n // A different, unknown type of error occurred.\n Log.d(TAG, \"Error: \" + e.getMessage());\n }\n }\n });\n}\n```\n\n### Validate the user response token\n\nWhen the reCAPTCHA API executes the\n`onSuccess()`\nmethod, the user has successfully completed the CAPTCHA challenge. However, this\nmethod only indicates that the user has solved the CAPTCHA correctly. You still\nneed to validate the user's response token from your backend server.\n\nTo learn how to validate the user's response token, see [Verifying the user's\nresponse](https://developers.google.com/recaptcha/docs/verify)."]]