php中文网

支付网关一般不必太复杂

php中文网

在 node.js 和 fastify 中使用适配器模式集成支付网关

集成不同的支付网关似乎是一项具有挑战性的任务,但想象一下,如果有一个解决方案使这个过程变得简单而高效,您会感到多么安心。使用设计模式适配器,您将完全控制集成,从而更轻松地维护和扩展您的系统。

现在,想象一下掌握一项技能的力量,它不仅可以节省您的时间,还可以提高代码的质量。在本文中,我们将向您展示如何在使用 node.js 和 fastify 集成支付网关时脱颖而出,fastify 是一项赢得了世界各地开发者青睐的技术。

如果您致力于将自己的技能提升到一个新的水平,那么此内容适合您。让我们一起探索使用 woovi api 创建 pix 费用,以及使您在市场中脱颖而出的其他功能。

我们将介绍使用node.jsfastify集成支付网关。除了其他功能之外,您还将学习如何使用 woovi api 通过 pix 生成费用。

本文是 crazystack node.js 类的一部分,我们在其中使用 node.js 和 fastify 从头开始​​开发了 rest api。 您可以通过此处和此处的视频跟随本教程的开头部分。

项目结构

我们将以模块化的方式构建项目,每个支付网关都有自己的实现,但每个人都共享一个共同的合约。我们将使用typescript来确保静态类型和代码安全。

目录和文件

  • 源代码/
    • 合同/
    • paymentgateway.ts(所有网关通用的合约)
    • 适配器/
    • wooviadapter.ts(woovi 网关实现)
    • stripeadapter.ts(stripe 网关实现)
    • pagarmeadapter.ts(pagar.me 网关的实现)
    • index.ts(适配器入口点)
    • 配置/
    • env.ts(环境设置)

支付网关协议

第一步是定义所有支付网关都必须实现的合约。这确保所有网关具有相同的功能和相同的签名,确保一致性。

// src/contracts/paymentgateway.ts
export abstract class paymentgateway {
  abstract createcharge(data: any): promise<any>;
  abstract deletecharge(id: string): promise<any>;
  abstract getcharge(id: string): promise<any>;
  abstract createsubscription(data: any): promise<any>;
  abstract getsubscription(id: string): promise<any>;
  abstract createcustomer(data: any): promise<any>;
  abstract getcustomer(id: string): promise<any>;
  abstract getchargebycustomer(data: any): promise<any>;
}
</any></any></any></any></any></any></any></any>

支付网关适配器

wovi 支付网关

woovi 的适配器实现使用 axios 库进行 http 调用。

// src/adapters/wooviadapter.ts
import axios from "axios";
import { paymentgateway } from "../contracts";
import { env } from "../config";

export class woovipaymentgateway extends paymentgateway {
  private apikey: string;

  constructor(paymentkey: string) {
    super();
    this.apikey = paymentkey;
  }

  async deletecharge(id: string): promise<any> {
    try {
      const response = await axios.delete(
        `https://api.openpix.com.br/api/v1/charge/${id}`,
        {
          headers: { authorization: this.apikey },
        }
      );
      return response?.data;
    } catch (e: any) {
      return e?.response?.data;
    }
  }

  async getcharge(id: string): promise<any> {
    try {
      const response = await axios.get(
        `https://api.openpix.com.br/api/v1/charge/${id}`,
        {
          headers: { authorization: this.apikey, "content-type": "application/json" },
        }
      );
      return response?.data;
    } catch (e: any) {
      return e?.response?.data;
    }
  }

  async createcharge(data: any): promise<any> {
    const { correlationid, value, comment } = data;
    try {
      const { data } = await axios.post(
        "https://api.openpix.com.br/api/v1/charge?return_existing=true",
        { correlationid, value, comment },
        {
          headers: { authorization: this.apikey, "content-type": "application/json" },
        }
      );
      return data;
    } catch (e: any) {
      return e?.response?.data;
    }
  }

  async createsubscription(body: any): promise<any> {
    try {
      const { data } = await axios.post(
        "https://api.openpix.com.br/api/v1/subscriptions",
        body,
        {
          headers: { authorization: this.apikey, "content-type": "application/json" },
        }
      );
      return data;
    } catch (e: any) {
      return e?.response?.data;
    }
  }

