Quantcast
Channel: Active questions tagged paypal - Stack Overflow
Viewing all articles
Browse latest Browse all 518

I have a index.js file that contains auto pay logic via Paypal Webhook. it wont run Payouts due to "cannot read timestamp: undefined" error

$
0
0

This is the top half of the code, the timestamp format is consistent throughout the rest of the functions

const { onRequest, onCall } = require("firebase-functions/v2/https");const { onSchedule } = require("firebase-functions/v2/scheduler");const logger = require("firebase-functions/logger");const admin = require("firebase-admin");const axios = require("axios");const { defineSecret } = require("firebase-functions/params");admin.initializeApp();const db = admin.firestore();const FieldValue = admin.firestore.FieldValue;const PAYPAL_CLIENT_ID = defineSecret("PAYPAL_CLIENT_ID");const PAYPAL_SECRET = defineSecret("PAYPAL_SECRET");const PAYPAL_WEBHOOK_ID = defineSecret("PAYPAL_WEBHOOK_ID");// 🔄 Auto Payouts (every 5 minutes)exports.processScheduledPayouts = onSchedule(  {         schedule: "every 5 minutes",    secrets: [PAYPAL_CLIENT_ID, PAYPAL_SECRET]  },  async (event) => {    const clientId = PAYPAL_CLIENT_ID.value();    const secret = PAYPAL_SECRET.value()    const now = new Date();    const snapshot = await db.collection("reservations")      .where("status", "==", "scheduled")      .where("startTime", "<=", now)      .get();    if (snapshot.empty) {      logger.info("No reservations to process.");      return;    }    let accessToken = "";    try {      const authResponse = await axios({        url: "https://api-m.sandbox.paypal.com/v1/oauth2/token",        method: "post",        headers: { "Content-Type": "application/x-www-form-urlencoded" },        auth: { username: clientId, password: secret },        data: "grant_type=client_credentials"      });      accessToken = authResponse.data.access_token;    } catch (err) {      logger.error("❌ Failed to get PayPal access token:", err.response?.data || err.message);      return;    }    for (const doc of snapshot.docs) {      const res = doc.data();      const resId = doc.id;      const payoutEmail = res.payoutEmail || res.spotOwnerEmail;      if (!payoutEmail) {        logger.warn(`Missing payout email for reservation ${resId}`);        continue;      }      const payoutAmount = res.fees?.ownerPayout?.toFixed(2) || "0.00";      const payoutBody = {        sender_batch_header: {          sender_batch_id: `batch-${resId}-${Date.now()}`,          email_subject: "You received a payout from ParknSpaces!"        },        items: [{          recipient_type: "EMAIL",          amount: {            value: payoutAmount,            currency: "USD"          },          receiver: payoutEmail,          note: "Thanks for sharing your spot!",          sender_item_id: resId        }]      };      try {        const payout = await axios({          url: "https://api-m.sandbox.paypal.com/v1/payments/payouts",          method: "post",          headers: {            Authorization: `Bearer ${accessToken}`,"Content-Type": "application/json"          },          data: payoutBody        });          await db.collection("payoutLogs").add({          reservationId: resId,          ownerId: res.spotOwnerId,          amount: Number(payoutAmount),          email: payoutEmail,          status: "Paid",          timestamp: FieldValue.serverTimestamp(),          paypalBatchId: payout.data.batch_header.payout_batch_id        });        await doc.ref.update({          status: "confirmed",          payoutSent: true,          payoutBatchId: payout.data.batch_header.payout_batch_id        });        logger.info(`✅ Payout sent for reservation ${resId}`);      } catch (err) {        logger.error(`❌ Failed payout for ${resId}`, err.response?.data || err.message);      }    }  });

CLI error while running processScheduledPayouts() from functions:shell states "Cannot read properties of undefined" reading serverTimestamp.

A checklog inserted before the payout script ran returned that serverTimestamp was recognized as a function and a different log at one point was returning timestamp data when checked during function deployment and again when entering shell.

The processScheduledPayouts never completes and fails with the reading error persistently.


Viewing all articles
Browse latest Browse all 518

Trending Articles