POPBill Developers
가이드

튜토리얼

.NET Core 개발환경에서 팝빌 SDK를 추가하여 단문 문자 메시지 전송 (SendSMS) 함수를 구현하는 예시입니다.

1. POPBiLL SDK 추가

[프로젝트 > NuGet 패키지 관리] 메뉴에서 popbill을 검색하여 최신 버전의 패키지를 설치합니다.

2. POPBiLL SDK 설정

① 프로젝트의 Startup.cs 파일에 문자 서비스 인스턴스 클래스를 생성하고, Startup클래스의 ConfigureServices() 함수에 의존성 주입 패턴으로 Singleton 서비스 인스턴스를 추가합니다.

② 문자 서비스명으로 컨트롤러를 생성하고 생성한 컨트롤러의 생성자 함수에서 문자 인스턴스 객체를 할당합니다.

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Popbill.Message;


public class MessageInstance
{
    // 연동신청 후 메일로 발급받은 링크아이디(LinkID)와 비밀키(SecretKey)값 으로 변경하시기 바랍니다.
    private string linkID = "TESTER";
    private string secretKey = "SwWxqU+0TErBXy/9TVjIPEnI0VTUMMSQZtJf3Ed8q3I=";

    public MessageService messageService;

    public MessageInstance()
    {
        // 문자 서비스 객체 초기화
        messageService = new MessageService(linkID, secretKey);

        // 연동환경 설정값, 개발용(true), 상업용(false)
        messageService.IsTest = true;

        // 인증토큰 아이피 제한 기능 사용여부 권장(true)
        messageService.IPRestrictOnOff = true;

        // 팝빌 API 서비스 고정 IP 사용여부, true-사용, false-미사용, 기본값(false)
        messageService.UseStaticIP = false;

        // 로컬시스템 시간 사용여부, true(사용) - 기본값, false(미사용)
        messageService.UseLocalTimeYN = true;
    }
}

namespace MessageExample
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            // 문자 서비스 객체 의존성 주입
            services.AddSingleton<MessageInstance>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Message}/{action=Index}");
            });
        }
    }
}

3. SendSMS 기능 구현

문자 서비스명으로 생성한 컨트롤러의 생성자 함수에 인스턴스 객체를 할당하고, 단문 문자 메시지 전송 함수(SendSMS) 호출 코드를 추가합니다.

// Controllers/MessageController.cs

using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Popbill;
using Popbill.Message;

namespace MessageExample.Controllers
{
    public class MessageController : Controller
    {
        private readonly MessageService _messageService;

        public MessageController(MessageInstance MSGinstance)
        {
            // 문자 서비스 객체 주입
            _messageService = MSGinstance.messageService;
        }

        public IActionResult SendSMS()
        {
            //팝빌 연동회원 사업자번호 (하이픈 '-' 제외 10자리)
            string corpNum = "1234567890";

            //팝빌 연동회원 아이디
            string userID = "testkorea";

            // 발신번호
            string senderNum = "07043042992";

            // 발신자명
            string senderName = "발신자명";

            // 수신번호
            string receiverNum = "010111222";

            // 수신자명
            string receiverName = "수신자명";

            // 메시지내용, 90byte초과된 내용은 삭제되어 전송됨.
            string contents = "단문 문자 메시지 내용. 90byte 초과시 삭제되어 전송";

            // 예약전송일시(yyyyMMddHHmmss), null인 경우 즉시전송
            // ex) DateTime sndDT = new DateTime(20220130120000);
            DateTime? sndDT = null;

            // 광고문자여부 (기본값 false)
            // [참고] "광고메시지 전송방법 안내" [ http://blog.linkhubcorp.com/2642/ ]
            bool adsYN = false;

            // 전송요청번호, 파트너가 전송요청에 대한 관리번호를 직접 할당하여 관리하는 경우 기재
            // 최대 36자리, 영문, 숫자, 언더바('_'), 하이픈('-')을 조합하여 사업자별로 중복되지 않도록 구성
            string requestNum = "";

            try
            {
                var receiptNum = _messageService.SendSMS(corpNum, senderNum, senderName, receiverNum,
                          receiverName, contents, sndDT, adsYN, requestNum);
                return View("Response", receiptNum);
            }
            catch (PopbillException pe)
            {
                return View("Exception", pe);
            }
        }
    }
}

4. 결과 확인

함수 호출이 정상적으로 처리된 경우 Response가 "성공"으로 반환되며, 실패일 경우 PopbillException으로 오류코드("-"로 시작하는 8자리 숫자값)와 오류메시지가 반환됩니다. [오류코드] 바로가기