PayOS Payment Form – Tích hợp Systeme.io

Thanh toán PayOS

Quét mã QR để thanh toán nhanh chóng

Code WordPress Plugin


// Thêm vào functions.php hoặc tạo plugin riêng

// PayOS Configuration
define('PAYOS_CLIENT_ID', 'your-client-id');
define('PAYOS_API_KEY', 'your-api-key');
define('PAYOS_CHECKSUM_KEY', 'your-checksum-key');

// Systeme.io Configuration  
define('SYSTEME_API_KEY', 'your-systeme-api-key');
define('SYSTEME_TAG_ID', 'your-tag-id'); // Tag ID được gán sẵn

// AJAX handler cho tạo payment link
add_action('wp_ajax_create_payos_payment', 'handle_create_payos_payment');
add_action('wp_ajax_nopriv_create_payos_payment', 'handle_create_payos_payment');

function handle_create_payos_payment() {
    // Verify nonce for security
    if (!wp_verify_nonce($_POST['nonce'], 'payos_payment_nonce')) {
        wp_die('Security check failed');
    }

    $email = sanitize_email($_POST['email']);
    $fullName = sanitize_text_field($_POST['fullName']);
    $amount = intval($_POST['amount']);
    $description = sanitize_text_field($_POST['description']) ?: 'Thanh toán dịch vụ';
    
    $orderCode = time(); // Mã đơn hàng unique
    
    // Tạo signature cho PayOS
    $data = [
        'amount' => $amount,
        'cancelUrl' => home_url('/payment-cancel/'),
        'description' => $description,
        'orderCode' => $orderCode,
        'returnUrl' => home_url('/payment-return/')
    ];
    
    $signature = create_payos_signature($data);
    
    // Payload cho PayOS API
    $payload = array_merge($data, [
        'buyerName' => $fullName,
        'buyerEmail' => $email,
        'signature' => $signature,
        'expiredAt' => time() + 900 // 15 phút
    ]);
    
    // Call PayOS API
    $response = wp_remote_post('https://api-merchant.payos.vn/v2/payment-requests', [
        'headers' => [
            'Content-Type' => 'application/json',
            'x-client-id' => PAYOS_CLIENT_ID,
            'x-api-key' => PAYOS_API_KEY
        ],
        'body' => json_encode($payload),
        'timeout' => 30
    ]);
    
    if (is_wp_error($response)) {
        wp_send_json_error('Không thể kết nối PayOS API');
        return;
    }
    
    $body = wp_remote_retrieve_body($response);
    $result = json_decode($body, true);
    
    if ($result['code'] === '00') {
        // Lưu thông tin giao dịch vào database
        global $wpdb;
        $table_name = $wpdb->prefix . 'payos_transactions';
        
        $wpdb->insert($table_name, [
            'order_code' => $orderCode,
            'payment_link_id' => $result['data']['paymentLinkId'],
            'email' => $email,
            'full_name' => $fullName,
            'amount' => $amount,
            'description' => $description,
            'status' => 'pending',
            'created_at' => current_time('mysql')
        ]);
        
        wp_send_json_success($result['data']);
    } else {
        wp_send_json_error('Lỗi tạo payment link: ' . $result['desc']);
    }
}

// Tạo signature cho PayOS
function create_payos_signature($data) {
    $sortedData = [];
    ksort($data);
    
    foreach ($data as $key => $value) {
        $sortedData[] = $key . '=' . $value;
    }
    
    $queryString = implode('&', $sortedData);
    return hash_hmac('sha256', $queryString, PAYOS_CHECKSUM_KEY);
}

// Webhook handler từ PayOS
add_action('init', 'handle_payos_webhook');

function handle_payos_webhook() {
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && $_SERVER['REQUEST_URI'] === '/payos-webhook/') {
        $payload = file_get_contents('php://input');
        $data = json_decode($payload, true);
        
        // Verify signature
        if (!verify_payos_signature($data)) {
            http_response_code(400);
            exit('Invalid signature');
        }
        
        if ($data['code'] === '00' && $data['desc'] === 'success') {
            $orderCode = $data['data']['orderCode'];
            $paymentLinkId = $data['data']['paymentLinkId'];
            
            // Cập nhật trạng thái thanh toán
            global $wpdb;
            $table_name = $wpdb->prefix . 'payos_transactions';
            
            $transaction = $wpdb->get_row($wpdb->prepare(
                "SELECT * FROM $table_name WHERE order_code = %d",
                $orderCode
            ));
            
            if ($transaction && $transaction->status === 'pending') {
                // Cập nhật trạng thái
                $wpdb->update(
                    $table_name,
                    ['status' => 'completed', 'updated_at' => current_time('mysql')],
                    ['id' => $transaction->id]
                );
                
                // Gửi thông tin đến Systeme.io
                send_to_systeme_io($transaction->email, $transaction->full_name);
                
                // Gửi email xác nhận
                send_payment_confirmation_email($transaction);
            }
        }
        
        http_response_code(200);
        exit('OK');
    }
}

