pauth.me × Spring Boot — 着信認証API実装ガイド
Java/Spring BootプロジェクトにpAuth着信認証APIを組み込む手順を解説します。 WebClientを使った非同期HTTP通信と、Spring Sessionによるセッション管理で実装します。
※本ページのコード例は説明目的の擬似コードです。実際の実装では環境に合わせた調整が必要です。
前提条件
- Java 17以上 / Spring Boot 3.0以上
- pauth.me APIキー(無料登録で取得)
- spring-boot-starter-webflux(WebClient使用のため)
Step 1: application.propertiesの設定
# application.properties
pauth.api-key=${PAUTH_API_KEY}
pauth.base-url=https://api.pauth.me
Step 2: PauthServiceの作成
// PauthService.java
@Service
public class PauthService {
@Value("${pauth.api-key}")
private String apiKey;
@Value("${pauth.base-url}")
private String baseUrl;
private final WebClient webClient = WebClient.create();
public Map createSession(String phoneNumber, String callbackUrl) {
return webClient.post()
.uri(baseUrl + "/v1/auth/sessions")
.header("Authorization", "Bearer " + apiKey)
.bodyValue(Map.of(
"phone_number", phoneNumber,
"callback_url", callbackUrl
))
.retrieve()
.bodyToMono(Map.class)
.block();
}
public Map getSessionStatus(String sessionId) {
return webClient.get()
.uri(baseUrl + "/v1/auth/sessions/" + sessionId)
.header("Authorization", "Bearer " + apiKey)
.retrieve()
.bodyToMono(Map.class)
.block();
}
}
Step 3: RESTコントローラの実装
// AuthController.java
@RestController
@RequestMapping("/api/auth")
public class AuthController {
@Autowired
private PauthService pauthService;
@PostMapping("/start")
public ResponseEntity> startVerification(
@RequestBody Map body,
HttpSession session) {
var result = pauthService.createSession(
body.get("phoneNumber"),
"https://your-app.com/api/auth/callback"
);
session.setAttribute("pauthSessionId", result.get("id"));
return ResponseEntity.ok(Map.of(
"sessionId", result.get("id"),
"callNumber", result.get("call_number")
));
}
@GetMapping("/status")
public ResponseEntity> checkStatus(HttpSession session) {
String sessionId = (String) session.getAttribute("pauthSessionId");
var data = pauthService.getSessionStatus(sessionId);
return ResponseEntity.ok(Map.of("status", data.get("status")));
}
}
エラーハンドリング
// WebClientのエラー処理
.retrieve()
.onStatus(HttpStatusCode::is4xxClientError, response ->
Mono.error(new PauthApiException("クライアントエラー: " + response.statusCode())))
.onStatus(HttpStatusCode::is5xxServerError, response ->
Mono.error(new PauthApiException("サーバーエラー: API一時停止中")))
// @ExceptionHandler
@ExceptionHandler(PauthApiException.class)
public ResponseEntity> handlePauthError(PauthApiException e) {
return ResponseEntity.status(503).body(Map.of("error", e.getMessage()));
}
本番環境の注意点
- APIキーは環境変数
PAUTH_API_KEYで渡し、application.propertiesにハードコードしない - Spring Sessionを使用し、セッションをRedis等の外部ストアで管理する
- WebClientにタイムアウト設定を追加する(
.timeout(Duration.ofSeconds(10))) - 本番では
@Profile("production")でAPIキーの設定を分離する