GA4 项目中使用测量协议时,标准数据报告会无法显示数据。但是,可以通过使用自定义报告及 BigQuery 等方法来获取数据。以下是通过测量协议将数据写入 BigQuery 的示例代码:
// Google Cloud project ID.
const projectId = 'your-project-id';
// Dataset ID for temporary storage.
const datasetId = 'ga4_data';
// Table ID to store data ingested through the Measurement Protocol.
const tableId = 'mp_data';
// BigQuery configuration.
const bigquery = new BigQuery({
projectId: projectId,
location: 'US'
});
// Handler function to ingest the data received through the Measurement Protocol.
exports.receiveMPData = async (req, res) => {
// Creates a new table in case it doesn't exist already.
await createTable(bigquery, datasetId, tableId);
// Parses the Measurement Protocol payload.
const mp_payload = new URLSearchParams(req.rawBody);
// Extracts the hits array from the payload.
const hit_string = mp_payload.get('hits');
const hits = JSON.parse(hit_string);
// Appends the hits to the BigQuery table.
const insertRowsResponse = await bigquery
.dataset(datasetId)
.table(tableId)
.insert(hits);
console.log(`Inserted ${insertRowsResponse[0].length} rows`);
res.status(200).send('Success');
};
// Function to create a BigQuery table in case it doesn't exist already.
async function createTable(bigquery, datasetId, tableId) {
const dataset = bigquery.dataset(datasetId);
// Creates the dataset if it doesn't exist already.
if (!(await dataset.exists())) {
await dataset.create();
}
const options = {
schema: 'schema.json',
location: 'US'
};
// Creates the table if it doesn't exist already.
const [table] = await dataset.table(tableId).get({ autoCreate: options });
console.log(`Table ${table.id} created.`);
}
此代码将 GA4