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?

【Go】twilio-goでTwilio 番号の検索・購入・削除を実装してみた

Last updated at Posted at 2025-09-30

はじめに

業務でTwilioを使った実装をする機会があり、電話番号の取得(購入)・SMS 送信といった機能をGo言語で実装をしました。その際に公式から出ているライブラリである twilio-go を採用しました。
今回は、twilio-go で、電話番号の検索・購入・削除の実装を行ってみたいと思います。

動作環境

  • Go 1.24(※1.20 以降なら概ね可)
  • Twilio アカウント(Console にログインできること)
  • 日本向け Regulatory Bundle(規制情報)審査済み であること
  • Address 登録(日本の電話番号の購入時に必須となります)

twilio-goのインストール

go get github.com/twilio/twilio-go

準備

今回はライブラリを使うためにベストプラクティスに従ってAPI キーとシークレットを使用します。
クライアントを初期化するための、API Keyをコンソールから作成します。
こちらはTwilioコンソールにログインして、Account ManagementからKeys&Credentials > APIKeys&tokenにて自身のアカウントの値を設定してください。

コンソールからの作成手順

1.API keys & tokensのトップページからCreate API keyを選択
APIKey作成前.png

2.API Keyを作成
APKey作成画面.png

Create後にSecret Keyが表示されます。

APIKey作成.png

Secret Keyに関しては作成直後しか表示されないため安全な場所へメモをしてください

3.作成完了
APIKey作成後.png

実装

ここでは利用可能な電話番号の取得、購入、購入した電話番号の削除それぞれの処理をtwilio-goを使って実装します。

電話番号の取得

利用可能な番号は、国コードと番号タイプごとのサブリソースに対してリクエストして検索します。

  • Local:地理番号(市外局番ベース)。例:+81...
  • Toll Free:フリーダイヤル。例:+81120... / +81800...
  • Mobile:モバイル番号(国によっては未提供/制限あり

:writing_hand:Toll Free は国内表記だと 0120 / 0800、E.164 では +81120 / +81800 になります。

main.go

package main

import (
	"fmt"
	"log"
	"os"

	"github.com/twilio/twilio-go"
	twilioApi "github.com/twilio/twilio-go/rest/api/v2010"
)

func main() {

	prefix := "+8150"

	client := twilio.NewRestClientWithParams(twilio.ClientParams{
		Username:   os.Getenv("TWILIO_API_KEY"),        // SK...
		Password:   os.Getenv("TWILIO_API_SECRET"),
		AccountSid: os.Getenv("TWILIO_ACCOUNT_SID"),    // AC...
	  })

	params := &twilioApi.ListAvailablePhoneNumberLocalParams{}
	params.SetContains(prefix)

    // CountryCodeにJP(日本)を指定
	resp, err := client.Api.ListAvailablePhoneNumberLocal("JP", params)
	if err != nil {
		log.Fatal(err)
	}

	var number twilioApi.ApiV2010AvailablePhoneNumberLocal
	var found bool
    // レスポンスから最初の1件を取得する
	for _, n := range resp {
		if n.Capabilities.Voice {
			number = n
			found = true
			break
		}
	}

	if !found {
		log.Fatal("No number found")
	}

	fmt.Println(*number.PhoneNumber)
}

利用可能な電話番号が取得できました。

go run main.go
+815017920325

コンソールで出力されて電話番号で検索すると、購入可能なことがわかります。
利用可能電話番号.png

電話番号の購入

先ほど取得できた電話番号を指定して、電話番号を購入します。
電話番号の購入については、BUNDLE_SIDADDRESS_SIDが追加で必要になります。

コンソールの以下のページから参照できます。
Phone Numbers > Regulatory Compliance > Bundles

・BUNDLE_SID (BU~から始まる値)
BUNDLE_SID.png

・ADDRESS_SID
Bundle名をクリック→ Bundleの詳細ページ
Address SIDのAD~から始まる値

main.go

package main

import (
	"fmt"
	"os"

	"github.com/twilio/twilio-go"
	twilioApi "github.com/twilio/twilio-go/rest/api/v2010"
)

func main() {

	client := twilio.NewRestClientWithParams(twilio.ClientParams{
		Username:   os.Getenv("TWILIO_API_KEY"),
		Password:   os.Getenv("TWILIO_API_SECRET"),
		AccountSid: os.Getenv("TWILIO_ACCOUNT_SID"),
	  })

	params := &twilioApi.CreateIncomingPhoneNumberParams{}
	params.SetPhoneNumber("+815017920325")
	params.SetAddressSid(os.Getenv("TWILIO_ADDRESS_SID"))
	params.SetBundleSid(os.Getenv("TWILIO_BUNDLE_SID_LOCAL"))

	resp, err := client.Api.CreateIncomingPhoneNumber(params)
	if err != nil {
		fmt.Println(err.Error())
	} else {
		fmt.Println("Phone Number Status: " + *resp.Status)
	}
}

実行します。

go run main.go
Phone Number Status: in-use

コンソールから購入した電話番号を確認できました

購入後.png

電話番号の削除

先ほど購入した電話番号を削除します。
電話番号を削除する際には電話番号を指定するのではなく、Phone Number SIDを指定して削除することになります。
そのため電話番号で情報を取得後、SIDを指定して削除を行います。

main.go
package main

import (
	"fmt"
	"os"

	"github.com/twilio/twilio-go"
	twilioApi "github.com/twilio/twilio-go/rest/api/v2010"
)

func main() {

	client := twilio.NewRestClientWithParams(twilio.ClientParams{
		Username:   os.Getenv("TWILIO_API_KEY"),
		Password:   os.Getenv("TWILIO_API_SECRET"),
		AccountSid: os.Getenv("TWILIO_ACCOUNT_SID"),
	  })


	params := &twilioApi.ListIncomingPhoneNumberParams{}
	params.SetPhoneNumber("+815017920325")

	resp, err := client.Api.ListIncomingPhoneNumber(params)
	if err != nil {
		fmt.Println(err.Error())
		return
	}

	//Twilioの電話番号は基本1つなので0もしくは2つ以上の場合はエラーを返す
	if len(resp) > 1 {
		fmt.Println("Multiple matching Twilio phone numbers found")
		return
	}
	if len(resp) == 0 {
		fmt.Println("No matching Twilio phone number found")
		return
	}

	incomingNumber := &resp[0]

	if err := client.Api.DeleteIncomingPhoneNumber(*incomingNumber.Sid, nil); err != nil {
		fmt.Println(err.Error())
		return
	}

	fmt.Println("deleted incoming number:", *incomingNumber.Sid)
}

削除が成功しました。

go run main.go
deleted incoming number: PNxxxxxxxxxxxxxxxxxxxx79

削除に成功した電話番号については、コンソールのReleased Numbersより確認することができます。無事削除できていることをコンソールからも確認することができました。

電話番号削除.png

まとめ

本記事では、twilio-goで利用可能番号の取得・購入・削除までを実装しました。
公式ドキュメント/サンプルが充実しているので、手元で動かしながら拡張してみてください。

参考

https://pkg.go.dev/github.com/twilio/twilio-go@v1.28.0#section-readme
https://www.twilio.com/docs/phone-numbers

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?