  async getsubscription(id: string): promise<any> {
    try {
      const response = await axios.get(
        `https://api.openpix.com.br/api/v1/subscriptions/${id}`,
        {
          headers: { authorization: this.apikey, "content-type": "application/json" },
        }
      );
      return response?.data;
    } catch (e: any) {
      return e?.response?.data;
    }
  }

  async createcustomer(body: any): promise<any> {
    try {
      const { data } = await axios.post(
        "https://api.openpix.com.br/api/v1/customer",
        body,
        {
          headers: { authorization: this.apikey, "content-type": "application/json" },
        }
      );
      return data;
    } catch (e: any) {
      return e?.response?.data;
    }
  }

  async getcustomer(id: string): promise<any> {
    try {
      const response = await axios.get(
        `https://api.openpix.com.br/api/v1/customer/${id}`,
        {
          headers: { authorization: this.apikey, "content-type": "application/json" },
        }
      );
      return response?.data;
    } catch (e: any) {
      return e?.response?.data;
    }
  }

  async getchargebycustomer(correlationid: string): promise<any> {
    try {
      const response = await axios.get(
        `https://api.openpix.com.br/api/v1/charge?customer=${correlationid}&amp;status=active`,
        {
          headers: { authorization: this.apikey, "content-type": "application/json" },
        }
      );
      return response?.data;
    } catch (e: any) {
      return e?.response?.data;
    }
  }
}

export const makewooviadapter = () =&gt; {
  return new woovipaymentgateway(env.woovikey);
};
</any></any></any></any></any></any></any></any>

stripe支付网关

对于stripe,我们使用官方的stripe sdk。

// src/adapters/stripeadapter.ts
import { paymentgateway } from "../contracts";
import { env } from "../config";
import stripe from "stripe";

export class stripepaymentgateway extends paymentgateway {
  private stripe: stripe;

  constructor(paymentkey: string) {
    super();
    this.stripe = new stripe(paymentkey, {
      apiversion: "2023-10-16",
      typescript: true,
    });
  }

  async createprice(amount: number): promise<any> {
    try {
      const price = await this.stripe.prices.create({
        currency: "brl",
        unit_amount: amount,
        recurring: { interval: "month" },
        product_data: { name: "gold plan" },
      });
      return { price };
    } catch (e: any) {
      return e?.response?.data;
    }
  }

  async createsubscription(data: any): promise<any> {
    try {
      const subscription = await this.stripe.subscriptions.create({
        customer: data?.customer?.id ?? data?.customer?.correlationid,
        items: [{ price: data?.priceid }],
      });
      return { subscription };
    } catch (e: any) {
      return e?.response?.data;
    }
  }

  async getsubscription(id: string): promise<any> {
    try {
      const subscription = await this.stripe.subscriptions.retrieve(id);
      return { subscription };
    } catch (e: any) {
      return e?.response?.data;
    }
  }

  async deletecharge(id: string): promise<any> {
    try {
      const charge = await this.stripe.paymentintents.update(id, {
        metadata: { status: "canceled" },
      });
      return { charge, status: "ok" };
    } catch (e: any) {
      return e?.response?.data;
    }
  }

  async getcharge(id: string): promise<any> {
    try {
      const charge = await this.stripe.paymentintents.retrieve(id);
      return { charge };
    } catch (e: any) {
      return e?.response?.data;
    }
  }

  async createcharge(data: any): promise<any> {
    try {
      const charge = await this.stripe.paymentintents.create({
        amount: number(data?.value),
        currency: "brl",
        metadata: { metadata: json.stringify(data) },
        automatic_payment_methods: { enabled: true },
      });
      return { charge };
    } catch (e: any) {
      return e?.response?.data;
    }
  }

  async createcustomer(data: any): promise<any> {
    const { email, description } = data;
    try {
      const customer: stripe.customer = await this.stripe.customers.create({
        description,
        email

,
      });
      return { customer };
    } catch (e: any) {
      return e?.response?.data;
    }
  }

