Skip to content

PHP Guide

Complete guide to using QR Code API with PHP.

Requirements

  • PHP 7.4+
  • cURL extension (usually included)

Quick Start

php
<?php
$apiKey = getenv('QRCODE_API_KEY');

function generateQR($data, $filename = 'qr.png') {
    global $apiKey;
    
    $url = 'https://www.qrcodeapi.io/api/generate?' . http_build_query([
        'data' => $data
    ]);
    
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => [
            'Authorization: Bearer ' . $apiKey
        ]
    ]);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($httpCode !== 200) {
        throw new Exception('Failed to generate QR code: ' . $response);
    }
    
    file_put_contents($filename, $response);
    echo "Saved to $filename\n";
}

generateQR('https://example.com');
?>

Complete Examples

Generate with Custom Options

php
<?php
function generateQR($data, $options = []) {
    global $apiKey;
    
    $params = array_merge([
        'data' => $data,
        'size' => 300,
        'format' => 'png',
        'color' => '000000',
        'background' => 'ffffff',
        'errorCorrection' => 'M',
        'margin' => 4
    ], $options);
    
    $url = 'https://www.qrcodeapi.io/api/generate?' . http_build_query($params);
    
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => [
            'Authorization: Bearer ' . $apiKey
        ]
    ]);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($httpCode !== 200) {
        $error = json_decode($response, true);
        throw new Exception($error['message'] ?? 'Unknown error');
    }
    
    return $response;
}

// Usage
$qr = generateQR('https://example.com', [
    'size' => 500,
    'color' => '22c55e',
    'format' => 'svg'
]);

file_put_contents('custom-qr.svg', $qr);
?>

Using file_get_contents (Alternative)

php
<?php
function generateQR($data, $options = []) {
    global $apiKey;
    
    $params = array_merge(['data' => $data], $options);
    $url = 'https://www.qrcodeapi.io/api/generate?' . http_build_query($params);
    
    $context = stream_context_create([
        'http' => [
            'header' => "Authorization: Bearer $apiKey\r\n"
        ]
    ]);
    
    $response = @file_get_contents($url, false, $context);
    
    if ($response === false) {
        throw new Exception('Failed to generate QR code');
    }
    
    return $response;
}

// Usage
$qr = generateQR('https://example.com', ['size' => 400]);
file_put_contents('qr.png', $qr);
?>
php
<?php
function createDynamicLink($name, $targetUrl) {
    global $apiKey;
    
    $ch = curl_init('https://www.qrcodeapi.io/api/links');
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode([
            'name' => $name,
            'targetUrl' => $targetUrl
        ]),
        CURLOPT_HTTPHEADER => [
            'Authorization: Bearer ' . $apiKey,
            'Content-Type: application/json'
        ]
    ]);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($httpCode !== 200 && $httpCode !== 201) {
        $error = json_decode($response, true);
        throw new Exception($error['message'] ?? 'Unknown error');
    }
    
    return json_decode($response, true);
}

// Usage
$link = createDynamicLink('My Campaign', 'https://example.com/landing');
echo "Short URL: https://www.qrcodeapi.io/r/{$link['shortCode']}\n";
?>
php
<?php
function updateDynamicLink($linkId, $updates) {
    global $apiKey;
    
    $ch = curl_init("https://www.qrcodeapi.io/api/links?id=$linkId");
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CUSTOMREQUEST => 'PUT',
        CURLOPT_POSTFIELDS => json_encode($updates),
        CURLOPT_HTTPHEADER => [
            'Authorization: Bearer ' . $apiKey,
            'Content-Type: application/json'
        ]
    ]);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($httpCode !== 200) {
        $error = json_decode($response, true);
        throw new Exception($error['message'] ?? 'Unknown error');
    }
    
    return json_decode($response, true);
}

// Usage
updateDynamicLink($link['id'], ['targetUrl' => 'https://example.com/new']);
?>

Get Analytics

php
<?php
function getAnalytics($linkId, $startDate = null, $endDate = null) {
    global $apiKey;
    
    $params = ['linkId' => $linkId];
    if ($startDate) $params['startDate'] = $startDate;
    if ($endDate) $params['endDate'] = $endDate;
    
    $url = 'https://www.qrcodeapi.io/api/analytics?' . http_build_query($params);
    
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => [
            'Authorization: Bearer ' . $apiKey
        ]
    ]);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($httpCode !== 200) {
        $error = json_decode($response, true);
        throw new Exception($error['message'] ?? 'Unknown error');
    }
    
    return json_decode($response, true);
}

// Get last 30 days
$endDate = date('Y-m-d');
$startDate = date('Y-m-d', strtotime('-30 days'));

$analytics = getAnalytics('your-link-id', $startDate, $endDate);

echo "Total scans: {$analytics['analytics']['totalScans']}\n";
?>

Laravel Integration

Service Provider

php
<?php
// app/Services/QRCodeService.php

namespace App\Services;

use Illuminate\Support\Facades\Http;

class QRCodeService
{
    private string $apiKey;
    private string $baseUrl = 'https://www.qrcodeapi.io/api';

    public function __construct()
    {
        $this->apiKey = config('services.qrcode.key');
    }

