본문 바로가기

Go

네이버 클라우드 플랫폼 카카오톡 알림톡 (golang)

https://www.ncloud.com/

 

NAVER CLOUD PLATFORM

cloud computing services for corporations, IaaS, PaaS, SaaS, with Global region and Security Technology Certification

www.ncloud.com

회원가입 or 로그인 -> 마이페이지 결재 카드 연동 후

마이페이지 -> 인증키 관리

신규 API 인증키 생성

 

아래의 Simple & Easy Notification Service 에 프로젝트 등록후 ServiceID 발급 

https://console.ncloud.com/sens/home

 

프로젝트 생성하기 클릭

Biz Message 체크후 원하는 프로젝트명과 설명 기입
Biz Message 에 알림톡 기능이 있다

이후 서비스 ID 자물쇠 클릭하면 ServiceID 가져올수있다. 로컬에 저장해놓으면 된다.

그 이후 아래 공식 nCloud 홈페이지에서의 가이드대로 따라오기
채널생성 -> 채널등록 -> 템플릿등록 

https://guide.ncloud-docs.com/docs/ko/sens-sens-1-5

템플릿등록을 하면 템플릿 검수를 받아야 한다.
템플릿 검수가 완료되면 이후에 사용가능

 

이후에 

https://api.ncloud-docs.com/docs/ko/ai-application-service-sens-alimtalkv2

 

알림톡 API - Simple & Easy Notification Service

 

api.ncloud-docs.com

알림톡 API 참고후 코드 작성

package main

import (
	"bytes"
	"crypto/hmac"
	"crypto/sha256"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"time"
)

type kakaoReq struct {
	PlusFriendId string         `json:"plusFriendId"`
	TemplateCode string         `json:"templateCode"`
	Messages     []kakaoMessage `json:"messages"`
}

type kakaoMessage struct {
	CountryCode    string         `json:"countryCode"`
	To             string         `json:"to"`
	Content        string         `json:"content"`
	Buttons        []kakaoButton  `json:"buttons"`
	UseSmsFailover bool           `json:"useSmsFailover"`
	FailoverConfig FailoverConfig `json:"failoverConfig"`
}

type kakaoButton struct {
	Type       string `json:"type"`
	Name       string `json:"name"`
	LinkMobile string `json:"linkMobile"`
	LinkPc     string `json:"linkPc"`
}

type FailoverConfig struct {
	Content string `json:"content"`
}

const AccessKeyID = "{Your Access Key ID}"
const SecretKey = "{Your SecretKey}"
const ServiceID = "{YOur Service ID}"
const plusFriendId = "@명스월드"

func main() {

	method := http.MethodPost
	host := "https://sens.apigw.ntruss.com"
	path := fmt.Sprintf("/alimtalk/v2/services/%s/messages", ServiceID)
	now := time.Now().Unix() * 1000
	signature := makeSignature(AccessKeyID, SecretKey, method, path, now)

	phoneNumber := "01012345678"
	tplCode := "{Your Template Code}"
	name := "myungsworld"
	message := fmt.Sprintf("환영합니다 %s님", name)

	reqBody := kakaoReq{
		PlusFriendId: plusFriendId,
		TemplateCode: tplCode,
		Messages: []kakaoMessage{
			{
				CountryCode:    "82",
				To:             phoneNumber,
				Content:        message,
				UseSmsFailover: false,
			},
		},
	}

	bodyByte, err := json.Marshal(reqBody)
	if err != nil {
		panic(err)
	}
	buff := bytes.NewBuffer(bodyByte)

	req, err := http.NewRequest(method, fmt.Sprintf("%s%s", host, path), buff)
	if err != nil {
		panic(err)
	}
	req.Header.Add("Content-Type", "application/json; charset=utf-8")
	req.Header.Add("x-ncp-apigw-timestamp", fmt.Sprintf("%d", now))
	req.Header.Add("x-ncp-iam-access-key", AccessKeyID)
	req.Header.Add("x-ncp-apigw-signature-v2", signature)

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		panic(err)
	}
	defer func(Body io.ReadCloser) {
		err := Body.Close()
		if err != nil {

		}
	}(resp.Body)

	bytes, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Println(err)
		panic(err)
	}

	fmt.Println(string(bytes))

}

func makeSignature(accessKeyID string, secretKey string, method string, path string, epochTime int64) string {
	const space = " "
	const newLine = "\n"
	h := hmac.New(sha256.New, []byte(secretKey))
	h.Write([]byte(method))
	h.Write([]byte(space))
	h.Write([]byte(path))
	h.Write([]byte(newLine))
	h.Write([]byte(fmt.Sprintf("%d", epochTime)))
	h.Write([]byte(newLine))
	h.Write([]byte(accessKeyID))
	rawSignature := h.Sum(nil)
	return base64.StdEncoding.EncodeToString(rawSignature)
}

성공시 아래와 같은 JSON 값 반환 해주고 카카오톡 채널에서 알림이 온다.

{
	"requestId":"askdjkasdjkasdjkasdjkas",
	"requestTime":"2022-10-12T17:50:27.462",
	"statusCode":"202","statusName":
	"processing",
	"messages":[
	  	{
			"messageId":"adfjadfjkadhfkjadkfjhad",
			"to":"01012345678",
			"countryCode":"82",
			"content":"환엽합니다 myungsworld님",
			"requestStatusCode":"A000",
			"requestStatusName":"success",
			"requestStatusDesc":"성공",
			"useSmsFailover":false
		}
	]
}