BÀI 72 - XÁC MINH ROBOT TRONG ANDROID
Đầu tiên, bạn vào đây để tạo key xác minh cho minh cho ứng dụng của bạn
API sẽ cung cấp cho bạn các loại xác minh như hình dưới:
Bạn chọn "reCAPTCHA Android"
Sau đó, ở domain bạn nhập địa chỉ của app bạn vào đó, nó có dạng com.gì đó.gì đó
SITE KEY sẽ giúp bạn xác minh người dùng có phải người dùng không.
SECRET KEY sẽ giúp bạn kiểm tra hành vi người dùng để bắt người dùng phải làm đúng trình tự
Trong android bạn thêm thư viện này
apply plugin: 'com.android.application'
...
dependencies {
implementation 'com.google.android.gms:play-services-safetynet:17.0.1'
}
Có 2 key do mình chọn cả trên web và app. Bạn copy key theo nhu cầu của bạn rồi làm tiếp như dưới
Trong android bạn thêm thư viện này
RequestQueue queue;
//...
btnDelete.setOnClickListener(v -> {
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setMessage("Nếu chấp nhận toàn bộ dữ liệu trong dự án này sẽ bị xóa và bạn không thể khôi phục lại. Hãy thận trọng!");
dialog.create();
dialog.setPositiveButton("Xóa", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
SafetyNet.getClient(this).verifyWithRecaptcha(GetKey.keyCaptcha)
.addOnSuccessListener(this, response -> {
String userResponseToken = response.getTokenResult();
if (!userResponseToken.isEmpty()) {
KiemTraHanhVi(userResponseToken);
}
})
.addOnFailureListener(this, e -> {
if (e instanceof ApiException) {
ApiException apiException = (ApiException) e;
int statusCode = apiException.getStatusCode();
Log.d("captcha", "Error: " + CommonStatusCodes
.getStatusCodeString(statusCode));
} else {
// A different, unknown type of error occurred.
Log.d("captcha", "Error: " + e.getMessage());
}
});
}
}).setNegativeButton("Hủy", (dialog1, which) -> dialog1.cancel());
});
//...
private void KiemTraHanhVi(String userResponseToken) {
String url = "https://www.google.com/recaptcha/api/siteverify";
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getBoolean("success")){
// Nếu ok hết thì làm gì đó ở đây
} else {
// Nếu sai thì in lỗi sai ra đây
Toast.makeText(getApplicationContext(), jsonObject.getString("error-codes"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, error -> { }){
protected Map<String, String> getParams(){
Map<String, String> params = new HashMap<>();
params.put("secret", GetKey.secretCaptcha);
params.put("response", userResponseToken);
return params;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
50000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(stringRequest);
}
Tham khảo thêm ở đây