ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 아마존 E-commerce 클론 -31) Order Receipt 이메일로 보내기
    NODE.JS 2021. 5. 30. 19:17

    우선 mailgun.com에 들어가서가입을 해준다. 

     

     

    sending>domains

     

    여기서 도메인을 생성하고 도메인을 클릭하면 

     

    api select> node.js를 클릭한다.

    여기서 apikey를 복사한다. 

    .env에 추가해준다. 여기서 도메인은 api base url의 sandbox~이다. 

    MALIGUN_API_KEY = ca4ad22c9e03a4a558b1bb875d3896f6-fa6e84b7-ea6a79b1
    MALIGUN_DOMAIN = sandbox024144b1dd7844b5a7ccd9c1ceff518d.mailgun.org
    
    

     

    최상위 폴더에서 npm install mailgun-js를 해준다. 

    백엔드의 utils.jsdp 다음을 추가해준다. 

    import mg from 'mailgun-js'
    
    export const mailgun =() => mg({
        apiKey: process.env.MALIGUN_API_KEY,
        domain: process.env.MALIGUN_DOMAIN
    }) 

     

     

    추가로 메일을 보낼 템플릿을 정해준다. 

    utils.js

    export const payOrderEmailTemplate = (order)=>{
        return `<h1>Thanks for shopping with us <h1>
        <p>
        Hi ${order.user.name},</p>
        <p>We have finished proessing your order.</p>
        <h2>[Order %{order._id}]  (${order.createdAt.toString().substring(0,10)})</h2>
        <table>
        <thead>
        <tr>
            <td><strong>Product</strong></td>
            <td><strong>Quantity</strong></td>
            <td><strong align="right">Price</strong></td>
        </tr>
        </thead>
        <tbody>
         ${order.orderItems.map(item=>`
         <tr>
             <td>${item.name}</td>
             <td align="center">${item.qty}</td>
             <td align="right">$${item.price.toFixed(2)}</td>
         </tr>
         `)
         .join('\n')}
        </tbody>
        <tfoot>
        <tr> 
            <td colspan="2">Items Price:</td>
            <td align="right">$${order.itemsPrice.toFixed(2)}</td>
        </tr>
        <tr>
        <td colspan="2">Tax Price:</td>
        <td align="right">$${order.taxPrice.toFixed(2)}</td>
        </tr>
        <tr>
        <td colspan="2">Shopping Price:</td>
        <td align="right">$${order.shippingPrice.toFixed(2)}</td>
        </tr>
        <tr>
        <td colspan="2">Total Price:</td>
        <td align="right"><strong>$${order.totalPrice.toFixed(2)}</strong></td>
        </tr>
        <tr>
        <td colspan="2">Payment Method</td>
        <td align="right">${order.paymentMethod.toFixed(2)}</td>
        </tr>
        </tfoot>
        </table>
        <h2>Shipping address</h2>
        <p>
            ${order.shippingAddress.fullname},<br/>
            ${order.shippingAddress.address},<br/>
            ${order.shippingAddress.city},<br/>
            ${order.shippingAddress.country},<br/>
            ${order.shippingAddress.postalCode}<br/>
        </p>
        <hr/>
        <p>
            Thanks for shopping with us.
        </p>
        `
    }

     

    orderRouter에 다음과 같이 수정해준다. 

    import { isAdmin, isAuth, isSellerOrAdmin, mailgun, payOrderEmailTemplate } from '../utils.js';
    
    orderRouter.put('/:id/pay', isAuth, expressAsyncHandler(async (req, res)=>{
        const order = await Order.findById(req.params.id).populate('user','email');
        if(order){
            order.isPaid = true,
            order.paidAt = Date.now();
            order.paymentResult = {id: req.body.id, status:req.body.status, update_time:req.body.update_time, email:req.body.email_address}
            const updatedOrder = await order.save();
            mailgun().messages().send({
                from :'Amazona <amazona@mg.yourdomain.com>',
                to:`${order.user.name} <${order.user.email}>`,
                subject:`New order ${order._id}`,
                html: payOrderEmailTemplate(order)
            },(error, body)=>{
                if(error){
                    console.log(error);
                }else{
                    console.log(body);
                }
            })
            res.send({message:'Order Paid', order: updatedOrder})
        }else{
            res.status(404).send({message:'Order Not Found'})
        }
    }))

     


    pay가 지금 오류가 나서 ㅠㅠㅠ 페이팔 결제가 안돼서 확인을 할 수 없다 ㅠㅠㅠ 나중에 꼭 해보기!

     

    완료되면 콘솔창에 뜬다.

    이런 이메일을 받아야 완료!

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

Designed by Tistory.