Voting Callback API Integration Guide

Overview

Whenever a user casts a vote, our system will make a callback POST request to a specified URL on your end. This guide helps you set up your endpoint to receive and process these callbacks.

Each user is limited to 1 vote every 4 hours, we have multiple layers of bot and fraud detection in place to keep the integrity of the toplist in place. If you feel there is foul play at hand, please contact the staff team right away.

Generating Links

When generating a custom link for your user, you will want to include the parameter uid in the link. Below is an example of such:

https://merchants.to/vote/CATEGORY/MERCHANT_ID/USER_ID

So for the sake of example, we will say "merchants" is an "automation" provider. So our link would look like:

https://merchants.to/vote/automation/merchants/jaysue

Or if "merchants" was a "casinos" provider, our link would look like:

https://merchants.to/vote/casinos/merchants/jaysue

Now once jaysue has succesfully voted, we will post to "merchants" endpoint, stating such.

* Note: For discord link generation, we suggest using Discord IDs instead of discord names, as they will always be the same.
Request Details
HTTP Method:
  • POST
Headers:
  • Content-type: application/x-www-form-urlencoded
Parameters:
  • uid:
    • The ID of the user who voted.
  • voted:
    • Always set to "true".
  • api_key:
    • Your unique API key for authentication.
Code Examples
* Always audit your code after integrating. These are simple examples to help you build your end point. Merchants.to holds no liability.

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    
    // Define your API key (You will provide this to us)
    $api_key = "YOUR_API_KEY_HERE";

    // Check if the 'key' POST parameter is set and matches the API key
    if (!isset($_POST['key']) || $_POST['key'] !== $api_key) {
        die("Invalid API key.");
    }

    // Retrieve the POST data
    $uid = isset($_POST['uid']) ? $_POST['uid'] : '';
    $voted = isset($_POST['voted']) ? $_POST['voted'] : '';

    // Database connection details
    $host = "localhost";
    $user = "root";
    $password = "";
    $database = "callback_test";

    // Create a database connection
    $connection = new mysqli($host, $user, $password, $database);

    // Check the connection
    if ($connection->connect_error) {
        die("Connection failed: " . $connection->connect_error);
    }

    // Insert the data into the database
    $insert_sql = "INSERT INTO callback_data (uid, voted) VALUES (?, ?)";
    $statement = $connection->prepare($insert_sql);
    $statement->bind_param("ss", $uid, $voted);

    if ($statement->execute()) {
        echo "Data inserted into the database.";
    } else {
        echo "Error: " . $connection->error;
    }

    // Close the database connection
    $statement->close();
    $connection->close();
} else {
    // Handle invalid requests
    echo "Invalid request method.";
}

                                

from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
import os

app = Flask(__name__)

# Configuration

# Define your API key (You will provide this to us)
API_KEY = "YOUR_API_KEY_HERE"
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:@localhost/callback_test'

db = SQLAlchemy(app)

class CallbackData(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    uid = db.Column(db.String(80))
    voted = db.Column(db.String(80))

@app.route('/', methods=['POST'])
def callback():
    if request.method == 'POST':
        # Check API key
        key = request.form.get('key')
        if key != API_KEY:
            return "Invalid API key.", 403

        # Retrieve POST data
        uid = request.form.get('uid', '')
        voted = request.form.get('voted', '')

        # Insert data into the database
        entry = CallbackData(uid=uid, voted=voted)
        db.session.add(entry)
        try:
            db.session.commit()
            return "Data inserted into the database."
        except Exception as e:
            return f"Error: {str(e)}", 500
    else:
        return "Invalid request method.", 405

if __name__ == '__main__':
    if not os.path.exists('db.sqlite'):
        db.create_all()
    app.run(debug=True)    

                                

const express = require('express');
const bodyParser = require('body-parser');
const mysql = require('mysql');

const app = express();
const port = 3000;

// Define your API key (You will provide this to us)
const API_KEY = 'YOUR_API_KEY_HERE';

// Middleware to parse POST request bodies
app.use(bodyParser.urlencoded({ extended: true }));

// Database configuration
const dbConfig = {
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'callback_test'
};

const connection = mysql.createConnection(dbConfig);

// Check database connection
connection.connect(err => {
    if (err) {
        console.error('Connection failed:', err.stack);
        return;
    }
    console.log('Connected to the database.');
});

app.post('/', (req, res) => {
    const key = req.body.key;

    if (key !== API_KEY) {
        return res.send('Invalid API key.');
    }

    const uid = req.body.uid || '';
    const voted = req.body.voted || '';

    const query = 'INSERT INTO callback_data (uid, voted) VALUES (?, ?)';
    connection.query(query, [uid, voted], (err, results) => {
        if (err) {
            return res.send('Error: ' + err.message);
        }
        res.send('Data inserted into the database.');
    });
});

app.all('*', (req, res) => {
    res.send('Invalid request method.');
});

app.listen(port, () => {
    console.log(`Server is running on https://merchants.to:${port}`);
});

                                

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class CallbackServlet extends HttpServlet {

    // Define your API key (You will provide this to us)
    private static final String API_KEY = "YOUR_API_KEY_HERE";
    
    private static final String DB_URL = "jdbc:mysql://localhost:3306/callback_test";
    private static final String DB_USER = "root";
    private static final String DB_PASSWORD = "";

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        
        // Check API Key
        String key = req.getParameter("key");
        if (key == null || !API_KEY.equals(key)) {
            resp.getWriter().write("Invalid API key.");
            return;
        }

        // Retrieve POST parameters
        String uid = req.getParameter("uid");
        String voted = req.getParameter("voted");

        uid = uid == null ? "" : uid;
        voted = voted == null ? "" : voted;

        // Insert into database
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            try (Connection connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD)) {
                String sql = "INSERT INTO callback_data (uid, voted) VALUES (?, ?)";
                try (PreparedStatement statement = connection.prepareStatement(sql)) {
                    statement.setString(1, uid);
                    statement.setString(2, voted);
                    statement.executeUpdate();
                    resp.getWriter().write("Data inserted into the database.");
                }
            }
        } catch (Exception e) {
            resp.getWriter().write("Error: " + e.getMessage());
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().write("Invalid request method.");
    }
}

                                

