# WebhookNotify - Code Examples

Complete integration examples for all major programming languages.

---

## Table of Contents

- [Python](#python)
- [JavaScript (Node.js)](#javascript-nodejs)
- [Rust](#rust)
- [Go](#go)
- [Java](#java)
- [Additional Examples](#additional-examples)

---

## Python

### Simple Notification

```python
import requests

def send_notification(token, message, title=None, priority="normal"):
    """Send a push notification via WebhookNotify"""
    url = f"https://webhooknotify.com/webhook/{token}"

    payload = {
        "message": message,
        "title": title,
        "priority": priority
    }

    response = requests.post(url, json=payload)
    response.raise_for_status()
    return response.json()

# Usage
TOKEN = "your-webhook-token-here"

# Basic notification
send_notification(TOKEN, "Deployment completed successfully!")

# With title and high priority
send_notification(
    TOKEN,
    message="CPU usage at 95%",
    title="Server Alert",
    priority="high"
)
```

### With Custom Payload (Deep Linking)

```python
import requests
import json

def send_notification_with_payload(token, title, message, custom_data):
    """Send notification with custom payload for app deep linking"""
    url = f"https://webhooknotify.com/webhook/{token}"

    payload = {
        "title": title,
        "message": message,
        "payload": custom_data  # Custom data for your app
    }

    response = requests.post(url, json=payload)
    response.raise_for_status()
    return response.json()

# Usage - E-commerce order notification
send_notification_with_payload(
    TOKEN,
    title="New Order",
    message="Order #12345 - $299.99",
    custom_data={
        "order_id": "12345",
        "amount": 299.99,
        "customer": "john@example.com",
        "action": "view_order"
    }
)
```

### Error Handling & Retries

```python
import requests
from time import sleep

def send_notification_with_retry(token, message, title=None, max_retries=3):
    """Send notification with automatic retries on failure"""
    url = f"https://webhooknotify.com/webhook/{token}"

    payload = {
        "message": message,
        "title": title
    }

    for attempt in range(max_retries):
        try:
            response = requests.post(url, json=payload, timeout=10)
            response.raise_for_status()
            return {"success": True, "data": response.json()}
        except requests.exceptions.RequestException as e:
            if attempt == max_retries - 1:
                return {"success": False, "error": str(e)}
            sleep(2 ** attempt)  # Exponential backoff

# Usage
result = send_notification_with_retry(
    TOKEN,
    message="Build completed",
    title="CI/CD Pipeline"
)

if result["success"]:
    print("Notification sent successfully")
else:
    print(f"Failed to send notification: {result['error']}")
```

### Django Integration

```python
# notifications/webhooknotify.py
from django.conf import settings
import requests
import logging

logger = logging.getLogger(__name__)

class WebhookNotify:
    """Django integration for WebhookNotify"""

    def __init__(self, token=None):
        self.token = token or settings.WEBHOOKNOTIFY_TOKEN
        self.base_url = "https://webhooknotify.com/webhook"

    def send(self, message, title=None, priority="normal", payload=None):
        """Send a notification"""
        url = f"{self.base_url}/{self.token}"

        data = {
            "message": message,
            "title": title,
            "priority": priority
        }

        if payload:
            data["payload"] = payload

        try:
            response = requests.post(url, json=data, timeout=10)
            response.raise_for_status()
            logger.info(f"Notification sent: {title or message}")
            return True
        except Exception as e:
            logger.error(f"Failed to send notification: {e}")
            return False

# Usage in views
from .webhooknotify import WebhookNotify

def process_order(request):
    # ... process order ...

    notifier = WebhookNotify()
    notifier.send(
        message=f"Order #{order.id} received - ${order.total}",
        title="New Order",
        priority="high",
        payload={"order_id": order.id}
    )

    return JsonResponse({"status": "success"})
```

---

## JavaScript (Node.js)

### Simple Notification

```javascript
const axios = require('axios');

async function sendNotification(token, message, options = {}) {
  const url = `https://webhooknotify.com/webhook/${token}`;

  const payload = {
    message,
    title: options.title || null,
    priority: options.priority || 'normal',
    payload: options.payload || null
  };

  try {
    const response = await axios.post(url, payload);
    return { success: true, data: response.data };
  } catch (error) {
    return { success: false, error: error.message };
  }
}

// Usage
const TOKEN = 'your-webhook-token-here';

// Basic notification
await sendNotification(TOKEN, 'Build completed successfully!');

// With options
await sendNotification(TOKEN, 'CPU usage critical', {
  title: 'Server Alert',
  priority: 'high'
});
```

### With TypeScript

```typescript
import axios, { AxiosError } from 'axios';

interface NotificationOptions {
  title?: string;
  priority?: 'low' | 'normal' | 'high';
  payload?: Record<string, any>;
}

interface NotificationResponse {
  success: boolean;
  message?: string;
  error?: string;
}

class WebhookNotify {
  private token: string;
  private baseUrl: string = 'https://webhooknotify.com/webhook';

  constructor(token: string) {
    this.token = token;
  }

  async send(
    message: string,
    options: NotificationOptions = {}
  ): Promise<NotificationResponse> {
    const url = `${this.baseUrl}/${this.token}`;

    const payload = {
      message,
      title: options.title,
      priority: options.priority || 'normal',
      payload: options.payload
    };

    try {
      const response = await axios.post(url, payload);
      return { success: true, message: response.data.message };
    } catch (error) {
      const axiosError = error as AxiosError;
      return {
        success: false,
        error: axiosError.message
      };
    }
  }
}

// Usage
const notifier = new WebhookNotify(process.env.WEBHOOKNOTIFY_TOKEN!);

await notifier.send('Deployment complete', {
  title: 'Production Deploy',
  priority: 'high',
  payload: { environment: 'production', version: '2.1.0' }
});
```

### Express.js Middleware

```javascript
const axios = require('axios');

// Middleware to send notifications on errors
function webhookNotifyErrorHandler(token) {
  return async (err, req, res, next) => {
    // Log error
    console.error(err);

    // Send notification
    try {
      await axios.post(`https://webhooknotify.com/webhook/${token}`, {
        title: 'Server Error',
        message: `${err.message} on ${req.path}`,
        priority: 'high',
        payload: {
          path: req.path,
          method: req.method,
          error: err.stack
        }
      });
    } catch (notifyError) {
      console.error('Failed to send notification:', notifyError);
    }

    // Send error response
    res.status(500).json({ error: 'Internal Server Error' });
  };
}

// Usage
const express = require('express');
const app = express();

app.get('/api/data', (req, res) => {
  throw new Error('Something went wrong!');
});

// Add error handler
app.use(webhookNotifyErrorHandler(process.env.WEBHOOKNOTIFY_TOKEN));

app.listen(3000);
```

### GitHub Actions Integration

```javascript
// .github/workflows/notify.yml
name: Build and Notify

on: [push]

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2

      - name: Build
        run: npm run build

      - name: Send Success Notification
        if: success()
        run: |
          curl -X POST https://webhooknotify.com/webhook/${{ secrets.WEBHOOKNOTIFY_TOKEN }} \
            -H "Content-Type: application/json" \
            -d '{
              "title": "Build Success",
              "message": "Build completed for ${{ github.repository }}",
              "priority": "normal",
              "payload": {
                "repo": "${{ github.repository }}",
                "branch": "${{ github.ref }}",
                "commit": "${{ github.sha }}"
              }
            }'

      - name: Send Failure Notification
        if: failure()
        run: |
          curl -X POST https://webhooknotify.com/webhook/${{ secrets.WEBHOOKNOTIFY_TOKEN }} \
            -H "Content-Type: application/json" \
            -d '{
              "title": "Build Failed",
              "message": "Build failed for ${{ github.repository }}",
              "priority": "high"
            }'
```

---

## Rust

### Simple Notification

```rust
use reqwest;
use serde::{Deserialize, Serialize};
use std::error::Error;

#[derive(Serialize)]
struct Notification {
    message: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    title: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    priority: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    payload: Option<serde_json::Value>,
}

#[derive(Deserialize)]
struct NotificationResponse {
    success: bool,
    message: String,
}

async fn send_notification(
    token: &str,
    message: &str,
    title: Option<&str>,
    priority: Option<&str>,
) -> Result<NotificationResponse, Box<dyn Error>> {
    let url = format!("https://webhooknotify.com/webhook/{}", token);

    let notification = Notification {
        message: message.to_string(),
        title: title.map(|s| s.to_string()),
        priority: priority.map(|s| s.to_string()),
        payload: None,
    };

    let client = reqwest::Client::new();
    let response = client
        .post(&url)
        .json(&notification)
        .send()
        .await?;

    let result: NotificationResponse = response.json().await?;
    Ok(result)
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let token = "your-webhook-token-here";

    // Simple notification
    send_notification(token, "Rust build completed!", None, None).await?;

    // With title and priority
    send_notification(
        token,
        "Memory usage at 95%",
        Some("Server Alert"),
        Some("high"),
    ).await?;

    Ok(())
}
```

### Production-Ready Client

```rust
use reqwest::{Client, Error as ReqwestError};
use serde::{Deserialize, Serialize};
use std::time::Duration;
use thiserror::Error;

#[derive(Error, Debug)]
pub enum NotifyError {
    #[error("HTTP request failed: {0}")]
    RequestFailed(#[from] ReqwestError),
    #[error("Invalid response")]
    InvalidResponse,
}

#[derive(Serialize)]
pub struct Notification {
    pub message: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub priority: Option<Priority>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payload: Option<serde_json::Value>,
}

#[derive(Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Priority {
    Low,
    Normal,
    High,
}

pub struct WebhookNotify {
    token: String,
    client: Client,
    base_url: String,
}

impl WebhookNotify {
    pub fn new(token: impl Into<String>) -> Self {
        let client = Client::builder()
            .timeout(Duration::from_secs(10))
            .build()
            .expect("Failed to build HTTP client");

        Self {
            token: token.into(),
            client,
            base_url: "https://webhooknotify.com/webhook".to_string(),
        }
    }

    pub async fn send(&self, notification: Notification) -> Result<(), NotifyError> {
        let url = format!("{}/{}", self.base_url, self.token);

        self.client
            .post(&url)
            .json(&notification)
            .send()
            .await?
            .error_for_status()?;

        Ok(())
    }

    pub async fn send_simple(&self, message: impl Into<String>) -> Result<(), NotifyError> {
        self.send(Notification {
            message: message.into(),
            title: None,
            priority: None,
            payload: None,
        }).await
    }
}

// Usage
#[tokio::main]
async fn main() -> Result<(), NotifyError> {
    let notifier = WebhookNotify::new("your-webhook-token-here");

    // Simple notification
    notifier.send_simple("Build completed!").await?;

    // Complex notification
    notifier.send(Notification {
        message: "Deployment successful".to_string(),
        title: Some("Production Deploy".to_string()),
        priority: Some(Priority::High),
        payload: Some(serde_json::json!({
            "version": "2.1.0",
            "environment": "production"
        })),
    }).await?;

    Ok(())
}
```

---

## Go

### Simple Notification

```go
package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "net/http"
    "time"
)

type Notification struct {
    Message  string                 `json:"message"`
    Title    string                 `json:"title,omitempty"`
    Priority string                 `json:"priority,omitempty"`
    Payload  map[string]interface{} `json:"payload,omitempty"`
}

func sendNotification(token, message string, options ...func(*Notification)) error {
    notification := &Notification{
        Message:  message,
        Priority: "normal",
    }

    // Apply options
    for _, opt := range options {
        opt(notification)
    }

    url := fmt.Sprintf("https://webhooknotify.com/webhook/%s", token)

    jsonData, err := json.Marshal(notification)
    if err != nil {
        return fmt.Errorf("failed to marshal JSON: %w", err)
    }

    client := &http.Client{Timeout: 10 * time.Second}
    resp, err := client.Post(url, "application/json", bytes.NewBuffer(jsonData))
    if err != nil {
        return fmt.Errorf("failed to send request: %w", err)
    }
    defer resp.Body.Close()

    if resp.StatusCode != http.StatusOK {
        return fmt.Errorf("unexpected status code: %d", resp.StatusCode)
    }

    return nil
}

// Option functions
func WithTitle(title string) func(*Notification) {
    return func(n *Notification) {
        n.Title = title
    }
}

func WithPriority(priority string) func(*Notification) {
    return func(n *Notification) {
        n.Priority = priority
    }
}

func WithPayload(payload map[string]interface{}) func(*Notification) {
    return func(n *Notification) {
        n.Payload = payload
    }
}

func main() {
    token := "your-webhook-token-here"

    // Simple notification
    err := sendNotification(token, "Build completed successfully!")
    if err != nil {
        fmt.Printf("Error: %v\n", err)
    }

    // With options
    err = sendNotification(
        token,
        "CPU usage at 95%",
        WithTitle("Server Alert"),
        WithPriority("high"),
        WithPayload(map[string]interface{}{
            "server": "prod-01",
            "cpu": 95.2,
        }),
    )
    if err != nil {
        fmt.Printf("Error: %v\n", err)
    }
}
```

### Production Client Package

```go
package webhooknotify

import (
    "bytes"
    "context"
    "encoding/json"
    "fmt"
    "net/http"
    "time"
)

// Client is a WebhookNotify API client
type Client struct {
    token      string
    baseURL    string
    httpClient *http.Client
}

// Notification represents a notification payload
type Notification struct {
    Message  string                 `json:"message"`
    Title    string                 `json:"title,omitempty"`
    Priority Priority               `json:"priority,omitempty"`
    Payload  map[string]interface{} `json:"payload,omitempty"`
}

// Priority levels
type Priority string

const (
    PriorityLow    Priority = "low"
    PriorityNormal Priority = "normal"
    PriorityHigh   Priority = "high"
)

// NewClient creates a new WebhookNotify client
func NewClient(token string) *Client {
    return &Client{
        token:   token,
        baseURL: "https://webhooknotify.com/webhook",
        httpClient: &http.Client{
            Timeout: 10 * time.Second,
        },
    }
}

// Send sends a notification
func (c *Client) Send(ctx context.Context, notification *Notification) error {
    url := fmt.Sprintf("%s/%s", c.baseURL, c.token)

    jsonData, err := json.Marshal(notification)
    if err != nil {
        return fmt.Errorf("marshal notification: %w", err)
    }

    req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewBuffer(jsonData))
    if err != nil {
        return fmt.Errorf("create request: %w", err)
    }

    req.Header.Set("Content-Type", "application/json")

    resp, err := c.httpClient.Do(req)
    if err != nil {
        return fmt.Errorf("send request: %w", err)
    }
    defer resp.Body.Close()

    if resp.StatusCode != http.StatusOK {
        return fmt.Errorf("unexpected status code: %d", resp.StatusCode)
    }

    return nil
}

// SendSimple sends a simple text notification
func (c *Client) SendSimple(ctx context.Context, message string) error {
    return c.Send(ctx, &Notification{
        Message:  message,
        Priority: PriorityNormal,
    })
}

// Usage example
func main() {
    client := NewClient("your-webhook-token-here")
    ctx := context.Background()

    // Simple notification
    if err := client.SendSimple(ctx, "Deployment completed!"); err != nil {
        fmt.Printf("Error: %v\n", err)
        return
    }

    // Complex notification
    notification := &Notification{
        Message:  "Order #12345 received",
        Title:    "New Order",
        Priority: PriorityHigh,
        Payload: map[string]interface{}{
            "order_id": "12345",
            "amount":   299.99,
            "customer": "john@example.com",
        },
    }

    if err := client.Send(ctx, notification); err != nil {
        fmt.Printf("Error: %v\n", err)
        return
    }
}
```

---

## Java

### Simple Notification (Java 11+)

```java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import com.google.gson.Gson;
import com.google.gson.JsonObject;

public class WebhookNotifyExample {

    public static void sendNotification(String token, String message) throws Exception {
        sendNotification(token, message, null, "normal");
    }

    public static void sendNotification(
        String token,
        String message,
        String title,
        String priority
    ) throws Exception {
        String url = "https://webhooknotify.com/webhook/" + token;

        // Build JSON payload
        JsonObject payload = new JsonObject();
        payload.addProperty("message", message);
        if (title != null) {
            payload.addProperty("title", title);
        }
        payload.addProperty("priority", priority);

        String jsonPayload = new Gson().toJson(payload);

        // Send HTTP request
        HttpClient client = HttpClient.newBuilder()
            .connectTimeout(Duration.ofSeconds(10))
            .build();

        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create(url))
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(jsonPayload))
            .build();

        HttpResponse<String> response = client.send(
            request,
            HttpResponse.BodyHandlers.ofString()
        );

        if (response.statusCode() != 200) {
            throw new Exception("Failed to send notification: " + response.statusCode());
        }
    }

    public static void main(String[] args) {
        String token = "your-webhook-token-here";

        try {
            // Simple notification
            sendNotification(token, "Build completed successfully!");

            // With title and high priority
            sendNotification(
                token,
                "CPU usage at 95%",
                "Server Alert",
                "high"
            );

            System.out.println("Notifications sent successfully!");
        } catch (Exception e) {
            System.err.println("Error: " + e.getMessage());
        }
    }
}
```

### Production Client Class

```java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import com.google.gson.Gson;

