Get Started

Note: Humanmark is currently in beta. To get API credentials, please email sales@humanmark.io.

Get up and running with Humanmark in just a few minutes.

1. Backend Setup

First, you'll need to set up your backend to create challenges and verify receipts. Store your API credentials securely in environment variables:

.env
# .env
HUMANMARK_API_KEY=your_api_key
HUMANMARK_API_SECRET=your_api_secret

Create an endpoint to generate challenge tokens:

app.py
# app.py
from flask import Flask, request, jsonify
import jwt
import requests
import os

app = Flask(__name__)

# Create a challenge endpoint
@app.route('/api/create-humanmark-challenge', methods=['POST'])
def create_humanmark_challenge():
    try:
        response = requests.post(
            'https://humanmark.io/api/v1/challenge/create',
            headers={
                'Content-Type': 'application/json',
                'hm-api-key': os.environ['HUMANMARK_API_KEY'],
                'hm-api-secret': os.environ['HUMANMARK_API_SECRET']
            },
            json={'domain': 'yourdomain.com'}
        )
        
        data = response.json()
        
        # Save challenge for future verification
        db.save_challenge(data['challenge'])
        
        # Return the challenge token to your frontend
        return jsonify({'token': data['token']})
        
    except Exception as e:
        print(f'Failed to create challenge: {e}')
        return jsonify({'error': 'Failed to create challenge'}), 500

2. Example: E-commerce Checkout

Here's an example flow integrating Humanmark verification into an e-commerce checkout:

Frontend Implementation

The frontend initiates the verification process and submits the receipt with the checkout:

checkout.js
import { HumanmarkSdk, ErrorCode } from '@humanmark/sdk-js';

async function handleCheckout(items, paymentMethod) {
  try {
    // Step 1: Get a challenge token from your backend
    const challengeResponse = await fetch('/api/create-humanmark-challenge', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' }
    });
    
    const { token } = await challengeResponse.json();
    
    // Step 2: Initialize SDK and verify human
    const sdk = new HumanmarkSdk({
      apiKey: 'YOUR_PUBLIC_KEY',
      challengeToken: token
    });
    
    const receipt = await sdk.verify();
    
    // Step 3: Complete checkout with receipt
    const checkoutResponse = await fetch('/api/checkout', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        items,
        paymentMethod,
        receipt
      })
    });
    
    const result = await checkoutResponse.json();
    
    if (result.success) {
      window.location.href = '/order-confirmation/' + result.orderId;
    } else {
      showError(result.error);
    }
  } catch (error) {
    if (error.code === ErrorCode.USER_CANCELLED) {
      showMessage('Verification cancelled');
    } else {
      showError('Checkout failed. Please try again.');
    }
  }
}

Backend Verification

Your backend verifies the receipt and processes the checkout:

checkout.py
# E-commerce checkout with human verification
@app.route('/api/checkout', methods=['POST'])
def checkout():
    try:
        data = request.json
        items = data['items']
        payment_method = data['paymentMethod']
        receipt = data['receipt']
        
        # Step 1: Verify the Humanmark receipt
        decoded = jwt.decode(
            receipt, 
            os.environ['HUMANMARK_API_SECRET'],
            algorithms=['HS256']
        )
        
        # Step 2: Check challenge validity
        challenge = db.get_challenge(decoded['sub'])
        if not challenge or challenge['verified']:
            return jsonify({
                'success': False,
                'error': 'Invalid or used verification'
            }), 400
        
        # Step 3: Mark challenge as used
        db.mark_challenge_as_verified(decoded['sub'])
        
        # Step 4: Process the actual request
        order = db.create_order({
            'userId': request.user['id'],
            'items': items,
            'paymentMethod': payment_method
        })
        
        payment = process_payment({
            'orderId': order['id'],
            'amount': order['total'],
            'method': payment_method
        })
        
        return jsonify({
            'success': True,
            'orderId': order['id'],
            'message': 'Order placed successfully'
        })

    except Exception as e:
        print(f'Checkout error: {e}')
        return jsonify({'error': 'Checkout failed'}), 500

3. Example: Comment Submission

Here's how to protect comment forms with human verification:

Frontend Implementation

The frontend handles verification before submitting the comment:

comments.js
import { HumanmarkSdk, ErrorCode } from '@humanmark/sdk-js';

async function submitComment(postId, content) {
  try {
    // Step 1: Get a challenge token from your backend
    const challengeResponse = await fetch('/api/create-humanmark-challenge', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' }
    });
    
    const { token } = await challengeResponse.json();
    
    // Step 2: Initialize SDK and verify human
    const sdk = new HumanmarkSdk({
      apiKey: 'YOUR_PUBLIC_KEY',
      challengeToken: token
    });
    
    const receipt = await sdk.verify();
    
    // Step 3: Submit comment with receipt
    const response = await fetch('/api/comments', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ postId, content, receipt })
    });
    
    const result = await response.json();
    if (result.success) {
      addCommentToUI(result.comment);
      clearCommentForm();
    }
  } catch (error) {
    if (error.code === ErrorCode.USER_CANCELLED) {
      console.log('User cancelled verification');
    } else {
      console.error('Failed to submit comment:', error);
    }
  }
}

Backend Verification

Your backend verifies the receipt and creates the comment:

comments.py
# Comment submission with human verification
@app.route('/api/comments', methods=['POST'])
def submit_comment():
    try:
        data = request.json
        post_id = data['postId']
        content = data['content']
        receipt = data['receipt']
        
        # Step 1: Verify the Humanmark receipt
        decoded = jwt.decode(
            receipt,
            os.environ['HUMANMARK_API_SECRET'],
            algorithms=['HS256']
        )
        
        # Step 2: Check challenge validity
        challenge = db.get_challenge(decoded['sub'])
        if not challenge or challenge['verified']:
            return jsonify({
                'success': False,
                'error': 'Invalid or used verification'
            }), 400
        
        # Step 3: Mark challenge as used
        db.mark_challenge_as_verified(decoded['sub'])
        
        # Step 4: Process the actual request
        comment = db.create_comment({
            'postId': post_id,
            'content': content,
            'authorId': request.user.get('id')
        })
        
        return jsonify({
            'success': True,
            'comment': comment
        })
        
    except Exception as e:
        print(f'Comment error: {e}')
        return jsonify({'error': 'Failed to post comment'}), 500

Next Steps

Ready to integrate Humanmark?

Humanmark is currently in beta.

To get started, email us at sales@humanmark.io and we'll help you integrate Humanmark into your application.