0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

郵便番号・デジタルアドレスAPI(ver2.0)対応の郵便番号取得PHP

0
Last updated at Posted at 2026-07-28

適当に書いてGeminiにリライトしてもらった(笑)

address-api.php
<?php
/*
 * 郵便番号・デジタルアドレスAPI(ver2.0)対応
 * $_SESSION['API_TOKEN'] = bin2hex(random_bytes(32));
 * address-api.php?zipcode=1000001&t=$_SESSION['API_TOKEN']
 */
define('CLIENT_ID', '');
define('SECRET_KEY', '');
if (is_file(__DIR__ . '/cacert.pem')) {
    define('CACERT_PATH', __DIR__ . '/cacert.pem');
}

define('URL_TOKEN', 'https://api.da.pf.japanpost.jp/api/v2/j/token');
define('URL_SEARCH', 'https://api.da.pf.japanpost.jp/api/v2/searchcode/');
define('HEADER_USERAGENT', 'User-Agent: Mozilla/5.0 (compatible; PHP cURL)');

// 許可する自サイトのドメイン(環境に合わせて直接指定、またはHostチェック)
define('ALLOW_ORIGIN', (empty($_SERVER['HTTPS']) ? 'http://' : 'https://') . ($_SERVER['HTTP_HOST'] ?? ''));

/**
 * JSON形式でメッセージを出力して処理を終了する
 */
function resultmsg(int $status, string $msg): void
{
    // CORS制御
    if (defined('ALLOW_ORIGIN') && ALLOW_ORIGIN !== '') {
        header('Access-Control-Allow-Origin: ' . ALLOW_ORIGIN);
    }
    header('Content-Type: application/json; charset=utf-8');
    http_response_code($status);
    echo json_encode(['message' => $msg], JSON_UNESCAPED_UNICODE);
    exit;
}

// -----------------------------------------------------------------------------
// 0. セッションとワンタイムトークン(CSRF)の検証
// -----------------------------------------------------------------------------
session_start();

$sessionToken = $_SESSION['API_TOKEN'] ?? '';
$requestToken = $_GET['t'] ?? '';

// hash_equals でタイミング攻撃を防止しつつ安全に比較
if ($sessionToken === '' || $requestToken === '' || !hash_equals($sessionToken, $requestToken)) {
    resultmsg(403, 'アクセスが不正です。'.$requestToken); // 505 から 403 に変更
}

// ワンタイム化する場合(1回の呼び出しでトークンを破棄)
// unset($_SESSION['API_TOKEN']);

/**
 * cURLリクエストの共通実行関数
 */
function execCurlRequest(string $url, array $headers = [], ?array $postData = null): array
{
    $ch = curl_init($url);

    // 共通オプション
    $options = [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 10,
        CURLOPT_HTTPHEADER     => array_merge([HEADER_USERAGENT], $headers),
    ];
    
    if (defined('CACERT_PATH')) {
        $options[CURLOPT_CAINFO] = CACERT_PATH;
    }

    // POST指定がある場合の設定
    if ($postData !== null) {
        $options[CURLOPT_POST] = true;
        $options[CURLOPT_POSTFIELDS] = json_encode($postData);
    }

    curl_setopt_array($ch, $options);

    $response = curl_exec($ch);
    
    // cURL自体のネットワークエラー判定
    if ($response === false) {
        $error = curl_error($ch);
        curl_close($ch);
        resultmsg(500, '通信エラーが発生しました: ' . $error);
    }

    $httpCode = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
    curl_close($ch);

    return [
        'status' => $httpCode,
        'body'   => json_decode($response, true)
    ];
}

// -----------------------------------------------------------------------------
// 1. Referer(アクセス元ページ)のチェック
// -----------------------------------------------------------------------------
$referer = $_SERVER['HTTP_REFERER'] ?? '';
if ($referer === '' || strpos($referer, ALLOW_ORIGIN) !== 0) {
    resultmsg(403, '許可されていないアクセスです');
}

// -----------------------------------------------------------------------------
// 2. 入力値のバリデーション
// -----------------------------------------------------------------------------
$zipcode = preg_replace('/\D/', '', $_GET['zipcode'] ?? '');
if (!preg_match('/^\d{7}$/', $zipcode)) {
    resultmsg(400, '郵便番号は7桁で指定してください');
}

// -----------------------------------------------------------------------------
// 3. トークン取得処理
// -----------------------------------------------------------------------------
$tokenParams = [
    'grant_type' => 'client_credentials',
    'client_id'  => CLIENT_ID,
    'secret_key' => SECRET_KEY,
];

$tokenRes = execCurlRequest(URL_TOKEN, ['Content-Type: application/json'], $tokenParams);

if ($tokenRes['status'] !== 200) {
    $errorMsg = $tokenRes['body']['message'] ?? 'アクセストークンの取得に失敗しました';
    resultmsg($tokenRes['status'], $errorMsg);
}

$accessToken = $tokenRes['body']['token'] ?? null;
if (!$accessToken) {
    resultmsg(500, '認証レスポンスの解析に失敗しました');
}

// -----------------------------------------------------------------------------
// 4. 住所検索処理
// -----------------------------------------------------------------------------
$searchHeaders = [
    'Authorization: Bearer ' . $accessToken,
];

$searchRes = execCurlRequest(URL_SEARCH . $zipcode, $searchHeaders);

if ($searchRes['status'] !== 200) {
    $errorMsg = $searchRes['body']['message'] ?? '住所検索APIでエラーが発生しました';
    resultmsg($searchRes['status'], $errorMsg);
}

if (!empty($searchRes['body']['addresses'][0])) {
    $addrData = $searchRes['body']['addresses'][0];
    
    $pref = $addrData['pref_name'] ?? '';
    $city = $addrData['city_name'] ?? '';
    $town = $addrData['town_name'] ?? '';
    
    resultmsg(200, $pref . $city . $town);
}

$failMsg = $searchRes['body']['message'] ?? '該当する住所が見つかりませんでした。';
resultmsg(400, $failMsg);

cacert.pemはここから入手
php.iniで設定してれば不要

呼び出し側は

index.php
<!doctype html>
<html lang="ja">
<?php
session_start();
$_SESSION['API_TOKEN'] = bin2hex(random_bytes(32));
?>
<!doctype html>
<html lang="ja">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>テスト</title>
</head>
<body>
	<main>
		<form action="#" method="post">
		<div>
			<div>
				<div><label for="inpostal">郵便番号</label></div>
				<div>
					<input type="tel" name="postal" value="" id="inpostal" style="width: 7rem;" required>
					<button type="button" onclick="searchAddress()">住所取得</button>
					<div id="result"></div>
				</div>
			</div>
			<div>
				<div><label for="inaddress">ご住所</label></div>
				<div><input type="text" name="address" value="" id="inaddress" required></div>
			</div>
		</div>
		<script>
			async function searchAddress() {
			  const zipcode = document.getElementById('inpostal').value;
			  const address = document.getElementById('inaddress');
			  const result = document.getElementById('result');

			  address.value = '';
			  result.textContent = '';
			  try {
				const res = await fetch('./address-api.php?zipcode=' + encodeURIComponent(zipcode) + '&t=<?=$_SESSION['API_TOKEN'];?>');
				const json = await res.json();

				if (!res.ok) {
				  result.textContent = json.message || '住所取得に失敗しました';
				  return;
				}

				address.value = json.message || '';
			  } catch (error) {
				result.textContent = error.message;
			  }
			}
		</script>
		</form>
	</main>
</body>
</html>
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?