← 記事に戻る
# デジタルアドレスAPIのコードを書いてみました.書いたのは

おはようございます.デジタルアドレスAPIのコードを書いてみました.書いたのは生成AIだけど一度で上手く正しいコードが生成出来たわけではなくて二、三回の指示出しを行って下記のコードが生成されました.

> デジタルアドレスAPIを生成AIの呪文を唱えて作らせてみたよ.動かしていないけどたぶんあってそうなコードを出力してくれた.
> 動かすには企業さんか個人事業者で屋号を持ってないとAPI登録出来ないみたいな🤔
> 因みにIPアドレスは動かしているサーバーのIPだとか.<https://t.co/j6175GtSiX> [pic.twitter.com/CKbgTmNwsV](https://t.co/CKbgTmNwsV)
> 
> — 田岡 寿章(taoka\_toshiaki) (@taoka\_toshiaki) [May 26, 2025](https://twitter.com/taoka_toshiaki/status/1927145681954787732?ref_src=twsrc%5Etfw)



デジタルアドレスのAPIを使用するには企業もしくは個人事業者で屋号を登録されている方でないとAPIのアカウント登録は今のところ出来ないので、自分はリファレンスと生成AIが出力したコードを見て恐らく正しく処理されるだろうと思ったのでgist.githubに[公開](https://gist.github.com/taoka3/e0c3c9627ef0619727a8ca0a4e54483f)しました.

尚、引数にIPアドレスを渡さないといけない所があるけれど、これはサーバーのIPアドレスになります.

```

<?php

class JapanPostAPIClient
{
    private string $clientId;
    private string $secretKey;
    private string $clientIp;
    private ?string $accessToken = null;
    private ?array $lastResponse = null;

    public function __construct(string $clientId, string $secretKey, string $clientIp)
    {
        $this->clientId = $clientId;
        $this->secretKey = $secretKey;
        $this->clientIp = $clientIp;
    }

    public function authenticate(): self
    {
        $url = 'https://api.da.pf.japanpost.jp/api/v1/j/token';
        $data = json_encode([
            'grant_type' => 'client_credentials',
            'client_id' => $this->clientId,
            'secret_key' => $this->secretKey
        ]);

        $headers = [
            "Content-Type: application/json",
            "x-forwarded-for: {$this->clientIp}"
        ];

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        $response = curl_exec($ch);
        $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($httpcode !== 200) {
            throw new Exception("Token request failed with status {$httpcode}: {$response}");
        }

        $responseData = json_decode($response, true);
        $this->accessToken = $responseData['token'] ?? null;
        $this->lastResponse = $responseData;

        return $this;
    }

    public function searchCode(string $searchCode, array $params = []): self
    {
        if (!$this->accessToken) {
            throw new Exception("Access token is not set. Please call authenticate() first.");
        }

        $defaultParams = [
            'page' => 1,
            'limit' => 10,
            'choikitype' => 1,
            'searchtype' => 1
        ];

        $queryParams = http_build_query(array_merge($defaultParams, $params));
        $url = "https://api.da.pf.japanpost.jp/api/v1/searchcode/{$searchCode}?{$queryParams}";

        $headers = [
            "Authorization: Bearer {$this->accessToken}",
            "Accept: application/json"
        ];

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($httpCode !== 200) {
            throw new Exception("Search request failed with status {$httpCode}: {$response}");
        }

        $this->lastResponse = json_decode($response, true);
        return $this;
    }

    public function getJson(): string
    {
        return json_encode($this->lastResponse, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    }

    public function getArray(): ?array
    {
        return $this->lastResponse;
    }
}

// 使い方の例:
// $client = new JapanPostAPIClient('YOUR_CLIENT_ID', 'YOUR_SECRET_KEY', 'IPアドレス.xxx.xxx.xxx');
// echo $client->authenticate()->searchCode('1000001')->getJson();
```



明日へ続く

 [ ![](https://zip358.com/wp-content/uploads/2026/01/image-31.png) サイトを分離した話を黙々と書いていきます.

 ](https://zip358.com/2026/02/04/%e3%82%b5%e3%82%a4%e3%83%88%e3%82%92%e5%88%86%e9%9b%a2%e3%81%97%e3%81%9f%e8%a9%b1%e3%82%92%e9%bb%99%e3%80%85%e3%81%a8%e6%9b%b8%e3%81%84%e3%81%a6%e3%81%84%e3%81%8d%e3%81%be%e3%81%99.html) 

 [ ![](https://zip358.com/wp-content/uploads/2026/01/image-30-300x300.png) 半額セールでアドビ様を延長.

 ](https://zip358.com/2026/02/03/%e5%8d%8a%e9%a1%8d%e3%82%bb%e3%83%bc%e3%83%ab%e3%81%a7%e3%82%a2%e3%83%89%e3%83%93%e6%a7%98%e3%82%92%e5%bb%b6%e9%95%b7.html) 

 [ ![](https://zip358.com/wp-content/uploads/2026/01/image-29.png) 何の前触れもなく変えたのは初めてかも.

 ](https://zip358.com/2026/02/02/%e4%bd%95%e3%81%ae%e5%89%8d%e8%a7%a6%e3%82%8c%e3%82%82%e3%81%aa%e3%81%8f%e5%a4%89%e3%81%88%e3%81%9f%e3%81%ae%e3%81%af%e5%88%9d%e3%82%81%e3%81%a6%e3%81%8b%e3%82%82.html) 

 [ ![](https://zip358.com/wp-content/uploads/2023/01/you-300x300.png) 跳ねたいサイトで跳ねたい

 ](https://zip358.com/2026/02/01/%e8%b7%b3%e3%81%ad%e3%81%9f%e3%81%84%e3%82%b5%e3%82%a4%e3%83%88%e3%81%a7%e8%b7%b3%e3%81%ad%e3%81%9f%e3%81%84.html) 

 [ ![](https://zip358.com/wp-content/uploads/2026/01/image-36.png) 映画、機動戦士ガンダム 閃光のハサウェイ キルケーの魔女

 ](https://zip358.com/2026/01/31/%e6%98%a0%e7%94%bb%e3%80%81%e6%a9%9f%e5%8b%95%e6%88%a6%e5%a3%ab%e3%82%ac%e3%83%b3%e3%83%80%e3%83%a0-%e9%96%83%e5%85%89%e3%81%ae%e3%83%8f%e3%82%b5%e3%82%a6%e3%82%a7%e3%82%a4-%e3%82%ad%e3%83%ab%e3%82%b1.html)