I'm working on integrating PayPal subscriptions into my Node.js application and need to store the subscription ID in a MongoDB database after a successful payment. Despite following the PayPal subscription creation and execution process, the subscriptionId isn't being saved as expected. I'm looking for guidance on how to ensure the subscriptionId is correctly stored in MongoDB.
Back-end's Code:
middlewares/auth.js
models/user.js
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
subscriptionId: {
type: String,
required: false,
unique: true,
},
});
const User = mongoose.model('User', userSchema);
module.exports = User;
routes/paypal.js
paypalRouter.post("/create-subscription", async (req,res) => {
try {
const subscriptionDetails = {
plan_id: process.env.PAYPAL_SANDBOX_BUSSINESS_SUBSCRIPTION_PLAN_ID,
application_context: {
brand_name: "pomoworko.com",
return_url: "http://localhost:3001/paypal/execute-subscription",
cancel_url: "http://localhost:3001/paypal/cancel-subscription",
}
};
// Generar un token de acceso
const params = new URLSearchParams();
params.append("grant_type", "client_credentials");
const authResponse = await axios.post(
"https://api-m.sandbox.paypal.com/v1/oauth2/token",
params,
{
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
auth: {
username: process.env.PAYPAL_CLIENT_ID,
password: process.env.PAYPAL_SECRET,
},
}
);
const access_token = authResponse.data.access_token;
// Crear la suscripción
const response = await axios.post(
"https://api-m.sandbox.paypal.com/v1/billing/subscriptions",
subscriptionDetails,
{
headers: {
Authorization: `Bearer ${access_token}`,
},
}
);
console.log(response.data);
// Aquí devolvemos el ID de la suscripción en la respuesta
console.error();
return res.json({ subscriptionId: response.data.id, ...response.data });
} catch (error) {
console.log(error);
return res.status(500).json("Something goes wrong");
}
});
paypalRouter.get("/execute-subscription", async (req, res) => {
const { token } = req.query; // El token de la suscripción que PayPal envía de vuelta
try {
// Paso 1: Obtener el Token de Acceso
const params = new URLSearchParams();
params.append("grant_type", "client_credentials");
const authResponse = await axios.post("https://api-m.sandbox.paypal.com/v1/oauth2/token", params, {
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
auth: {
username: process.env.PAYPAL_CLIENT_ID,
password: process.env.PAYPAL_SECRET,
},
});
const access_token = authResponse.data.access_token;
// Paso 2: Confirmar la Suscripción
// Nota: Debes reemplazar {subscription_id} con el ID de suscripción real obtenido previamente o pasado a través de la URL si es posible.
const subscriptionId = authResponse.data.id; // Necesitas obtener este ID de alguna manera, generalmente se guarda en la base de datos antes de redirigir al usuario a PayPal
const executeResponse =
await axios.post(`https://api-m.sandbox.paypal.com/v1/billing/subscriptions/${subscriptionId}/activate`, {}, {
headers: {
Authorization: `Bearer ${access_token}`,
'Content-Type': 'application/json'
},
});
console.log("Subscription confirmed:", executeResponse.data);
console.error();
res.send("Subscription successful!");
} catch (error) {
console.error("Error executing subscription:", error.response ? error.response.data : error.message);
res.status(500).send("An error occurred while executing the subscription.");
}
});
After executing the subscription, I expect to find the subscriptionId stored in the user's document in MongoDB, but it appears to be missing. There are no errors thrown by MongoDB or in my Node.js server logs.
Has anyone faced a similar issue or can offer insights into what I might be doing wrong?