package main

import (
    "database/sql"
    "fmt"
    "log"
    "net/http"
    "strings"

    _ "github.com/go-sql-driver/mysql"
)

// Define your API key (You will provide this to us)
const API_KEY = "YOUR_API_KEY_HERE"

var db *sql.DB

func main() {
    var err error
    dataSourceName := "root:@tcp(localhost:3306)/callback_test"
    db, err = sql.Open("mysql", dataSourceName)
    if err != nil {
        log.Fatal(err)
    }

    defer db.Close()

    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}

func handler(w http.ResponseWriter, r *http.Request) {
    if r.Method != http.MethodPost {
        fmt.Fprint(w, "Invalid request method.")
        return
    }

    if key := r.FormValue("key"); key != API_KEY {
        fmt.Fprint(w, "Invalid API key.")
        return
    }

    uid := strings.TrimSpace(r.FormValue("uid"))
    voted := strings.TrimSpace(r.FormValue("voted"))

    stmt, err := db.Prepare("INSERT INTO callback_data (uid, voted) VALUES (?, ?)")
    if err != nil {
        http.Error(w, "Error preparing the statement.", http.StatusInternalServerError)
        return
    }

    defer stmt.Close()

    _, err = stmt.Exec(uid, voted)
    if err != nil {
        http.Error(w, "Error: "+err.Error(), http.StatusInternalServerError)
        return
    }

    fmt.Fprint(w, "Data inserted into the database.")
}    

                                

#!/usr/bin/perl

use strict;
use warnings;

use CGI;
use DBI;

my $cgi = CGI->new;

if ($cgi->request_method() eq 'POST') {
    
    # Define your API key (You will provide this to us)
    my $api_key = "YOUR_API_KEY_HERE";

    # Check if the 'key' POST parameter is set and matches the API key
    my $key = $cgi->param('key');
    unless (defined $key && $key eq $api_key) {
        die("Invalid API key.");
    }

    # Retrieve the POST data
    my $uid = $cgi->param('uid') || '';
    my $voted = $cgi->param('voted') || '';

    # Database connection details
    my $dsn = "DBI:mysql:database=callback_test;host=localhost";
    my $user = "root";
    my $password = "";

    # Create a database connection
    my $dbh = DBI->connect($dsn, $user, $password, { RaiseError => 1, AutoCommit => 0 }) 
        or die("Connection failed: $DBI::errstr");

    # Insert the data into the database
    my $insert_sql = "INSERT INTO callback_data (uid, voted) VALUES (?, ?)";
    my $sth = $dbh->prepare($insert_sql);

    $sth->bind_param(1, $uid);
    $sth->bind_param(2, $voted);

    if ($sth->execute()) {
        print "Content-type: text/plain\n\n";
        print "Data inserted into the database.";
    } else {
        print "Content-type: text/plain\n\n";
        print "Error: " . $dbh->errstr;
    }

    # Close the database connection
    $sth->finish();
    $dbh->disconnect();
    
} else {
    # Handle invalid requests
    print "Content-type: text/plain\n\n";
    print "Invalid request method.";
}       

                                
Callback Test

Test to see if your callback end point is working.

Reminder
Always validate the API key to ensure the authenticity of the request. Do not expose the callback endpoint to the public; it should only be accessible to merchants.to operators.