支付完成后Strapi发送邮件

问题描述 投票:0回答:1

支付完成后Strapi发送邮件

我有一个带有 Strapi 后端的 React 前端。

我将产品添加到购物车,然后将该购物车提交到 Stripe

这一切都有效。

付款完成后我想发送电子邮件。

我有一个 sendgrid 帐户。

我已将 sendgrid 添加到 Strapi 中

yarn add @strapi/provider-email-sendgrid

我已将我的 sendgrid 应用程序密钥添加到 .env 文件中

在配置/插件中我有

module.exports = ({ env }) => ({
    email: {
        config: {
            provider: 'sendgrid',
            providerOptions: {
                apiKey: env('SENDGRID_API_KEY'),
            },
            settings: {
                defaultFrom: '[email protected]',
                defaultReplyTo: '[email protected]',
            },
        },
    },
});

我有订单内容类型

在 src/api/order/controllers/order.ts 中我有

"use strict";
// @ts-ignore
const stripe = require("stripe")("sk_test_51H");

/**
 *  order controller
 */
const { createCoreController } = require("@strapi/strapi").factories;
module.exports = createCoreController("api::order.order");

module.exports = {
    setUpStripe: async (ctx) => {

    let total = 0
    let validatedCart = []
    let receiptCart = []

    const { cart } = ctx.request.body

    await Promise.all(cart.map(async product => {
        try {

            const validatedProduct = await strapi.db.query('api::product.product').findOne({
                where: { id: product.id }
            });

            if (validatedProduct) {
                validatedCart.push(validatedProduct);

                receiptCart.push({
                    id: product.id
                })
            }
        } catch (error) {
            console.error('Error while querying the databases:', error);
        }
    }));

    total = validatedCart.reduce((n, { price }) => n + price, 0) || 0;

    try {
        const paymentIntent = await stripe.paymentIntents.create({
            amount: total,
            currency: 'usd',
            metadata: { cart: JSON.stringify(validatedCart.toString()) },
            payment_method_types: ['card']
        });

        // Send a response back to the client
        ctx.send({
            message: 'Payment intent created successfully',
            paymentIntent,
        });
    } catch (error) {
        // Handle errors and send an appropriate response
        ctx.send({
            error: true,
            message: 'Error in processing payment',
            details: error.message,
        });
    }
},

};

在 src > api > order > content-types > order >lifecycles.js

module.exports = {
    lifecycles: {
        async afterCreate(event) {
            const { result } = event

            try {
                await strapi.plugins['email'].services.email.send({

                    to: '[email protected]',
                    from: '[email protected]',
                    subject: 'Thank you for your order',
                    text: `Thank you for your order ${result.name}`

                })
            } catch (err) {
                console.log(err)
            }
        }
    }
}

在 Strapi 管理 > 设置 > 配置中

发送测试电子邮件有效

发送lifecycles.js的邮件不起作用。

有谁知道为什么这可能不起作用或者我如何调试它

reactjs email strapi
1个回答
0
投票

我不确定您使用的是哪个版本的 Strapi,或者您是否使用 TypeScript 编译为 JavaScript。

您可能想尝试使用普通 JS,直到您能更好地处理事情。如果您想使用 TS,请使用

import/export
语法,而不是
require/exports

使用 vanilla JS 我建议进行以下更改:

src/api/order/controllers/order.js
<--- Note the change from
.ts
.js

const { createCoreController } = require("@strapi/strapi").factories;
// Only define module.exports once
module.exports = createCoreController("api::order.order", {
    // Your previous implementation
    
    setUpStripe: async (ctx) => {

    let total = 0
    let validatedCart = []
    let receiptCart = []

    const { cart } = ctx.request.body

    await Promise.all(cart.map(async product => {
        try {

            const validatedProduct = await strapi.db.query('api::product.product').findOne({
                where: { id: product.id }
            });

            if (validatedProduct) {
                validatedCart.push(validatedProduct);

                receiptCart.push({
                    id: product.id
                })
            }
        } catch (error) {
            console.error('Error while querying the databases:', error);
        }
    }));

    total = validatedCart.reduce((n, { price }) => n + price, 0) || 0;

    try {
        const paymentIntent = await stripe.paymentIntents.create({
            amount: total,
            currency: 'usd',
            metadata: { cart: JSON.stringify(validatedCart.toString()) },
            payment_method_types: ['card']
        });

        // Send a response back to the client
        ctx.send({
            message: 'Payment intent created successfully',
            paymentIntent,
        });
    } catch (error) {
        // Handle errors and send an appropriate response
        ctx.send({
            error: true,
            message: 'Error in processing payment',
            details: error.message,
        });
    }
});

src/api/order/content-types/order/lifecycles.js

module.exports = {
    // Do not nest under "lifecycles" key
    async afterCreate(event) {
        const { result } = event

        try {
            await strapi.plugins['email'].services.email.send({

                to: '[email protected]',
                from: '[email protected]',
                subject: 'Thank you for your order',
                text: `Thank you for your order ${result.name}`

            })
        } catch (err) {
            console.log(err)
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.