  async getcustomer(id: string): promise<any> {
    try {
      const customer = await this.stripe.customers.retrieve(id);
      return { customer };
    } catch (e: any) {
      return e?.response?.data;
    }
  }
}

export const makestripeadapter = () =&gt; {
  return new stripepaymentgateway(env.stripekeysecret);
};
</any></any></any></any></any></any></any></any>

pagar.me 支付网关

pagar.me 的文档详细介绍了如何使用其 api 创建客户端。通过向 /customers 端点发出 post 请求,可以在平台上注册新客户。需要注意的是,电子邮件字段是唯一的:如果已经存在具有相同电子邮件的客户,则数据将被更新,而不是创建新记录。此外,持有护照的客户只能使用有效的国际地址进行交易。

现在,根据这个文档解释pagarmeadapter:

解释 pagarmeadapter

pagarmeadapter 是适配器的实现,它允许您与 pagar.me api 交互以创建和管理客户、费用和订阅。它使用 axios 库对 pagar.me api 进行 http 调用。

创建客户函数

此函数向 pagar.me /customers 端点发送 post 请求,并在请求正文中传递客户数据。 axios 使用 api 令牌(bearer ${this.apikey})处理身份验证并返回创建或更新的客户端数据。

使用示例

async createcustomer(data: any): promise<any> {
    try {
        const response = await axios.post(
            "https://api.pagar.me/1/customers",
            data,
            {
                headers: { authorization: `bearer ${this.apikey}` },
            }
        );
        return response?.data;
    } catch (e: any) {
        return e?.response?.data;
    }
}
</any>

此功能对于使用适配器模式直接从 node.js 应用程序在 pagar.me 上注册或更新客户至关重要,确保系统的灵活性和模块化。

有关在 pagar.me 创建客户的更多详细信息,请参阅此处的官方文档。

获取客户

pagar.me 文档解释了如何使用 api 获取已注册客户的详细信息。具体的端点是 get https://api.pagar.me/core/v5/customers/{customer_id},其中 {customer_id} 是您要查询的客户的标识符。

pagarmeadapter说明-getcustomer函数

pagarmeadapter 中的 getcustomer 函数正是执行此操作。它使用提供的 customer_id 向 pagar.me 端点发出 get 请求。这是它的工作原理:

  1. 身份验证: 该函数使用 api 令牌(bearer ${this.apikey})来验证请求。
  2. 请求: 对 pagar.me 端点进行 get 调用,获取与 customer_id 对应的客户详细信息。
  3. response: 请求成功则返回客户端数据,失败则返回错误响应。

使用示例

async getcustomer(id: string): promise<any> {
    try {
        const response = await axios.get(
            `https://api.pagar.me/1/customers/${id}`,
            {
                headers: { authorization: `bearer ${this.apikey}` },
            }
        );
        return response?.data;
    } catch (e: any) {
        return e?.response?.data;
    }
}
</any>

此功能允许您直接从 pagar.me api 获取有关特定客户的详细信息,轻松将此功能集成到您的 node.js 系统中。更多详细信息,您可以参考这里的官方文档。

创建交易

pagar.me 文档解释了如何使用 api 获取已注册客户的详细信息。具体的端点是 get https://api.pagar.me/core/v5/customers/{customer_id},其中 {customer_id} 是您要查询的客户的标识符。

pagarmeadapter说明-getcustomer函数

pagarmeadapter 中的 getcustomer 函数正是执行此操作。它使用提供的 customer_id 向 pagar.me 端点发出 get 请求。这是它的工作原理:

  1. 身份验证: 该函数使用 api 令牌(bearer ${this.apikey})来验证请求。
  2. 请求: 对 pagar.me 端点进行 get 调用,获取与 customer_id 对应的客户详细信息。
  3. response: 请求成功则返回客户端数据,失败则返回错误响应。

使用示例

async getcustomer(id: string): promise<any> {
    try {
        const response = await axios.get(
            `https://api.pagar.me/1/customers/${id}`,
            {
                headers: { authorization: `bearer ${this.apikey}` },
            }
        );
        return response?.data;
    } catch (e: any) {
        return e?.response?.data;
    }
}
</any>

