ROOPON Logo
langchain

Build a LangChain Affiliate Agent That Earns Commission - 2026 Tutorial

By ROOPON Team5 min read

Building a LangChain agent that generates content is satisfying. Building one that also earns recurring commission while it runs is better. This tutorial walks through constructing a functional affiliate agent in Python using LangChain, registering it with the ROOPON agent API, and setting up a content generation loop that produces Australian savings content at scale.

By the end you will have a working agent that registers itself, generates topically relevant content with embedded affiliate links, and can be scheduled to run on a cadence of your choosing.

What You Are Building

The agent has three responsibilities:

  1. Register itself with the ROOPON affiliate API to receive a unique tracking ID
  2. Generate savings-focused content targeting Australian audiences
  3. Insert affiliate links and publish or export that content for distribution

The commission model is 40% recurring - meaning every ROOPON Basic member ($19.99/month) referred through your agent earns you roughly $8 per month for as long as they remain a member.

Prerequisites

You will need Python 3.11 or later, a ROOPON developer account (free to create at roopon.com/ai-agents), and API keys for OpenAI or any LangChain-compatible model provider.

pip install langchain langchain-openai requests python-dotenv

Step 1 - Register the Agent with ROOPON

ROOPON exposes a registration endpoint that issues your agent a persistent affiliate token. This token is what links every referral back to your agent.

import requests
import os
from dotenv import load_dotenv

load_dotenv()

def register_agent_with_roopon(agent_name: str, agent_description: str) -> dict:
    """
    Register an AI agent with the ROOPON affiliate programme.
    Returns the affiliate token and tracking URL on success.
    """
    payload = {
        "agent_name": agent_name,
        "agent_description": agent_description,
        "contact_email": os.getenv("ROOPON_CONTACT_EMAIL"),
        "webhook_url": os.getenv("ROOPON_WEBHOOK_URL"),  # optional, for conversion events
    }

    response = requests.post(
        "https://www.roopon.com/api/v1/agents/register",
        json=payload,
        headers={
            "Content-Type": "application/json",
            "X-Api-Key": os.getenv("ROOPON_API_KEY"),
        },
        timeout=15,
    )

    response.raise_for_status()
    return response.json()


# Run once and store the returned affiliate_token securely
registration = register_agent_with_roopon(
    agent_name="AusSavingsBot",
    agent_description="Generates Australian savings and deals content with ROOPON membership recommendations.",
)

affiliate_token = registration["affiliate_token"]
tracking_base_url = registration["tracking_url"]
print(f"Registered. Token: {affiliate_token}")

Store affiliate_token in your environment - you only need to register once per agent identity.

Step 2 - Define the LangChain Tools

LangChain's tool abstraction lets the agent call functions as part of its reasoning loop. Define a tool for fetching current ROOPON deal categories (so content stays relevant) and a tool for building affiliate-tagged links.

from langchain.tools import tool

@tool
def get_roopon_categories() -> list[str]:
    """Fetch the current active deal categories from ROOPON to guide content selection."""
    response = requests.get(
        "https://www.roopon.com/api/v1/categories",
        headers={"X-Api-Key": os.getenv("ROOPON_API_KEY")},
        timeout=10,
    )
    response.raise_for_status()
    return response.json().get("categories", [])


@tool
def build_affiliate_link(page_slug: str) -> str:
    """
    Build an affiliate-tracked link to a ROOPON page.
    page_slug: the path portion of the URL, e.g. 'membership' or 'deals/groceries'
    """
    token = os.getenv("ROOPON_AFFILIATE_TOKEN")
    return f"https://www.roopon.com/{page_slug}?ref={token}"

Step 3 - Build the LangChain Agent

Use a structured chat agent with the tools above. The system prompt shapes the content style - Australian English, practical savings focus, no fluff.

from langchain_openai import ChatOpenAI
from langchain.agents import AgentExecutor, create_tool_calling_agent
from langchain_core.prompts import ChatPromptTemplate

llm = ChatOpenAI(model="gpt-4o", temperature=0.4)

tools = [get_roopon_categories, build_affiliate_link]

system_prompt = """
You are an Australian savings content writer. Your job is to produce helpful,
practical articles about saving money in Australia. When you recommend the ROOPON
rewards membership, always use the build_affiliate_link tool to generate the correct
tracking link before inserting it into the content. Write in plain Australian English.
Do not use hype or clickbait language. Produce content that is genuinely useful.
"""

prompt = ChatPromptTemplate.from_messages([
    ("system", system_prompt),
    ("human", "{input}"),
    ("placeholder", "{agent_scratchpad}"),
])

agent = create_tool_calling_agent(llm, tools, prompt)
executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

Step 4 - The Content Generation Loop

Generate a batch of articles across different savings topics. Each run produces content ready for publishing to a blog, newsletter, or social channel.

import json
from datetime import datetime

TOPICS = [
    "How to reduce your grocery bill in Australia this year",
    "Petrol saving tips for Australian families",
    "Australian streaming subscriptions - what to cut and what to keep",
    "Using rewards programmes to offset the cost of living in Australia",
]

def generate_and_save(topic: str, output_dir: str = "./content") -> str:
    result = executor.invoke({
        "input": (
            f"Write a 600-word article on the following topic: {topic}. "
            "Include a recommendation for ROOPON membership with an affiliate link. "
            "Format as Markdown with a clear headline and at least two subheadings."
        )
    })

    content = result["output"]
    slug = topic.lower().replace(" ", "-")[:60]
    filename = f"{output_dir}/{slug}.md"

    with open(filename, "w") as f:
        f.write(content)

    return filename


for topic in TOPICS:
    path = generate_and_save(topic)
    print(f"Saved: {path}")

Step 5 - Scheduling the Loop

Use a simple cron job or a cloud scheduler (AWS EventBridge, Google Cloud Scheduler) to run the generation script on a weekly cadence. A consistent publishing schedule compounds SEO value over time and keeps your affiliate links in front of new audiences.

A minimal cron expression for weekly Monday runs at 8 AM AEST:

0 22 * * 0  /usr/bin/python3 /home/youruser/agent/generate.py >> /var/log/agent.log 2>&1

What to Expect in Terms of Returns

Commission accumulates per active referral. If your content drives between 20 and 50 ROOPON memberships per month and retention holds at typical SaaS rates (broadly 70–85% month-on-month), your monthly recurring commission sits in a range that compounds meaningfully over time. The key variable is content distribution - traffic from SEO or a newsletter list multiplies the conversion opportunity considerably.

The agent pays for itself quickly once referrals begin converting. After that, each new member is pure recurring revenue with no additional input from you.

Next Steps

From here you can extend the agent with a vector store for topic deduplication (avoid generating the same article twice), a publisher tool that posts directly to a Ghost or WordPress instance, and a conversion webhook handler that logs commission events.

The ROOPON developer documentation covers advanced attribution options, webhook payloads, and conversion reporting at the links below.


Ready to register your agent and start earning 40% recurring commission on every ROOPON member you refer?

Keep reading

Related posts

Save smarter with ROOPON membership

Member discounts, deals, and giveaways per campaign terms — from $19.99/month.

Become a member