pauth.me × Ruby on Rails — 着信認証API実装ガイド
RailsプロジェクトにpAuth着信認証APIを組み込む手順を解説します。 サービスクラスとコントローラを組み合わせてクリーンな実装を実現します。
※本ページのコード例は説明目的の擬似コードです。実際の実装では環境に合わせた調整が必要です。
前提条件
- Ruby 3.0以上 / Rails 7以上
- pauth.me APIキー(無料登録で取得)
- faraday gem(HTTPクライアント)
Step 1: Gemfileへの追加と環境変数
# Gemfile
gem 'faraday'
# .env または config/credentials.yml.enc
PAUTH_API_KEY=your_api_key_here
PAUTH_BASE_URL=https://api.pauth.me
Step 2: PauthServiceクラスの作成
# app/services/pauth_service.rb
class PauthService
BASE_URL = ENV['PAUTH_BASE_URL']
API_KEY = ENV['PAUTH_API_KEY']
def self.create_session(phone_number:, callback_url:)
conn = Faraday.new(BASE_URL) do |f|
f.request :json
f.response :json
f.headers['Authorization'] = "Bearer #{API_KEY}"
end
response = conn.post('/v1/auth/sessions', {
phone_number: phone_number,
callback_url: callback_url
})
raise "pAuth API error: #{response.body}" unless response.success?
response.body
end
def self.check_status(session_id)
conn = Faraday.new(BASE_URL) do |f|
f.response :json
f.headers['Authorization'] = "Bearer #{API_KEY}"
end
conn.get("/v1/auth/sessions/#{session_id}").body
end
end
Step 3: コントローラでの利用
# app/controllers/auth_controller.rb
class AuthController < ApplicationController
def start
result = PauthService.create_session(
phone_number: params[:phone_number],
callback_url: auth_callback_url
)
session[:pauth_session_id] = result['id']
render json: { session_id: result['id'], call_number: result['call_number'] }
rescue => e
render json: { error: e.message }, status: :unprocessable_entity
end
def status
data = PauthService.check_status(session[:pauth_session_id])
if data['status'] == 'verified'
sign_in User.find_by(phone: data['phone_number'])
end
render json: { status: data['status'] }
end
end
エラーハンドリング
# APIエラーをrescueして適切なメッセージを返す
rescue Faraday::TimeoutError
render json: { error: '接続タイムアウト' }, status: :gateway_timeout
rescue Faraday::ConnectionFailed
render json: { error: 'API接続に失敗しました' }, status: :service_unavailable
# セッション期限切れ
if data['status'] == 'expired'
session.delete(:pauth_session_id)
render json: { status: 'expired', message: '再度お試しください' }, status: :request_timeout
end
本番環境の注意点
- APIキーは
Rails.application.credentialsまたは環境変数で管理する - セッションIDはRailsセッション(cookie-based)またはRedisで管理する
- ポーリングはJavaScript側で実装し、最大試行回数を設定する(例:30回)
- 本番環境ではSSL証明書の検証を必ず有効にする