跳转到内容

Express

  1. 安装依赖包。

    终端窗口
    npm install express @spacepost/node
  2. 创建服务器。

    server.js
    import express from "express";
    import { SpacePost } from "@spacepost/node";
    const app = express();
    const spacepost = new SpacePost(process.env.SPACEPOST_API_KEY);
    // Webhooks need the RAW body to verify the signature: register this route BEFORE express.json().
    app.post("/webhooks/spacepost", express.raw({ type: "application/json" }), async (req, res) => {
    try {
    const event = await spacepost.webhooks.verify({
    payload: req.body.toString("utf8"),
    headers: req.headers,
    secret: process.env.SPACEPOST_WEBHOOK_SECRET,
    });
    console.log(event.type, event.data.email_id);
    res.sendStatus(200);
    } catch {
    res.sendStatus(400);
    }
    });
    app.use(express.json());
    app.post("/send", async (req, res) => {
    const { data, error } = await spacepost.emails.send({
    from: "Acme <hello@acme.com>",
    to: [req.body.to],
    subject: "Hello from Express",
    html: "<p>It works.</p>",
    });
    if (error) return res.status(error.statusCode ?? 500).json(error);
    res.json(data);
    });
    app.listen(3000, () => console.log("http://localhost:3000"));
  3. 运行并试用。

    终端窗口
    SPACEPOST_API_KEY=sp_live_YOUR_API_KEY node server.js
    curl -X POST localhost:3000/send -H "Content-Type: application/json" -d '{"to":"delivered@test.spacepost.dev"}'