/**
 * WebhookNotify client for sending push notifications
 */
public class WebhookNotify {

    private final String token;
    private final String baseUrl;
    private final HttpClient httpClient;
    private final Gson gson;

    public enum Priority {
        LOW("low"),
        NORMAL("normal"),
        HIGH("high");

        private final String value;

        Priority(String value) {
            this.value = value;
        }

        public String getValue() {
            return value;
        }
    }

    public static class Notification {
        private String message;
        private String title;
        private String priority;
        private Map<String, Object> payload;

        public Notification(String message) {
            this.message = message;
            this.priority = Priority.NORMAL.getValue();
        }

        public Notification setTitle(String title) {
            this.title = title;
            return this;
        }

        public Notification setPriority(Priority priority) {
            this.priority = priority.getValue();
            return this;
        }

        public Notification setPayload(Map<String, Object> payload) {
            this.payload = payload;
            return this;
        }
    }

    public WebhookNotify(String token) {
        this.token = token;
        this.baseUrl = "https://webhooknotify.com/webhook";
        this.httpClient = HttpClient.newBuilder()
            .connectTimeout(Duration.ofSeconds(10))
            .build();
        this.gson = new Gson();
    }

    public void send(Notification notification) throws Exception {
        String url = baseUrl + "/" + token;
        String jsonPayload = gson.toJson(notification);

        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create(url))
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(jsonPayload))
            .build();

        HttpResponse<String> response = httpClient.send(
            request,
            HttpResponse.BodyHandlers.ofString()
        );

        if (response.statusCode() != 200) {
            throw new Exception(
                "Failed to send notification. Status: " + response.statusCode()
            );
        }
    }

    public void sendSimple(String message) throws Exception {
        send(new Notification(message));
    }

    // Usage example
    public static void main(String[] args) {
        WebhookNotify notifier = new WebhookNotify("your-webhook-token-here");

        try {
            // Simple notification
            notifier.sendSimple("Build completed!");

            // Complex notification
            Map<String, Object> payload = new HashMap<>();
            payload.put("order_id", "12345");
            payload.put("amount", 299.99);

            Notification notification = new Notification("Order #12345 received")
                .setTitle("New Order")
                .setPriority(Priority.HIGH)
                .setPayload(payload);

            notifier.send(notification);

            System.out.println("Notifications sent successfully!");

        } catch (Exception e) {
            System.err.println("Error: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
```

### Spring Boot Integration

```java
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

@Service
public class NotificationService {

    @Value("${webhooknotify.token}")
    private String token;

    private final RestTemplate restTemplate;

    public NotificationService() {
        this.restTemplate = new RestTemplate();
    }

    public void sendNotification(String message, String title, String priority) {
        String url = "https://webhooknotify.com/webhook/" + token;

        Map<String, Object> payload = new HashMap<>();
        payload.put("message", message);
        payload.put("title", title);
        payload.put("priority", priority);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<Map<String, Object>> request = new HttpEntity<>(payload, headers);

        try {
            restTemplate.postForObject(url, request, String.class);
        } catch (Exception e) {
            // Log error
            System.err.println("Failed to send notification: " + e.getMessage());
        }
    }

    public void notifyOrderReceived(String orderId, double amount) {
        sendNotification(
            String.format("Order #%s - $%.2f", orderId, amount),
            "New Order",
            "high"
        );
    }
}

// Usage in controller
@RestController
@RequestMapping("/api/orders")
public class OrderController {

    @Autowired
    private NotificationService notificationService;

    @PostMapping
    public ResponseEntity<Order> createOrder(@RequestBody Order order) {
        // Save order...

        // Send notification
        notificationService.notifyOrderReceived(
            order.getId(),
            order.getTotal()
        );

        return ResponseEntity.ok(order);
    }
}
```

---

## Additional Examples

### cURL (Command Line)

```bash
#!/bin/bash

TOKEN="your-webhook-token-here"

# Simple notification
curl -X POST "https://webhooknotify.com/webhook/$TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"message": "Hello from bash!"}'

# With title and priority
curl -X POST "https://webhooknotify.com/webhook/$TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "title": "Server Alert",
    "message": "CPU usage at 95%",
    "priority": "high"
  }'

# With custom payload
curl -X POST "https://webhooknotify.com/webhook/$TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "title": "New Order",
    "message": "Order #12345 received",
    "payload": {
      "order_id": "12345",
      "amount": 299.99,
      "customer": "john@example.com"
    }
  }'
```

### Ruby

```ruby
require 'net/http'
require 'json'
require 'uri'

def send_notification(token, message, title: nil, priority: 'normal')
  uri = URI("https://webhooknotify.com/webhook/#{token}")

  payload = {
    message: message,
    title: title,
    priority: priority
  }.compact

  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true

  request = Net::HTTP::Post.new(uri.path, 'Content-Type' => 'application/json')
  request.body = payload.to_json

  response = http.request(request)

  if response.code == '200'
    puts "Notification sent successfully!"
  else
    puts "Failed to send notification: #{response.code}"
  end
end

# Usage
TOKEN = 'your-webhook-token-here'

send_notification(TOKEN, 'Build completed!')
send_notification(TOKEN, 'CPU at 95%', title: 'Server Alert', priority: 'high')
```

### PHP

```php
<?php

function sendNotification($token, $message, $title = null, $priority = 'normal') {
    $url = "https://webhooknotify.com/webhook/{$token}";

    $payload = [
        'message' => $message,
        'title' => $title,
        'priority' => $priority
    ];

    $options = [
        'http' => [
            'header'  => "Content-Type: application/json\r\n",
            'method'  => 'POST',
            'content' => json_encode($payload),
            'timeout' => 10
        ]
    ];

    $context = stream_context_create($options);
    $result = file_get_contents($url, false, $context);

    if ($result === FALSE) {
        error_log("Failed to send notification");
        return false;
    }

    return true;
}

// Usage
$token = 'your-webhook-token-here';

sendNotification($token, 'Build completed!');
sendNotification($token, 'CPU at 95%', 'Server Alert', 'high');
?>
```

---

## Best Practices

### 1. Environment Variables

Always store your webhook token in environment variables:

**Python (.env file)**
```bash
WEBHOOKNOTIFY_TOKEN=your-webhook-token-here
```

```python
import os
from dotenv import load_dotenv

load_dotenv()
TOKEN = os.getenv('WEBHOOKNOTIFY_TOKEN')
```

**Node.js**
```javascript
require('dotenv').config();
const TOKEN = process.env.WEBHOOKNOTIFY_TOKEN;
```

**Go**
```go
import "os"

token := os.Getenv("WEBHOOKNOTIFY_TOKEN")
```

### 2. Error Handling

Always handle network errors gracefully:

```python
try:
    send_notification(TOKEN, "Message")
except requests.exceptions.Timeout:
    logger.error("Notification timeout")
except requests.exceptions.RequestException as e:
    logger.error(f"Notification failed: {e}")
```

### 3. Async/Background Sending

Don't block your main application flow:

**Python (async)**
```python
import asyncio
import aiohttp

async def send_notification_async(token, message):
    async with aiohttp.ClientSession() as session:
        async with session.post(
            f"https://webhooknotify.com/webhook/{token}",
            json={"message": message}
        ) as response:
            return await response.json()
```

**Node.js (background)**
```javascript
// Fire and forget
sendNotification(TOKEN, message).catch(err =>
    console.error('Notification failed:', err)
);
```

### 4. Rate Limiting

Be mindful of sending too many notifications:

```python
from time import sleep

# Limit to 1 notification per second
for item in items:
    send_notification(TOKEN, f"Processing {item}")
    sleep(1)
```

---

## API Reference

### Endpoint

```
POST https://webhooknotify.com/webhook/{token}
```

### Request Body

```json
{
  "message": "Notification message (required)",
  "title": "Notification title (optional)",
  "priority": "low|normal|high (optional, default: normal)",
  "payload": {
    "custom": "data for deep linking (optional)"
  }
}
```

### Response

```json
{
  "success": true,
  "message": "Notification sent successfully"
}
```

### Error Response

```json
{
  "error": {
    "code": "ERROR_CODE",
    "message": "Error description"
  }
}
```

---

## Support

For more examples and documentation, visit:
- Website: https://webhooknotify.com
- API Docs: https://webhooknotify.com/docs (coming soon)
- GitHub: https://github.com/webhooknotify (coming soon)

---

**Last Updated:** 2025-10-15