    public function generate(string $data, array $options = []): string
    {
        $params = array_merge(['data' => $data], $options);

        $response = Http::withToken($this->apiKey)
            ->get("{$this->baseUrl}/generate", $params);

        if (!$response->successful()) {
            throw new \Exception($response->json('message', 'Unknown error'));
        }

        return $response->body();
    }

    public function createLink(string $name, string $targetUrl): array
    {
        $response = Http::withToken($this->apiKey)
            ->post("{$this->baseUrl}/links", [
                'name' => $name,
                'targetUrl' => $targetUrl
            ]);

        if (!$response->successful()) {
            throw new \Exception($response->json('message', 'Unknown error'));
        }

        return $response->json();
    }

    public function getAnalytics(string $linkId): array
    {
        $response = Http::withToken($this->apiKey)
            ->get("{$this->baseUrl}/analytics", ['linkId' => $linkId]);

        if (!$response->successful()) {
            throw new \Exception($response->json('message', 'Unknown error'));
        }

        return $response->json();
    }
}

Controller

php
<?php
// app/Http/Controllers/QRController.php

namespace App\Http\Controllers;

use App\Services\QRCodeService;
use Illuminate\Http\Request;

class QRController extends Controller
{
    public function __construct(
        private QRCodeService $qrService
    ) {}

    public function generate(Request $request)
    {
        $request->validate([
            'data' => 'required|string|max:2953',
            'size' => 'integer|min:50|max:2000',
            'format' => 'in:png,svg'
        ]);

        $qr = $this->qrService->generate(
            $request->input('data'),
            $request->only(['size', 'format', 'color', 'background'])
        );

        $contentType = $request->input('format') === 'svg' 
            ? 'image/svg+xml' 
            : 'image/png';

        return response($qr)->header('Content-Type', $contentType);
    }

    public function createLink(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'targetUrl' => 'required|url'
        ]);

        $link = $this->qrService->createLink(
            $request->input('name'),
            $request->input('targetUrl')
        );

        return response()->json($link, 201);
    }
}

Config

php
<?php
// config/services.php
return [
    // ...
    'qrcode' => [
        'key' => env('QRCODE_API_KEY'),
    ],
];

WordPress Plugin

php
<?php
/**
 * Plugin Name: QR Code API
 * Description: Generate QR codes using QR Code API
 */

class QRCodeAPI {
    private $apiKey;
    
    public function __construct() {
        $this->apiKey = get_option('qrcode_api_key');
        
        add_shortcode('qrcode', [$this, 'shortcode']);
        add_action('admin_menu', [$this, 'adminMenu']);
    }
    
    public function shortcode($atts) {
        $atts = shortcode_atts([
            'data' => '',
            'size' => 200,
            'color' => '000000'
        ], $atts);
        
        if (empty($atts['data'])) {
            return 'Error: data attribute required';
        }
        
        $params = http_build_query([
            'data' => $atts['data'],
            'size' => $atts['size'],
            'color' => $atts['color']
        ]);
        
        $url = "https://www.qrcodeapi.io/api/generate?{$params}";
        
        // Cache the QR code
        $cacheKey = 'qrcode_' . md5($params);
        $cached = get_transient($cacheKey);
        
        if ($cached) {
            return $cached;
        }
        
        $html = sprintf(
            '<img src="%s" alt="QR Code" width="%d" height="%d">',
            esc_url($url . '&api_key=' . $this->apiKey),
            $atts['size'],
            $atts['size']
        );
        
        set_transient($cacheKey, $html, DAY_IN_SECONDS);
        
        return $html;
    }
    
    public function adminMenu() {
        add_options_page(
            'QR Code API',
            'QR Code API',
            'manage_options',
            'qrcode-api',
            [$this, 'settingsPage']
        );
    }
    
    public function settingsPage() {
        if (isset($_POST['qrcode_api_key'])) {
            update_option('qrcode_api_key', sanitize_text_field($_POST['qrcode_api_key']));
        }
        ?>
        <div class="wrap">
            <h1>QR Code API Settings</h1>
            <form method="post">
                <table class="form-table">
                    <tr>
                        <th>API Key</th>
                        <td>
                            <input type="text" name="qrcode_api_key" 
                                   value="<?php echo esc_attr(get_option('qrcode_api_key')); ?>" 
                                   class="regular-text">
                        </td>
                    </tr>
                </table>
                <?php submit_button(); ?>
            </form>
            
            <h2>Usage</h2>
            <code>[qrcode data="https://example.com" size="200" color="000000"]</code>
        </div>
        <?php
    }
}

new QRCodeAPI();

Error Handling

php
<?php
function generateQRSafe($data, $options = [], $retries = 3) {
    global $apiKey;
    
    for ($i = 0; $i < $retries; $i++) {
        $params = array_merge(['data' => $data], $options);
        $url = 'https://www.qrcodeapi.io/api/generate?' . http_build_query($params);
        
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . $apiKey]
        ]);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        if ($httpCode === 429) {
            $error = json_decode($response, true);
            $wait = $error['retryAfter'] ?? 60;
            echo "Rate limited. Waiting {$wait} seconds...\n";
            sleep($wait);
            continue;
        }
        
        if ($httpCode !== 200) {
            $error = json_decode($response, true);
            throw new Exception($error['message'] ?? 'Unknown error');
        }
        
        return $response;
    }
    
    throw new Exception('Max retries exceeded');
}
?>