// Verify PayOS signature
function verify_payos_signature($data) {
    $signature = $data['signature'];
    unset($data['signature']);
    
    $expectedSignature = hash_hmac('sha256', json_encode($data), PAYOS_CHECKSUM_KEY);
    return hash_equals($signature, $expectedSignature);
}

// Gửi thông tin contact đến Systeme.io
function send_to_systeme_io($email, $fullName) {
    $names = explode(' ', $fullName, 2);
    $firstName = $names[0];
    $lastName = isset($names[1]) ? $names[1] : '';
    
    // Tạo hoặc cập nhật contact
    $contactData = [
        'email' => $email,
        'fields' => [
            ['slug' => 'first_name', 'value' => $firstName],
            ['slug' => 'surname', 'value' => $lastName]
        ]
    ];
    
    $response = wp_remote_post('https://api.systeme.io/api/contacts', [
        'headers' => [
            'Content-Type' => 'application/json',
            'X-API-Key' => SYSTEME_API_KEY
        ],
        'body' => json_encode($contactData),
        'timeout' => 30
    ]);
    
    if (!is_wp_error($response)) {
        $body = wp_remote_retrieve_body($response);
        $result = json_decode($body, true);
        
        if (isset($result['id'])) {
            // Gán tag cho contact
            assign_tag_to_contact($result['id'], SYSTEME_TAG_ID);
        }
    }
}

// Gán tag cho contact trong Systeme.io
function assign_tag_to_contact($contactId, $tagId) {
    $response = wp_remote_post("https://api.systeme.io/api/contacts/{$contactId}/tags/{$tagId}", [
        'headers' => [
            'X-API-Key' => SYSTEME_API_KEY
        ],
        'method' => 'PUT',
        'timeout' => 30
    ]);
    
    return !is_wp_error($response);
}

// Tạo bảng database khi activate plugin
register_activation_hook(__FILE__, 'create_payos_table');

function create_payos_table() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'payos_transactions';
    
    $charset_collate = $wpdb->get_charset_collate();
    
    $sql = "CREATE TABLE $table_name (
        id int(11) NOT NULL AUTO_INCREMENT,
        order_code bigint(20) NOT NULL,
        payment_link_id varchar(255) NOT NULL,
        email varchar(255) NOT NULL,
        full_name varchar(255) NOT NULL,
        amount int(11) NOT NULL,
        description text,
        status varchar(20) DEFAULT 'pending',
        created_at datetime NOT NULL,
        updated_at datetime DEFAULT NULL,
        PRIMARY KEY (id),
        UNIQUE KEY order_code (order_code)
    ) $charset_collate;";
    
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);
}

// Shortcode để hiển thị form
add_shortcode('payos_payment_form', 'payos_payment_form_shortcode');

function payos_payment_form_shortcode() {
    wp_enqueue_script('payos-form-js', plugin_dir_url(__FILE__) . 'payos-form.js', ['jquery'], '1.0.0', true);
    wp_localize_script('payos-form-js', 'payos_ajax', [
        'ajax_url' => admin_url('admin-ajax.php'),
        'nonce' => wp_create_nonce('payos_payment_nonce')
    ]);
    
    ob_start();
    // HTML form code ở đây
    return ob_get_clean();
}
                

Hướng dẫn cài đặt:

  1. Tạo tài khoản PayOS và lấy Client ID, API Key, Checksum Key
  2. Tạo tài khoản Systeme.io và lấy API Key
  3. Tạo tag trong Systeme.io và lấy Tag ID
  4. Cập nhật các constant trong code với thông tin thực tế
  5. Tạo plugin WordPress hoặc thêm code vào functions.php
  6. Cấu hình webhook URL trong dashboard PayOS: your-site.com/payos-webhook/
  7. Sử dụng shortcode [payos_payment_form] để hiển thị form