### Install Refgrow Tracking Script
Source: https://refgrow.com/docs/quickstart
Add this script to the `
` section of your website to enable Refgrow tracking. Replace 'YOUR_PROJECT_ID' with your actual project ID from the Refgrow dashboard.
```html
```
--------------------------------
### Example Multilevel Commission Setup
Source: https://refgrow.com/docs/multilevel
Demonstrates a sample configuration for a 4-level commission structure, including commission rates, durations, conditions, and the outcome of a sale for a Gold affiliate. It also highlights the automatic upgrade mechanism.
```text
Level 1 - Starter: 5% lifetime
Condition: Amount threshold, $0+ (total)
Level 2 - Bronze: 7% for 6 months
Condition: Amount threshold, $100+ (total)
Level 3 - Silver: 10% lifetime
Condition: Amount threshold, $500+ (total)
Level 4 - Gold: 15% lifetime
Condition: Referral count, 10+ referrals (total)
Result when Gold affiliate sells $100:
- Gold affiliate earns: $15 (15% commission)
- Automatic upgrade when affiliate reaches next threshold
```
--------------------------------
### Add Refgrow Tracking Script to Website
Source: https://refgrow.com/docs/tracking
Include the Refgrow tracking script in your HTML to enable referral and conversion tracking. This script should be placed before the closing `` tag for optimal performance.
```html
```
--------------------------------
### Track User Registrations with Refgrow
Source: https://refgrow.com/docs/quickstart
Call this JavaScript function after a successful user signup to track referred users creating accounts. Replace 'user@example.com' with the actual user's email address.
```javascript
Refgrow(0, 'signup', 'user@example.com');
```
--------------------------------
### Example JSON Response for Get Affiliate
Source: https://refgrow.com/docs/api-reference
This is an example of a successful JSON response (200 OK) when retrieving affiliate data. It provides details such as user email, referral code, earnings, creation date, and current status.
```json
{
"success": true,
"data": {
"id": 123,
"user_email": "affiliate1@example.com",
"referral_code": "REF123",
"created_at": "2024-01-15T10:00:00.000Z",
"status": "active",
"clicks": 58,
"signups": 12,
"purchases": 5,
"unpaid_earnings": "50.00",
"total_earnings": "150.00"
}
}
```
--------------------------------
### HTML: Basic Page Example with Refgrow Widget
Source: https://refgrow.com/docs/widget
A complete HTML page example demonstrating the integration of the Refgrow affiliate widget. Includes basic structure, navigation, and the widget's script.
```html
My Affiliate Program
Join Our Affiliate Program
```
--------------------------------
### Embed Refgrow Affiliate Dashboard (With User Email)
Source: https://refgrow.com/docs/quickstart
Embed this HTML code to display the affiliate dashboard for logged-in users, allowing them to track performance and earnings. Ensure 'user@example.com' is replaced with the actual user's email.
```html
```
--------------------------------
### Webhook Setup and Usage
Source: https://refgrow.com/docs/webhooks
This section covers the process of setting up webhooks, including creating them, testing, and understanding the payload format and signature verification.
```APIDOC
## Webhooks API
### Description
Refgrow's webhook system allows you to receive HTTP POST notifications about important events in your affiliate program. This enables you to integrate Refgrow with your internal systems for automated conversion processing, notifications, and analytics.
__**Security:** All webhooks are signed with HMAC-SHA256 signatures for authenticity verification.
### Supported Events
- `referral_signed_up`: New user signed up via referral link.
- `referral_converted`: Referral converted to paying customer.
- `referral_canceled`: Conversion canceled or refunded.
### Setting up Webhooks
1. **Creating a Webhook**
- Navigate to Project Settings → "Webhooks" tab.
- Click "Add Webhook".
- Enter your endpoint URL (e.g., `https://yourapp.com/webhooks/refgrow`).
- Select the events you want to receive.
- Optional: Generate a secret key for signature verification.
- Save the settings.
2. **Testing Your Webhook**
- In the webhooks table, click the test button next to your webhook.
- Select the event type to test.
- Click "Send Test".
- Check the delivery status and server response.
__**Important:** Your endpoint must respond with HTTP status 200-299 for successful delivery.
### Payload Format
Webhooks are sent as HTTP POST requests with a JSON payload.
#### Request Headers
- `Content-Type: application/json`
- `User-Agent: Refgrow-Webhooks/1.0`
- `X-Refgrow-Event: [Event Type]`
- `X-Refgrow-Signature: sha256=abc123...` (if signature is configured)
#### Payload Structure
##### `referral_signed_up` Example
```json
{
"event": "referral_signed_up",
"timestamp": 1703123456,
"project_id": "123",
"referrer": {
"id": "456",
"email": "affiliate@example.com"
},
"referred": {
"id": "789",
"email": "customer@example.com"
},
"data": {
"referral_code": "REF123",
"signup_date": "2024-01-15T10:00:00Z",
"user_agent": "Mozilla/5.0...",
"ip_address": "192.168.1.1"
}
}
```
##### `referral_converted` Example
```json
{
"event": "referral_converted",
"timestamp": 1703123456,
"project_id": "123",
"referrer": {
"id": "456",
"email": "affiliate@example.com"
},
"referred": {
"id": "789",
"email": "customer@example.com"
},
"conversion": {
"id": "conv_123",
"amount": 99.99,
"currency": "USD",
"commission_amount": 19.99,
"commission_type": "percentage",
"commission_rate": 20,
"payment_processor": "stripe",
"product_id": "prod_abc123",
"order_id": "order_456",
"conversion_date": "2024-01-15T10:30:00Z"
}
}
```
##### `referral_canceled` Example
```json
{
"event": "referral_canceled",
"timestamp": 1703123456,
"project_id": "123",
"referrer": {
"id": "456",
"email": "affiliate@example.com"
},
"referred": {
"id": "789",
"email": "customer@example.com"
},
"conversion": {
"id": "conv_123",
"amount": 99.99,
"commission_amount": 19.99,
"refund_amount": 99.99,
"reason": "Customer requested refund",
"canceled_date": "2024-01-16T14:20:00Z"
}
}
```
### Signature Verification
If a secret key is configured, webhooks include an HMAC-SHA256 signature in the `X-Refgrow-Signature` header.
#### Signature Verification (PHP)
```php
```
#### Signature Verification (Node.js)
```javascript
const crypto = require('crypto');
function verifySignature(payload, signature, secret) {
const expectedSignature = 'sha256=' + crypto
.createHmac('sha256', secret)
.update(payload, 'utf8')
.digest('hex');
return crypto.timingSafeEqual(
Buffer.from(expectedSignature),
Buffer.from(signature)
);
}
// Express middleware
app.use('/webhooks/refgrow', express.raw({type: 'application/json'}), (req, res) => {
const signature = req.headers['x-refgrow-signature'];
const secret = process.env.REFGROW_WEBHOOK_SECRET;
if (!verifySignature(req.body, signature, secret)) {
return res.status(401).send('Invalid signature');
}
// Process webhook
const event = JSON.parse(req.body);
console.log('Received event:', event.event);
res.status(200).send('OK');
});
```
```
--------------------------------
### EJS: Server-Side Dynamic Example with Refgrow Widget
Source: https://refgrow.com/docs/widget
Server-side integration example using Node.js and EJS to dynamically render the Refgrow widget based on user authentication status. It uses environment variables for sensitive data.
```html
Affiliate Program - <%= siteName %>
Our Affiliate Program
<% if (user) { %>
<% } else { %>
<% } %>
```
--------------------------------
### Example Commission Calculation
Source: https://refgrow.com/docs/multi-tier
This example demonstrates how commissions are calculated in a two-tier system. It shows the breakdown of earnings for both the Tier 2 affiliate and their Tier 1 parent based on a sale amount and defined commission rates.
```text
Standard Commission: 30% lifetime
Tier 2 Commission: 10% lifetime
Result when Tier 2 affiliate sells $100:
- Tier 2 affiliate earns: $30 (standard commission)
- Tier 1 parent earns: $10 (additional tier 2 commission)
```
--------------------------------
### Manually Track Conversions with Refgrow
Source: https://refgrow.com/docs/tracking
Use the Refgrow JavaScript function to manually track conversions such as signups and purchases. This function requires the conversion value, type, and the user's email address. Ensure the tracking script has loaded before calling this function.
```javascript
// Track a signup
Refgrow(0, 'signup', 'user@example.com');
// Track a purchase
Refgrow(99.99, 'purchase', 'user@example.com');
```
--------------------------------
### Webhook Payload Structure Examples
Source: https://refgrow.com/docs/webhooks
Examples of JSON payloads for different webhook events: referral_signed_up, referral_converted, and referral_canceled. These structures define the data sent with each notification.
```json
{
"event": "referral_signed_up",
"timestamp": 1703123456,
"project_id": "123",
"referrer": {
"id": "456",
"email": "affiliate@example.com"
},
"referred": {
"id": "789",
"email": "customer@example.com"
},
"data": {
"referral_code": "REF123",
"signup_date": "2024-01-15T10:00:00Z",
"user_agent": "Mozilla/5.0...",
"ip_address": "192.168.1.1"
}
}
```
```json
{
"event": "referral_converted",
"timestamp": 1703123456,
"project_id": "123",
"referrer": {
"id": "456",
"email": "affiliate@example.com"
},
"referred": {
"id": "789",
"email": "customer@example.com"
},
"conversion": {
"id": "conv_123",
"amount": 99.99,
"currency": "USD",
"commission_amount": 19.99,
"commission_type": "percentage",
"commission_rate": 20,
"payment_processor": "stripe",
"product_id": "prod_abc123",
"order_id": "order_456",
"conversion_date": "2024-01-15T10:30:00Z"
}
}
```
```json
{
"event": "referral_canceled",
"timestamp": 1703123456,
"project_id": "123",
"referrer": {
"id": "456",
"email": "affiliate@example.com"
},
"referred": {
"id": "789",
"email": "customer@example.com"
},
"conversion": {
"id": "conv_123",
"amount": 99.99,
"commission_amount": 19.99,
"refund_amount": 99.99,
"reason": "Customer requested refund",
"canceled_date": "2024-01-16T14:20:00Z"
}
}
```
--------------------------------
### Fixed-Period Subscription Commission Example
Source: https://refgrow.com/docs/commissions
Illustrates earnings for a subscription product over a specified duration with a percentage-based commission. This example details the monthly earnings and total earnings over the fixed period.
```example
Monthly Subscription: $50
Commission Rate: 15%
Monthly Affiliate Earnings: $7.50
Duration: 6 months
Total Earnings: $45
```
--------------------------------
### Minimum Payout Threshold Example
Source: https://refgrow.com/docs/commissions
Demonstrates the concept of a minimum payout threshold for affiliates. Affiliates must reach this earnings amount before they are eligible to receive payments, helping to streamline the payout process.
```example
Example: $50 minimum payout threshold
An affiliate must earn at least $50 before they can receive a payment.
```
--------------------------------
### Webhook Payload Example - Payment Completed
Source: https://refgrow.com/docs/dodo
This JSON object represents an example payload for a 'payment.completed' webhook event. It includes details about the payment, customer, product, and associated metadata such as the referral code.
```json
{
"type": "payment.completed",
"data": {
"payment": {
"id": "pay_123456789",
"amount": 2900,
"currency": "USD",
"discount_amount": 0,
"tax_amount": 290
},
"customer": {
"email": "customer@example.com"
},
"product": {
"id": "prod_123456789"
},
"metadata": {
"referral_code": "ABC123"
},
"discount": {
"code": "SAVE10"
}
}
}
```
--------------------------------
### Webhook Payload Example (JSON)
Source: https://refgrow.com/docs/polar
An example of the JSON payload structure for a subscription creation event. This payload is crucial for tracking referral codes and calculating commissions.
```json
{
"type": "subscription.created",
"data": {
"subscription": {
"id": "sub_123456789",
"customer": {
"email": "customer@example.com"
},
"price": {
"amount": 2900,
"currency": "USD"
},
"product": {
"id": "prod_123456789"
},
"metadata": {
"referral_code": "ABC123"
}
}
}
}
```
--------------------------------
### List Affiliates - Ruby
Source: https://refgrow.com/docs/api-reference
Provides a Ruby example for listing affiliates using the Net::HTTP library. It constructs the URI with query parameters, sets the Authorization header, and parses the JSON response. Suitable for Ruby-based backend services.
```ruby
require 'net/http'
require 'uri'
require 'json'
uri = URI('https://refgrow.com/api/v1/affiliates')
uri.query = URI.encode_www_form(limit: 10, status: 'active')
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Get.new(uri)
request['Authorization'] = 'Bearer YOUR_API_KEY'
response = http.request(request)
data = JSON.parse(response.body)
puts data
```
--------------------------------
### Embed Refgrow Affiliate Dashboard (Without User Email)
Source: https://refgrow.com/docs/quickstart
Embed this HTML code to display the affiliate dashboard when users need to enter their email to access it. The dashboard handles user authentication automatically.
```html
```
--------------------------------
### Apply Custom CSS for Dashboard Styling
Source: https://refgrow.com/docs/customization
This snippet demonstrates how to apply custom CSS to style the affiliate dashboard. It includes examples for styling the header, stat cards, and hover effects. Custom CSS is available for Pro and Business plan users.
```css
.dashboard-header {
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
.stat-card {
border-radius: 10px;
transition: transform 0.2s;
}
.stat-card:hover {
transform: translateY(-5px);
}
```
--------------------------------
### Example JSON Response for Update Affiliate
Source: https://refgrow.com/docs/api-reference
This is an example of a successful JSON response (200 OK) after updating an affiliate's details. It includes the updated status and core affiliate fields. Note that calculated fields like earnings are typically not returned on an update operation.
```json
{
"success": true,
"data": {
"id": 123,
"user_email": "affiliate1@example.com",
"referral_code": "REF123",
"unpaid_earnings": null,
"total_earnings": null,
"created_at": "2024-01-15T10:00:00.000Z",
"status": "inactive"
}
}
```
--------------------------------
### Refgrow Widget Manual Recovery TypeScript Methods
Source: https://refgrow.com/docs/widget-troubleshooting
Demonstrates the TypeScript interface and usage for manually controlling the Refgrow widget's state. It includes methods for restoring, force-initializing, and resetting the widget, ensuring type safety in custom implementations.
```typescript
// TypeScript interface for Refgrow methods
interface RefgrowWidget {
restore(): void;
forceInit(): void;
reset(): void;
init(): void;
}
// Usage
declare global {
interface Window {
Refgrow: RefgrowWidget;
}
}
// Check and restore the widget
window.Refgrow.restore();
// Force re-initialization
window.Refgrow.forceInit();
```
--------------------------------
### Refgrow Widget Manual Recovery JavaScript Methods
Source: https://refgrow.com/docs/widget-troubleshooting
Provides JavaScript methods for manually restoring, force-initializing, or completely resetting and re-initializing the Refgrow widget. These functions are useful for custom implementations requiring direct control over widget state.
```javascript
// Check and restore the widget
window.Refgrow.restore();
// Force re-initialization
window.Refgrow.forceInit();
// Complete reset and re-initialization
window.Refgrow.reset();
window.Refgrow.init();
```
--------------------------------
### GET /api/v1/coupons
Source: https://refgrow.com/docs/api-reference
Retrieves a list of coupons for your project. Supports pagination and filtering by status, affiliate, and coupon code.
```APIDOC
## GET /api/v1/coupons
### Description
Retrieves a list of coupons for your project. Supports pagination and filtering by status, affiliate, and coupon code.
### Method
GET
### Endpoint
/api/v1/coupons
### Parameters
#### Query Parameters
- **limit** (integer) - Optional - Number of coupons to return (default: 50).
- **offset** (integer) - Optional - Number of coupons to skip for pagination (default: 0).
- **status** (string) - Optional - Filter by status ('active' or 'inactive').
- **affiliate_id** (integer) - Optional - Filter by affiliate ID.
- **coupon_code** (string) - Optional - Filter by coupon code (partial match).
```
--------------------------------
### Shopify Refgrow Widget Section Load Monitor
Source: https://refgrow.com/docs/widget-troubleshooting
A JavaScript snippet for Shopify themes that listens for the `shopify:section:load` event. When a section loads, it attempts to restore the Refgrow widget using `window.Refgrow.restore()` after a 1-second delay. This helps ensure the widget is functional after theme section updates.
```javascript
{% comment %} Refgrow Widget Monitor {% endcomment %}
```
--------------------------------
### Enhanced Visibility Monitoring for Refgrow Widget
Source: https://refgrow.com/docs/widget-troubleshooting
Implements custom visibility monitoring for the Refgrow widget. It listens for the 'visibilitychange' event to restore the widget if it becomes empty and visible, and runs a periodic health check every 30 seconds to ensure the widget is restored if it appears empty. Dependencies include the global `window.Refgrow` object.
```javascript
// Enhanced visibility monitoring
document.addEventListener('visibilitychange', function() {
if (!document.hidden) {
// Page became visible
setTimeout(function() {
const element = document.getElementById('refgrow');
if (element && element.innerHTML.trim() === '' && window.Refgrow) {
console.log('Restoring empty Refgrow widget');
window.Refgrow.restore();
}
}, 1000);
}
});
// Periodic health check
function healthCheck() {
const element = document.getElementById('refgrow');
const isEmpty = !element || element.innerHTML.trim() === '';
if (isEmpty && window.Refgrow) {
console.warn('Refgrow widget appears empty, attempting restore...');
window.Refgrow.restore();
}
return !isEmpty;
}
// Run health check every 30 seconds
setInterval(healthCheck, 30000);
```
--------------------------------
### Refgrow Widget Integration in React
Source: https://refgrow.com/docs/widget-troubleshooting
This React component integrates the Refgrow widget, handling initialization, route changes, and visibility changes using useEffect hooks. It requires 'react' and the global Refgrow object to be available.
```javascript
import { useEffect } from 'react';
function RefgrowWidget({ projectId, userEmail }) {
useEffect(() => {
// Initialize widget when component mounts
const element = document.getElementById('refgrow');
if (element && window.Refgrow) {
window.Refgrow.forceInit();
}
}, []);
useEffect(() => {
// Check widget state on route changes
const timer = setTimeout(() => {
if (window.Refgrow) {
window.Refgrow.restore();
}
}, 500);
return () => clearTimeout(timer);
});
// Handle page visibility changes
useEffect(() => {
const handleVisibilityChange = () => {
if (!document.hidden && window.Refgrow) {
setTimeout(() => {
const element = document.getElementById('refgrow');
if (element && element.innerHTML.trim() === '') {
window.Refgrow.restore();
}
}, 1000);
}
};
document.addEventListener('visibilitychange', handleVisibilityChange);
return () => {
document.removeEventListener('visibilitychange', handleVisibilityChange);
};
}, []);
return (
);
}
```
--------------------------------
### Debugging Refgrow Widget Status and Errors
Source: https://refgrow.com/docs/widget-troubleshooting
Provides utility functions to debug the Refgrow widget's status and monitor for errors. The `checkRefgrowStatus` function logs the Refgrow element, its content, and associated global objects to the console. An error listener captures and logs Refgrow-specific errors. Dependencies include the global `window.Refgrow` and `window.ReferralProgram` objects.
```javascript
// Debug widget status
function checkRefgrowStatus() {
const element = document.getElementById('refgrow');
console.log('Refgrow element:', element);
console.log('Element content:', element ? element.innerHTML : 'Not found');
console.log('Refgrow object:', window.Refgrow);
console.log('ReferralProgram object:', window.ReferralProgram);
}
// Run debug check
checkRefgrowStatus();
// Monitor for errors
window.addEventListener('error', function(e) {
if (e.message && e.message.includes('Refgrow')) {
console.error('Refgrow widget error:', e);
// Send error to your monitoring service
}
});
```
--------------------------------
### Delete Coupon using Ruby (Net::HTTP)
Source: https://refgrow.com/docs/api-reference
This Ruby example shows how to delete a coupon using the built-in Net::HTTP library. It constructs the URI, sets up the HTTP connection with SSL, creates a DELETE request with the Authorization header, and prints the response code.
```ruby
require 'net/http'
require 'uri'
uri = URI('https://refgrow.com/api/v1/coupons/1')
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Delete.new(uri)
request['Authorization'] = 'Bearer YOUR_API_KEY'
response = http.request(request)
puts response.code # "204"
```
--------------------------------
### Node.js Webhook Signature Verification
Source: https://refgrow.com/docs/webhooks
Node.js code snippet demonstrating how to verify webhook signatures using the `crypto` module. Includes an Express.js middleware example for handling incoming requests.
```javascript
const crypto = require('crypto');
function verifySignature(payload, signature, secret) {
const expectedSignature = 'sha256=' + crypto
.createHmac('sha256', secret)
.update(payload, 'utf8')
.digest('hex');
return crypto.timingSafeEqual(
Buffer.from(expectedSignature),
Buffer.from(signature)
);
}
// Express middleware
app.use('/webhooks/refgrow', express.raw({type: 'application/json'}), (req, res) => {
const signature = req.headers['x-refgrow-signature'];
const secret = process.env.REFGROW_WEBHOOK_SECRET;
if (!verifySignature(req.body, signature, secret)) {
return res.status(401).send('Invalid signature');
}
// Process webhook
const event = JSON.parse(req.body);
console.log('Received event:', event.event);
res.status(200).send('OK');
});
```
--------------------------------
### Fetch Referral by Email using cURL, Node.js, Python, PHP, Ruby
Source: https://refgrow.com/docs/api-reference
This section demonstrates how to fetch referral data for a specific customer email using various programming languages and cURL. It requires an API key for authentication and sends a GET request to the /api/v1/referrals/:email endpoint. The email address must be URL-encoded.
```curl
curl -X GET "https://refgrow.com/api/v1/referrals/customer1%40example.com" \
-H "Authorization: Bearer YOUR_API_KEY"
```
```node
const axios = require('axios');
const email = encodeURIComponent('customer1@example.com');
const response = await axios.get(`https://refgrow.com/api/v1/referrals/${email}`, {
headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
});
console.log(response.data);
```
```python
import requests
from urllib.parse import quote
email = quote('customer1@example.com')
url = f"https://refgrow.com/api/v1/referrals/{email}"
headers = {"Authorization": "Bearer YOUR_API_KEY"}
response = requests.get(url, headers=headers)
data = response.json()
print(data)
```
```php
$url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => $headers,
]);
$response = curl_exec($curl);
curl_close($curl);
$data = json_decode($response, true);
print_r($data);
?>
```
```ruby
require 'net/http'
require 'uri'
require 'json'
email = URI.encode_www_form_component('customer1@example.com')
uri = URI("https://refgrow.com/api/v1/referrals/#{email}")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Get.new(uri)
request['Authorization'] = 'Bearer YOUR_API_KEY'
response = http.request(request)
data = JSON.parse(response.body)
puts data
```
--------------------------------
### Refgrow Widget Integration in Angular
Source: https://refgrow.com/docs/widget-troubleshooting
This Angular component provides integration for the Refgrow widget, utilizing Angular's component lifecycle hooks and input properties. It ensures proper initialization and cleanup. Requires Angular framework and the global Refgrow object.
```typescript
import { Component, Input, OnInit, OnDestroy } from '@angular/core';
declare global {
interface Window {
Refgrow: any;
}
}
@Component({
selector: 'app-refgrow-widget',
template: '
'
})
export class RefgrowWidgetComponent implements OnInit, OnDestroy {
@Input() projectId!: string;
@Input() userEmail?: string;
private visibilityChangeHandler?: () => void;
ngOnInit() {
this.initWidget();
this.setupVisibilityListener();
}
ngOnDestroy() {
this.cleanup();
}
private initWidget() {
setTimeout(() => {
if (window.Refgrow) {
window.Refgrow.forceInit();
}
}, 100);
}
private restoreWidget() {
if (window.Refgrow) {
window.Refgrow.restore();
}
}
private setupVisibilityListener() {
this.visibilityChangeHandler = () => {
if (!document.hidden && window.Refgrow) {
setTimeout(() => {
const element = document.getElementById('refgrow');
if (element && element.innerHTML.trim() === '') {
window.Refgrow.restore();
}
}, 1000);
}
};
document.addEventListener('visibilitychange', this.visibilityChangeHandler);
}
private cleanup() {
if (this.visibilityChangeHandler) {
document.removeEventListener('visibilitychange', this.visibilityChangeHandler);
}
if (window.Refgrow) {
window.Refgrow.reset();
}
}
}
```
--------------------------------
### Refgrow Widget Automatic Recovery Script
Source: https://refgrow.com/docs/widget-troubleshooting
This script embeds the Refgrow affiliate widget and includes automatic recovery features to ensure it remains visible and functional across tab switches, SPAs, and window focus changes. It performs periodic health checks and detects page visibility changes.
```html
```
--------------------------------
### WordPress Refgrow Widget Monitoring
Source: https://refgrow.com/docs/widget-troubleshooting
A WordPress-specific PHP function that adds a JavaScript snippet to the footer of theme pages. This script uses jQuery to periodically check if the Refgrow widget (`#refgrow`) is empty and attempts to restore it using `window.Refgrow.restore()` every 10 seconds. It requires jQuery to be loaded.
```php
function refgrow_widget_monitor() {
?>
{
try {
const event = JSON.parse(req.body);
switch (event.event) {
case 'referral_signed_up':
await handleReferralSignup(event);
break;
case 'referral_converted':
await handleReferralConversion(event);
break;
case 'referral_canceled':
await handleReferralCancellation(event);
break;
default:
console.log('Unknown event type:', event.event);
}
res.status(200).json({ received: true });
} catch (error) {
console.error('Webhook error:', error);
res.status(400).send('Webhook Error');
}
});
async function handleReferralConversion(event) {
const { referrer, conversion } = event;
// Update stats in database
await db.updatePartnerStats(referrer.id, {
totalCommissions: conversion.commission_amount,
lastConversionDate: new Date()
});
// Send push notification
await sendPushNotification(referrer.email, {
title: 'New conversion!',
body: `You earned $${conversion.commission_amount}`
});
}
```
--------------------------------
### Embed Refgrow Affiliate Dashboard
Source: https://refgrow.com/docs/index
Embed the affiliate dashboard into your website. Option 1 is for when the user's email is known (e.g., logged in users). Option 2 is for when users need to enter their email.
```html
```
```html
```
--------------------------------
### Add Refgrow Tracking Script to Website
Source: https://refgrow.com/docs/lemonsqueezy
Include this JavaScript snippet in the `` of your website pages to enable Refgrow's tracking functionality. Ensure you replace 'YOUR_PROJECT_ID' with your actual Refgrow project ID. The script tracks user activity and referral codes for subsequent purchases.
```html
```
--------------------------------
### Create Affiliate
Source: https://refgrow.com/docs/api-reference
Creates a new affiliate for your project.
```APIDOC
## POST /api/v1/affiliates
### Description
Creates a new affiliate for your project.
### Method
POST
### Endpoint
/api/v1/affiliates
### Parameters
#### Request Body
(Details for request body fields would be specified here, e.g., user_email, etc.)
### Request Example
(Example request body for creating an affiliate would be provided here)
### Response
#### Success Response (201 Created)
(Details for the successful response, including the created affiliate object, would be provided here)
#### Response Example
(Example response body for a successful creation would be provided here)
#### Error Responses
- `400 Bad Request`: Invalid request body.
- `401 Unauthorized`: Missing or invalid API key.
- `403 Forbidden`: API key doesn't have permission to create an affiliate.
```
--------------------------------
### Multi-Currency Support
Source: https://refgrow.com/docs/lemonsqueezy
Information on how Refgrow handles multiple currencies in transactions.
```APIDOC
## Multi-Currency Support
Refgrow automatically handles different currencies from Lemon Squeezy:
* Commissions are calculated in the original transaction currency.
* Dashboard displays amounts in your project's configured currency.
* Conversion rates are handled automatically.
```
--------------------------------
### Retrieve Referral via GET Request
Source: https://refgrow.com/docs/api-reference
Describes how to retrieve a specific referral record by email using a GET request to the Refgrow API. The email is URL-encoded and included in the path. The API returns a JSON object containing the referral details.
```text
GET /api/v1/referrals/:email
```
--------------------------------
### Webhook Endpoint Configuration
Source: https://refgrow.com/docs/lemonsqueezy
Troubleshoot webhook issues by verifying your endpoint URL and secret.
```APIDOC
## Webhooks Not Working
1. Verify your webhook secret is correctly set in your project settings.
2. Check that the webhook endpoint was created with the correct URL: `https://refgrow.com/webhook/lemonsqueezy/{your-project-id}`.
3. Confirm all required events are enabled for the webhook.
4. Check your Lemon Squeezy dashboard for webhook delivery logs.
5. Ensure the webhook signature verification is working.
```
--------------------------------
### GET /api/v1/conversions/{id}
Source: https://refgrow.com/docs/api-reference
Retrieves details of a specific conversion by its ID.
```APIDOC
## GET /api/v1/conversions/{id}
### Description
Retrieves details of a specific conversion by its ID.
### Method
GET
### Endpoint
/api/v1/conversions/{id}
### Parameters
#### Path Parameters
- **id** (integer) - Required - The ID of the conversion to retrieve.
### Request Example
```json
{
"example": "curl -X GET \"https://refgrow.com/api/v1/conversions/1002\" \
-H \"Authorization: Bearer YOUR_API_KEY\""
}
```
### Response
#### Success Response (200)
- **success** (boolean) - Indicates if the request was successful.
- **data** (object) - Contains the conversion details.
- **id** (integer) - The unique identifier for the conversion.
- **type** (string) - The type of conversion (e.g., 'purchase', 'signup').
- **affiliate_id** (integer) - The ID of the affiliate associated with the conversion.
- **referred_user_id** (integer) - The ID of the user referred.
- **value** (number) - The value of the conversion.
- **base_value** (number) - The base value of the transaction.
- **base_value_currency** (string) - The currency of the base value.
- **paid** (boolean) - Indicates if the conversion has been paid out.
- **created_at** (string) - The timestamp when the conversion was created.
- **reference** (string) - A custom reference ID for the conversion.
- **coupon_code_used** (string or null) - The coupon code used, if any.
#### Response Example
```json
{
"success": true,
"data": {
"id": 1002,
"type": "purchase",
"affiliate_id": 123,
"referred_user_id": 501,
"value": 12.5,
"base_value": 250,
"base_value_currency": "USD",
"paid": false,
"created_at": "2024-07-29T13:05:00.000Z",
"reference": "ORDER-123",
"coupon_code_used": null
}
}
```
#### Error Responses
- `400 Bad Request`: Invalid conversion ID.
- `404 Not Found`: Conversion not found for this project.
```
--------------------------------
### Get Referrals by Email
Source: https://refgrow.com/docs/api-reference
Retrieves details of a referred user by their email address. This endpoint is useful for checking the status and details of a specific referral.
```APIDOC
## GET /api/v1/referrals/:email
### Description
Retrieves details of a referred user by their email address.
### Method
GET
### Endpoint
`/api/v1/referrals/:email`
### Parameters
#### Path Parameters
- **email** (string) - Required - The email address of the referred user.
### Request Example
```json
{
"example": "curl -X GET \"https://refgrow.com/api/v1/referrals/customer1%40example.com\" \
-H \"Authorization: Bearer YOUR_API_KEY\""
}
```
### Response
#### Success Response (200)
- **success** (boolean) - Indicates if the request was successful.
- **data** (object) - Contains the referral details.
- **id** (integer) - The unique identifier for the referral.
- **user_email** (string) - The email address of the referred user.
- **conversion_status** (string) - The current conversion status (e.g., 'converted', 'pending').
- **conversion_date** (string) - The date and time of conversion, if applicable.
- **created_at** (string) - The date and time the referral was created.
- **affiliate_id** (integer) - The ID of the affiliate associated with the referral.
- **affiliate_code** (string) - The code of the affiliate associated with the referral.
#### Response Example
```json
{
"success": true,
"data": {
"id": 501,
"user_email": "customer1@example.com",
"conversion_status": "converted",
"conversion_date": "2024-02-10T11:05:00.000Z",
"created_at": "2024-02-01T09:00:00.000Z",
"affiliate_id": 123,
"affiliate_code": "REF123"
}
}
```
#### Error Responses
- `400 Bad Request`: Invalid email format in URL.
- `404 Not Found`: Referred user not found for this project.
```
--------------------------------
### List Affiliates - PHP
Source: https://refgrow.com/docs/api-reference
Demonstrates how to fetch a list of affiliates in PHP using cURL. It constructs the URL with query parameters and sets the Authorization header. Useful for web applications built with PHP.
```php
10,
'status' => 'active'
]);
$headers = ['Authorization: Bearer YOUR_API_KEY'];
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => $headers,
]);
$response = curl_exec($curl);
curl_close($curl);
$data = json_decode($response, true);
print_r($data);
?>
```
--------------------------------
### Delete Coupon using Node.js (Axios)
Source: https://refgrow.com/docs/api-reference
This example shows how to delete a coupon using Node.js with the Axios library. It sends a DELETE request to the API endpoint with the necessary Authorization header. The response status code is logged to the console.
```javascript
const axios = require('axios');
const response = await axios.delete('https://refgrow.com/api/v1/coupons/1', {
headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
});
console.log(response.status); // 204
```