此功能允许您直接从 pagar.me api 获取有关特定客户的详细信息,并轻松将此功能集成到您的 node.js 系统中。更多详细信息,您可以参考这里的官方文档。
我们将按照 pagar.me api 文档扩展 pagarmeadapter 以包含处理信用卡交易的特定方法。我还将提供示例测试负载,您可以使用它来验证每种方法。

信用卡的 pagarmeadapter 方法

这是 pagarmeadapter 方法的实现:

import axios from "axios";
import { paymentgateway } from "../contracts";
import { env } from "../config";

export class pagarmepaymentgateway extends paymentgateway {
  private apikey: string;

  constructor(paymentkey: string) {
    super();
    this.apikey = paymentkey;
  }

  async createcharge(data: any): promise<any> {
    try {
      const response = await axios.post(
        "https://api.pagar.me/1/transactions",
        data,
        {
          headers: { authorization: `bearer ${this.apikey}` },
        }
      );
      return response?.data;
    } catch (e: any) {
      return e?.response?.data;
    }
  }

  async deletecharge(id: string): promise<any> {
    try {
      const response = await axios.delete(
        `https://api.pagar.me/1/transactions/${id}`,
        {
          headers: { authorization: `bearer ${this.apikey}` },
        }
      );
      return response?.data;
    } catch (e: any) {
      return e?.response?.data;
    }
  }

  async getcharge(id: string): promise<any> {
    try {
      const response = await axios.get(
        `https://api.pagar.me/1/transactions/${id}`,
        {
          headers: { authorization: `bearer ${this.apikey}` },
        }
      );
      return response?.data;
    } catch (e: any) {
      return e?.response?.data;
    }
  }

  async capturecharge(id: string, amount: number): promise<any> {
    try {
      const response = await axios.post(
        `https://api.pagar.me/1/transactions/${id}/capture`,
        { amount },
        {
          headers: { authorization: `bearer ${this.apikey}` },
        }
      );
      return response?.data;
    } catch (e: any) {
      return e?.response?.data;
    }
  }

  async refundcharge(id: string, amount: number): promise<any> {
    try {
      const response = await axios.post(
        `https://api.pagar.me/1/transactions/${id}/refund`,
        { amount },
        {
          headers: { authorization: `bearer ${this.apikey}` },
        }
      );
      return response?.data;
    } catch (e: any) {
      return e?.response?.data;
    }
  }
}

export const makepagarmeadapter = () =&gt; {
  return new pagarmepaymentgateway(env.pagarmekey);
};
</any></any></any></any></any>

测试有效负载示例

  1. 信用卡交易创建(验证和捕获)
{
    "amount": 2990,
    "payment_method": "credit_card",
    "card_number": "4000000000000010",
    "card_cvv": "123",
    "card_expiration_date": "1225",
    "card_holder_name": "tony stark",
    "customer": {
        "external_id": "#3311",
        "name": "tony stark",
        "type": "individual",
        "country": "br",
        "email": "tonystark@avengers.com",
        "documents": [
            {
                "type": "cpf",
                "number": "12345678909"
            }
        ],
        "phone_numbers": ["+5511999998888"],
        "birthday": "1967-03-01"
    },
    "billing": {
        "name": "tony stark",
        "address": {
            "country": "br",
            "state": "sp",
            "city": "sao paulo",
            "neighborhood": "bela vista",
            "street": "avenida paulista",
            "street_number": "1000",
            "zipcode": "01310000"
        }
    },
    "items": [
        {
            "id": "r123",
            "title": "chaveiro do tesseract",
            "unit_price": 2990,
            "quantity": 1,
            "tangible": true
        }
    ]
}
  1. 预授权交易捕获
{
    "amount": 2990
}
  1. 交易退款
{
    "amount": 2990
}

解释

  • createcharge:创建新的信用卡交易。
  • deletecharge:取消现有交易。
  • getcharge:获取特定交易的详细信息。
  • capturecharge:捕获先前已授权的交易。
  • refundcharge:撤销交易。

这些方法涵盖了您可以使用 pagar.me api 对信用卡交易执行的主要操作。提供的有效负载是可用于测试这些功能的基本示例。

