github.com/sacloud/iaas-api-go@v1.12.0/example_esme_test.go (about)

     1  // Copyright 2022-2023 The sacloud/iaas-api-go Authors
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package iaas_test
    16  
    17  import (
    18  	"context"
    19  	"fmt"
    20  	"log"
    21  	"os"
    22  
    23  	"github.com/sacloud/iaas-api-go"
    24  	"github.com/sacloud/iaas-api-go/types"
    25  )
    26  
    27  func Example_sendSMSMessage() {
    28  	// 2要素認証SMSの送信例
    29  
    30  	// APIキー
    31  	token := os.Getenv("SAKURACLOUD_ACCESS_TOKEN")
    32  	secret := os.Getenv("SAKURACLOUD_ACCESS_TOKEN_SECRET")
    33  	destination := os.Getenv("SAKURACLOUD_ESME_DESTINATION") // 送信先電話番号 81 + 9012345678の形式で指定する
    34  	if token == "" || secret == "" || destination == "" {
    35  		log.Fatal("environment variable 'SAKURACLOUD_ACCESS_TOKEN'/'SAKURACLOUD_ACCESS_TOKEN_SECRET'/SAKURACLOUD_ESME_DESTINATION required")
    36  	}
    37  
    38  	// クライアントの作成
    39  	caller := iaas.NewClient(token, secret)
    40  	esmeOp := iaas.NewESMEOp(caller)
    41  
    42  	// ESMEの作成(初回のみ必要)
    43  	ctx := context.Background()
    44  	esme, err := esmeOp.Create(ctx, &iaas.ESMECreateRequest{
    45  		Name:        "libsacloud-example",
    46  		Description: "description",
    47  		Tags:        types.Tags{"tag1", "tag2"},
    48  	})
    49  	if err != nil {
    50  		log.Fatal(err)
    51  	}
    52  
    53  	// SMS送信(OTPは自動生成の場合)
    54  	result, err := esmeOp.SendMessageWithGeneratedOTP(ctx, esme.ID, &iaas.ESMESendMessageWithGeneratedOTPRequest{
    55  		Destination: destination,
    56  		Sender:      "example-sender",
    57  	})
    58  	if err != nil {
    59  		log.Fatal(err)
    60  	}
    61  
    62  	fmt.Printf("OTP(result): %s\n", result.OTP)
    63  
    64  	// OTPはログからも参照可能
    65  	logs, err := esmeOp.Logs(ctx, esme.ID)
    66  	if err != nil {
    67  		log.Fatal(err)
    68  	}
    69  	fmt.Printf("OTP(logs): %s\n", logs[0].OTP)
    70  }