CPFHub.io

使用 Ruby on Rails 查询巴西 CPF

在 Ruby on Rails 中通过基于 Net::HTTP 的 service object 查询 CPF(巴西个人税号),并在 controller 中调用。API 密钥保存在 Rails credentials 中。

正在使用 Cursor、Lovable、v0 或其他 AI 工具? 复制标准查询的提示词,粘贴到您的 AI 助手中。

在 Cursor 中打开

准备工作

  1. 在 app.cpfhub.io 免费创建账户。免费版包含 50 个积分,无需信用卡。
  2. 在 app.cpfhub.io/api-keys 复制您的 API 密钥。
  3. 将密钥保存在环境变量中,不要写进代码:
bash
export CPFHUB_API_KEY="sua_api_key"

示例

将密钥以 cpfhub_api_key 保存在 credentials 中(bin/rails credentials:edit),或保存在 CPFHUB_API_KEY 环境变量中。

Ruby
# app/services/cpfhub_client.rb
require 'net/http'

class CpfhubClient
  class Error < StandardError; end

  # Returns the "data" hash, or nil when the CPF is not in the database (404).
  def self.lookup(cpf)
    uri = URI("https://api.cpfhub.io/cpf/#{cpf}")
    req = Net::HTTP::Get.new(uri)
    req['x-api-key'] = Rails.application.credentials.cpfhub_api_key || ENV.fetch('CPFHUB_API_KEY')

    res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true, open_timeout: 5, read_timeout: 10) do |http|
      http.request(req)
    end
    body = JSON.parse(res.body)

    case res.code.to_i
    when 200 then body['data']
    when 404 then nil
    else
      # error is a string ("...") or an object ({ "message" => "..." })
      error = body['error']
      raise Error, "#{res.code}: #{error.is_a?(Hash) ? error['message'] : error}"
    end
  end
end
Ruby
# app/controllers/cpfs_controller.rb
class CpfsController < ApplicationController
  def show
    cpf = params[:id].to_s.gsub(/\D/, '')
    return render(json: { error: 'CPF must have 11 digits' }, status: :bad_request) unless cpf.length == 11

    data = CpfhubClient.lookup(cpf)
    if data
      render json: data
    else
      render json: { error: 'CPF not found' }, status: :not_found
    end
  rescue CpfhubClient::Error => e
    # 401, 403, 422, 429 and 5xx: log it and do not expose details to the client
    Rails.logger.error("CPFHub.io #{e.message}")
    render json: { error: 'CPF lookup is unavailable right now' }, status: :service_unavailable
  end
end

在 config/routes.rb 中添加路由 resources :cpfs, only: :show,然后用 curl http://localhost:3000/cpfs/12345678909 测试。

响应

查到 CPF(200,消耗 1 个积分):

JSON
{
  "success": true,
  "data": {
    "cpf": "12345678909",
    "name": "Fulano de Tal",
    "nameUpper": "FULANO DE TAL",
    "gender": "M",
    "birthDate": "15/06/1990",
    "day": 15,
    "month": 6,
    "year": 1990
  }
}

未查到 CPF(404,不消耗积分):

JSON
{
  "success": false,
  "data": null,
  "error": { "message": "CPF não encontrado na base de dados" }
}

CPF 12345678909 为虚构号码,仅用于示例。gender 可能为 null。error.message 的文本由 API 以葡萄牙语返回(意为“数据库中未找到该 CPF”)。

错误

状态码含义处理方式
404数据库中没有该 CPF按“未找到”处理。不消耗积分。
400 / 422CPF 不是 11 位数字或校验位无效修正输入。不消耗积分。
401缺少 API 密钥或密钥无效检查 CPFHUB_API_KEY 变量。
403积分已用完或账户未激活通过 GET /quota 查看余额,或在控制台充值。
429超出每分钟请求限制等待 Retry-After 响应头中的秒数,然后重试。
5xx临时故障几秒后重试。

error 字段可能是文本("error": "..."),也可能是对象("error": { "message": "..." }),取决于状态码。上面的示例已处理这两种格式。完整列表见错误代码。

下一步