完整代码

// src/adapters/PagarmeAdapter.ts
import axios from "axios";
import { PaymentGateway } from "../contracts";
import { env } from "../config";

export class PagarmePaymentGateway extends PaymentGateway {
  private apiKey: string;

  constructor(paymentKey: string) {
    super();
    this.apiKey = paymentKey;
  }

  async createCharge(data: any): Promise<any> {
    try {
      const response = await axios.post(
        "https://api.pagar.me/1/transactions",
        data,
        {
          headers: { Authorization: `Bearer ${this.apiKey}` },
        }
      );
      return response?.data;
    } catch (e: any) {
      return e?.response?.data;
    }
  }

  async deleteCharge(id: string): Promise<any> {
    try {
      const response = await axios.delete(
        `https://api.pagar.me/1/transactions/${id}`,
        {
          headers: { Authorization: `Bearer ${this.apiKey}` },
        }
      );
      return response?.data;
    } catch (e: any) {
      return e?.response?.data;
    }
  }

  async getCharge(id: string): Promise<any> {
    try {
      const response = await axios.get(
        `https://api.pagar.me/1/transactions/${id}`,
        {
          headers: { Authorization: `Bearer ${this.apiKey}` },
        }
      );
      return response?.data;
    } catch (e: any) {
      return e?.response?.data;
    }
  }

  async createSubscription(data: any): Promise<any> {
    try {
      const response = await axios.post(
        "https://api.pagar.me/1/subscriptions",
        data,
        {
          headers: { Authorization: `Bearer ${this.apiKey}` },
        }
      );
      return response?.data;
    } catch (e: any) {
      return e?.response?.data;
    }
  }

  async getSubscription(id: string): Promise<any> {
    try {
      const response = await axios.get(
        `https://api.pagar.me/1/subscriptions/${id}`,
        {
          headers: { Authorization: `Bearer ${this.apiKey}` },
        }
      );
      return response?.data;
    } catch (e: any) {
      return e?.response?.data;
    }
  }

  async createCustomer(data: any): Promise<any> {
    try {
      const response = await axios.post(
        "https://api.pagar.me/1/customers",
        data,
        {
          headers: { Authorization: `Bearer ${this.apiKey}` },
        }
      );
      return response?.data;
    } catch (e: any) {
      return e?.response?.data;
    }
  }

  async getCustomer(id: string): Promise<any> {
    try {
      const response = await axios.get(
        `https://api.pagar.me/1/customers/${id}`,
        {
          headers: { Authorization: `Bearer ${this.apiKey}` },
        }
      );
      return response?.data;
    } catch (e: any) {
      return e?.response?.data;
    }
  }

  async getChargeByCustomer(correlationID: string): Promise<any> {
    try {
      const response = await axios.get(
        `https://api.pagar.me/1/transactions?customer=${correlationID}`,
        {
          headers: { Authorization: `Bearer ${this.apiKey}` },
        }
      );
      return response?.data;
    } catch (e: any) {
      return e?.response?.data;
    }
  }
}

export const makePagarmeAdapter = () =&gt; {
  return new PagarmePaymentGateway(env.pagarmeKey);
};
</any></any></any></any></any></any></any></any>

结论

使用typescript中的adapter模式实现支付网关,使代码集成和维护变得更加容易。通过采用这种方法,您可以保证系统的灵活性和模块化,从而能够轻松添加或更换网关。

要更详细、更实际地了解如何使用 node.jsfastify 实现支付网关,请观看我们在 crazystack node.js 第 99 类中的完整视频教程。不要错过这个加深知识并掌握最佳支付系统开发实践的机会。

?重要链接:

  • crazystack typescript 课程:crazystack.com.br
  • github 上的存储库:crazystacknodejs

本课程是训练营形式的实用强化培训,重点针对想要改进编写代码方式的全职和高级开发人员。您将学习先进的概念,例如设计模式清洁架构tddddd,并通过node.jsfastify应用于实际项目。

了解更多并报名!

以上就是支付网关一般不必太复杂的详细内容,更多请关注php中文网其它相关文章!