Google Cloud reCAPTCHA Enterprise API client library for protecting websites and applications from fraud
—
Core fraud detection functionality that analyzes user interactions and provides risk scores, token validation, and detailed threat analysis. Assessment operations form the heart of reCAPTCHA Enterprise's fraud prevention capabilities.
Analyzes user interactions to determine the likelihood of fraudulent activity. Returns a comprehensive assessment including risk scores, token validation results, and detailed fraud analysis signals.
def create_assessment(
request: CreateAssessmentRequest = None,
*,
parent: str = None,
assessment: Assessment = None,
retry: Union[retries.Retry, gapic_v1.method._MethodDefault] = _MethodDefault._DEFAULT_VALUE,
timeout: Union[float, object] = _MethodDefault._DEFAULT_VALUE,
metadata: Sequence[Tuple[str, str]] = ()
) -> Assessment:
"""
Creates an Assessment to analyze user interactions.
Args:
request: The request object for creating an assessment
parent: Required. The name of the project in format 'projects/{project}'
assessment: Required. The assessment details
retry: Retry configuration for the request
timeout: Timeout for the request in seconds
metadata: Additional metadata for the request
Returns:
Assessment: Complete assessment results including risk analysis,
token properties, and fraud detection signals
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request fails
google.api_core.exceptions.InvalidArgument: If request parameters are invalid
google.api_core.exceptions.PermissionDenied: If insufficient permissions
"""from google.cloud import recaptchaenterprise
from google.cloud.recaptchaenterprise_v1.types import Assessment, Event
client = recaptchaenterprise.RecaptchaEnterpriseServiceClient()
# Create event details
event = Event(
token="03AIIukzh7Z...", # reCAPTCHA token from frontend
site_key="6LdGwQ0...", # Your site key
user_agent="Mozilla/5.0...",
user_ip_address="203.0.113.1",
expected_action="login",
hashed_account_id=b"hashed_user_id"
)
# Create assessment
assessment = Assessment(event=event)
request = recaptchaenterprise.CreateAssessmentRequest(
parent="projects/your-project-id",
assessment=assessment
)
# Execute assessment
response = client.create_assessment(request=request)
# Analyze results
risk_score = response.risk_analysis.score
if risk_score >= 0.5:
print(f"Legitimate interaction (score: {risk_score})")
else:
print(f"Potential fraud detected (score: {risk_score})")
print(f"Reasons: {response.risk_analysis.reasons}")Provides feedback on assessment accuracy to improve the machine learning model. This helps reCAPTCHA Enterprise learn from real-world outcomes and improve future assessments.
def annotate_assessment(
request: AnnotateAssessmentRequest = None,
*,
name: str = None,
annotation: AnnotateAssessmentRequest.Annotation = None,
retry: Union[retries.Retry, gapic_v1.method._MethodDefault] = _MethodDefault._DEFAULT_VALUE,
timeout: Union[float, object] = _MethodDefault._DEFAULT_VALUE,
metadata: Sequence[Tuple[str, str]] = ()
) -> AnnotateAssessmentResponse:
"""
Annotates a previously created Assessment with feedback.
Args:
request: The request object for annotating an assessment
name: Required. The resource name of the Assessment in format
'projects/{project}/assessments/{assessment}'
annotation: Optional. The annotation providing feedback
retry: Retry configuration for the request
timeout: Timeout for the request in seconds
metadata: Additional metadata for the request
Returns:
AnnotateAssessmentResponse: Response confirming annotation was recorded
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request fails
google.api_core.exceptions.NotFound: If the assessment doesn't exist
google.api_core.exceptions.InvalidArgument: If annotation is invalid
"""# After determining the actual outcome of a user interaction
assessment_name = response.name # From previous create_assessment call
# Annotate based on actual fraud outcome
annotation_request = recaptchaenterprise.AnnotateAssessmentRequest(
name=assessment_name,
annotation=recaptchaenterprise.AnnotateAssessmentRequest.Annotation.LEGITIMATE
)
client.annotate_assessment(request=annotation_request)class CreateAssessmentRequest:
"""Request message for creating an assessment."""
parent: str # Required. Project name in format 'projects/{project}'
assessment: Assessment # Required. The assessment detailsclass Assessment:
"""Assessment of user interaction for fraud detection."""
name: str # Output only. Resource name
event: Event # Required. User event details
risk_analysis: RiskAnalysis # Output only. Risk analysis results
token_properties: TokenProperties # Output only. Token validation results
account_defender_assessment: AccountDefenderAssessment # Account defender results
fraud_prevention_assessment: FraudPreventionAssessment # Fraud prevention results
phone_fraud_assessment: PhoneFraudAssessment # Phone fraud analysis
firewall_policy_assessment: FirewallPolicyAssessment # Firewall policy results
account_verification: AccountVerificationInfo # Account verification
private_password_leak_verification: PrivatePasswordLeakVerification # Password leak checkclass Event:
"""User event details for assessment."""
token: str # Optional. reCAPTCHA token
site_key: str # Optional. Site key for the event
user_agent: str # Optional. User agent string
user_ip_address: str # Optional. IP address of the user
expected_action: str # Optional. Expected action name
hashed_account_id: bytes # Optional. Hashed account identifier
express: bool # Optional. Whether this is Express assessment
requested_uri: str # Optional. URI being requested
waf_token_assessment: bool # Optional. Whether to assess WAF token
ja3: str # Optional. JA3 fingerprint
headers: List[str] # Optional. HTTP headers
firewall_policy_evaluation: bool # Optional. Whether to evaluate firewall policies
transaction_data: TransactionData # Optional. Transaction details for fraud prevention
user_info: UserInfo # Optional. User informationclass RiskAnalysis:
"""Risk analysis results from assessment."""
score: float # Risk score between 0.0 (likely fraud) and 1.0 (likely legitimate)
reasons: List[str] # List of reasons for the risk score
extended_verdict: ExtendedVerdict # Extended verdict with additional context
class ExtendedVerdict:
"""Extended verdict information."""
class Verdict(Enum):
VERDICT_UNSPECIFIED = 0
LEGITIMATE = 1
SUSPICIOUS = 2
MALICIOUS = 3class TokenProperties:
"""Properties of the reCAPTCHA token."""
valid: bool # Whether the token is valid
invalid_reason: str # Reason for invalidity if token is invalid
hostname: str # Hostname for which the token was generated
android_package_name: str # Android package name (if applicable)
ios_bundle_id: str # iOS bundle ID (if applicable)
action: str # Action associated with the token
create_time: Timestamp # When the token was created
class InvalidReason(Enum):
"""Reasons why a token might be invalid."""
INVALID_REASON_UNSPECIFIED = 0
UNKNOWN_INVALID_REASON = 1
MALFORMED = 2
EXPIRED = 3
DUPE = 4
MISSING = 5
BROWSER_ERROR = 6class AccountDefenderAssessment:
"""Account Defender assessment results."""
labels: List[str] # Account defender labels
class FraudPreventionAssessment:
"""Fraud prevention assessment results."""
transaction_risk: float # Transaction risk score
stolen_instrument_verdict: StolenInstrumentVerdict # Stolen instrument analysis
card_testing_verdict: CardTestingVerdict # Card testing analysis
behavioral_trust_verdict: BehavioralTrustVerdict # Behavioral trust analysis
class PhoneFraudAssessment:
"""Phone fraud assessment results."""
sms_toll_fraud_verdict: SmsTollFraudVerdict # SMS toll fraud analysis
class SmsTollFraudVerdict:
"""SMS toll fraud verdict."""
reasons: List[str] # Reasons for the verdict
risk: float # Risk score for SMS toll fraud
class FirewallPolicyAssessment:
"""Firewall policy assessment results."""
firewall_policy: FirewallPolicy # The firewall policy that matched
error: Status # Error information if policy evaluation failedclass AnnotateAssessmentRequest:
"""Request to annotate an assessment with feedback."""
name: str # Required. Assessment name
annotation: Annotation # Optional. The annotation
reasons: List[Reason] # Optional. Reasons for the annotation
hashed_account_id: bytes # Optional. Account identifier
transaction_event: TransactionEvent # Optional. Transaction event details
class Annotation(Enum):
"""Annotation values for assessment feedback."""
ANNOTATION_UNSPECIFIED = 0
LEGITIMATE = 1
FRAUDULENT = 2
PASSWORD_CORRECT = 3
PASSWORD_INCORRECT = 4
class Reason(Enum):
"""Reasons for annotation."""
REASON_UNSPECIFIED = 0
CHARGEBACK = 1
CHARGEBACK_FRAUD = 8
CHARGEBACK_DISPUTE = 9
REFUND = 10
REFUND_FRAUD = 11
TRANSACTION_ACCEPTED = 12
TRANSACTION_DECLINED = 13
PAYMENT_HEURISTICS = 2
INITIATED_TWO_FACTOR = 7
PASSED_TWO_FACTOR = 3
FAILED_TWO_FACTOR = 4
CORRECT_PASSWORD = 5
INCORRECT_PASSWORD = 6class AnnotateAssessmentResponse:
"""Response message for annotation request."""
# This message is typically empty, indicating successful annotationclass AccountVerificationInfo:
"""Information about account verification for identity verification."""
endpoints: List[EndpointVerificationInfo] # Endpoints for identity verification
language_code: str # Language preference for verification
latest_verification_result: Result # Result of latest verification challenge
username: str # Username being verified (deprecated)
class EndpointVerificationInfo:
"""Information about a verification endpoint for 2FA."""
email_address: str # Email endpoint for verification
phone_number: str # Phone endpoint for verification
class PrivatePasswordLeakVerification:
"""Private password leak verification information."""
lookup_hash_prefix: bytes # 26-bit prefix of SHA-256 hash
encrypted_user_credentials_hash: bytes # Encrypted Scrypt hash
encrypted_leak_match_prefixes: List[bytes] # Encrypted leak match prefixes
reencrypted_user_credentials_hash: bytes # Re-encrypted hash
class TransactionData:
"""Transaction data for payment fraud prevention."""
transaction_id: str # Unique transaction identifier
payment_method: str # Payment method used
card_bin: str # Bank identification number
card_last_four: str # Last four digits of card
currency_code: str # Transaction currency
value: float # Transaction value
shipping_value: float # Shipping cost
shipping_address: TransactionData.Address # Shipping address
billing_address: TransactionData.Address # Billing address
user: TransactionData.User # User information
merchants: List[TransactionData.User] # Merchant information
items: List[TransactionData.Item] # Transaction items
gateway_info: TransactionData.GatewayInfo # Payment gateway information
class TransactionEvent:
"""Describes an event in payment transaction lifecycle."""
event_type: TransactionEventType # Type of transaction event
reason: str # Reason or code for the event
value: float # Value associated with event
event_time: Timestamp # When event occurred
class UserInfo:
"""User information for assessment."""
create_account_time: Timestamp # Account creation time
account_id: str # Account identifier
user_ids: List[UserId] # Associated user identifiers
class UserId:
"""User identifier for assessment."""
email: str # Email address
phone_number: str # Phone number
username: str # Username
account_id: str # Account ID
class FraudSignals:
"""Fraud signals describing users and cards in transaction."""
user_signals: FraudSignals.UserSignals # User-related fraud signals
card_signals: FraudSignals.CardSignals # Card-related fraud signals
class AssessmentEnvironment:
"""Environment information for assessment creation."""
client: str # Client module information
version: str # Client versionCommon errors when working with assessments:
from google.api_core import exceptions
try:
response = client.create_assessment(request=request)
except exceptions.InvalidArgument as e:
# Invalid request parameters (missing required fields, malformed data)
print(f"Invalid request: {e}")
except exceptions.PermissionDenied as e:
# Insufficient IAM permissions for reCAPTCHA Enterprise API
print(f"Permission denied: {e}")
except exceptions.ResourceExhausted as e:
# Rate limits or quota exceeded
print(f"Rate limit exceeded: {e}")
except exceptions.FailedPrecondition as e:
# Site key not configured properly or project setup issues
print(f"Precondition failed: {e}")user_ip_address and user_agent for better accuracyexpected_action names that match your application's actionshashed_account_id for account-level analysisInstall with Tessl CLI
npx tessl i tessl/pypi-google-cloud-recaptcha-enterprise