Xuất file CSV trực tiếp từ Google Sheets về server WordPress

Xuất file CSV trực tiếp từ Google Sheets về server WordPress

Em muốn kết nối giữa Trang tính (Google sheets) với một file trong mã nguồn Wordpress là wp-content/uploads/topics.csv để mỗi khi em cập nhật nội dung ở Trang tính thì File topics.csv cũng sẽ cập nhật theo. Mong các bác hướng dẫn ạ!
Từ khóa:
Google Adsense
Đã xác thực
Quảng Cáo

Re: xuất file CSV trực tiếp từ Google Sheets về server WordPress

Đơn giản mà, Google Apps Script sẽ giúp bạn xuất file CSV trực tiếp từ Google Sheets về server WordPress. Bạn làm như sau:

Bước 1: Mở Google Apps Script
- Trong Google Sheets, nhấn Extensions > Apps Script.
- Dán đoạn mã sau:

Mã: Chọn tất cả

function updateCSV() {
  // Lấy nội dung từ Google Sheets
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var data = sheet.getDataRange().getValues();

  // Chuyển dữ liệu sang định dạng CSV, thêm dấu ngoặc kép nếu cần
  var csvContent = data.map(row => 
    row.map(value => {
      if (value.toString().includes(",")) {
        return `"${value}"`; // Thêm dấu ngoặc kép nếu giá trị chứa dấu phẩy
      }
      return value;
    }).join(",")
  ).join("\n");

  // URL endpoint trên WordPress
  var url = "https://yourwordpresssite.com/wp-json/custom/v1/upload_csv";

  // Gửi yêu cầu tới WordPress
  var options = {
    method: "post",
    contentType: "application/json",
    payload: JSON.stringify({
      file_content: csvContent
    }),
    muteHttpExceptions: true
  };

  try {
    var response = UrlFetchApp.fetch(url, options);
    var responseText = response.getContentText();

    // Giải mã chuỗi Unicode
    var decodedResponse = decodeUnicode(responseText);
    Logger.log("Phản hồi từ server: " + decodedResponse);

  } catch (e) {
    Logger.log("Lỗi khi gửi file CSV: " + e.message);
  }
}

// Hàm giải mã chuỗi Unicode
function decodeUnicode(str) {
  return str.replace(/\\u[\dA-F]{4}/gi, function(match) {
    return String.fromCharCode(parseInt(match.replace("\\u", ""), 16));
  });
}

Bước 2: Tùy chỉnh URL
- Thay https://yourwordpresssite.com/wp-json/custom/v1/upload_csv bằng URL thực tế website WordPress của bạn.
- Nếu server yêu cầu xác thực, thêm API key hoặc thông tin xác thực vào options.headers.

Bước 3: Mở file plugin của bạn (hoặc file functions.php trong theme đang sử dụng) và thêm đoạn mã sau:

Mã: Chọn tất cả

// Thêm endpoint REST API trong WordPress
add_action('rest_api_init', function () {
    register_rest_route('custom/v1', '/upload_csv', [
        'methods' => 'POST',
        'callback' => 'handle_csv_upload',
        'permission_callback' => '__return_true', // Điều chỉnh quyền nếu cần
    ]);
});

function handle_csv_upload(WP_REST_Request $request) {
    // Lấy nội dung CSV từ request
    $csv_content = $request->get_param('file_content');

    // Kiểm tra nếu nội dung CSV rỗng
    if (empty($csv_content)) {
        return new WP_REST_Response(['status' => 'error', 'message' => 'Nội dung CSV trống.'], 400);
    }

    // Đường dẫn tới file topics.csv
    $file_path = ABSPATH . 'wp-content/uploads/topics.csv';

    // Ghi nội dung vào file
    if (file_put_contents($file_path, $csv_content)) {
        return new WP_REST_Response(['status' => 'success', 'message' => 'File CSV đã được cập nhật thành công!'], 200);
    } else {
        return new WP_REST_Response(['status' => 'error', 'message' => 'Không thể ghi nội dung vào file CSV.'], 500);
    }
}

Bước 4: Lưu và chạy script
- Lưu script với tên: Export CSV to Server.
- Nhấn nút Run để chạy script.
- Cấp quyền truy cập nếu được yêu cầu.

Re: Xuất file CSV trực tiếp từ Google Sheets về server WordPress

Hiện tại, permission_callback là __return_true, nghĩa là bất kỳ ai cũng có thể gọi endpoint này mà không cần quyền truy cập. Điều này không an toàn. Liệu có nên kiểm tra xem người dùng có đăng nhập và có quyền cần thiết hay không ạ?

Mã: Chọn tất cả

'permission_callback' => function () {
    return current_user_can('manage_options'); // Chỉ quản trị viên mới có thể sử dụng endpoint này
},

Re: Xuất file CSV trực tiếp từ Google Sheets về server WordPress

Nếu bạn muốn an toàn hơn, hãy thử thêm một API key đơn giản để bảo vệ endpoint.

Bước 1: Cập Nhật Apps Script
Hãy đảm bảo rằng Apps Script đang gửi đúng nội dung tới endpoint. Đây là mã sửa lỗi cho Apps Script

Mã: Chọn tất cả

function sendCsvToWordPress() {
  var sheetUrl = "https://docs.google.com/spreadsheets/d/e/2PACX-1vXXXXX/pub?output=csv"; // URL xuất CSV từ Google Sheets
  var apiEndpoint = "https://your-site.com/wp-json/custom/v1/upload_csv"; // Địa chỉ endpoint của bạn
  var apiKey = "your-secret-key-here"; // Khóa API bí mật (nếu sử dụng)

  try {
    // Lấy nội dung CSV từ Google Sheets
    var response = UrlFetchApp.fetch(sheetUrl);
    var csvContent = response.getContentText();

    // Gửi nội dung CSV tới REST API của WordPress
    var options = {
      'method': 'post',
      'contentType': 'application/json',
      'payload': JSON.stringify({
        'file_content': csvContent,
        'api_key': apiKey // Gửi API key để xác thực
      }),
      'muteHttpExceptions': true
    };

    var apiResponse = UrlFetchApp.fetch(apiEndpoint, options);

    // Hiển thị phản hồi từ WordPress trong Apps Script Logger
    Logger.log(apiResponse.getContentText());
  } catch (error) {
    Logger.log("Lỗi: " + error.message);
  }
}

Bước 2: Đảm Bảo Endpoint WordPress Hoạt Động

Mã: Chọn tất cả

<?php
/*
Plugin Name: Thêm endpoint REST API
Description: Nhận file CSV từ Google Sheets qua REST API
Version: 1.1
Author: Your Name
*/

// Tạo endpoint REST API trong WordPress
add_action('rest_api_init', function () {
    register_rest_route('custom/v1', '/upload_csv', [
        'methods' => 'POST',
        'callback' => 'handle_csv_upload',
        'permission_callback' => '__return_true',
    ]);
});

function handle_csv_upload(WP_REST_Request $request) {
    $csv_content = $request->get_param('file_content');
    $api_key = $request->get_param('api_key');

    // Kiểm tra API key
    $valid_key = 'your-secret-key-here';
    if ($api_key !== $valid_key) {
        return new WP_REST_Response(['status' => 'error', 'message' => 'API Key không hợp lệ.'], 401);
    }

    // Kiểm tra nếu nội dung CSV rỗng
    if (empty($csv_content)) {
        return new WP_REST_Response(['status' => 'error', 'message' => 'Nội dung CSV trống.'], 400);
    }

    // Đường dẫn tới file CSV
    $file_path = ABSPATH . 'wp-content/uploads/topics.csv';

    // Ghi nội dung CSV vào file
    if (file_put_contents($file_path, $csv_content)) {
        return new WP_REST_Response(['status' => 'success', 'message' => 'File CSV đã được cập nhật thành công!'], 200);
    } else {
        return new WP_REST_Response(['status' => 'error', 'message' => 'Không thể ghi nội dung vào file CSV.'], 500);
    }
}
Chuyên mục Công nghệ chia sẻ kiến thức về thiết bị, phần mềm và xu hướng số, giúp bạn cập nhật thông tin và ứng dụng hiệu quả trong thực tế.