첨부 실행 코드는 나눔고딕코딩 폰트를 사용합니다.
728x90
반응형
728x170

TestProject.zip
0.01MB

▶ KakaoAPIHelper.cs

namespace TestProject
{
    /// <summary>
    /// 카카오 API 헬퍼
    /// </summary>
    public static class KakaoAPIHelper
    {
        //////////////////////////////////////////////////////////////////////////////////////////////////// Field
        ////////////////////////////////////////////////////////////////////////////////////////// Static
        //////////////////////////////////////////////////////////////////////////////// Public

        #region Field

        /// <summary>
        /// 애플리케이션 ID
        /// </summary>
        public static readonly string APPLICATION_ID = "[애플리케이션 ID를 설정한다.]";

        /// <summary>
        /// REST API 키
        /// </summary>
        public static readonly string REST_API_KEY = "[REST API 키를 설정한다.]";

        /// <summary>
        /// 재전송 URL
        /// </summary>
        public static readonly string REDIRECT_URL = "[Redirect URI를 설정한다.]";

        /// <summary>
        /// 메시지 템플리트 ID
        /// </summary>
        public static readonly string MESAGE_TEMPLATE_ID = "[메시지 템플릿 ID를 설정한다.]";

        /// <summary>
        /// 로그인 URL
        /// </summary>
        public static readonly string LOGIN_URL = $"https://kauth.kakao.com/oauth/authorize?response_type=code&client_id={REST_API_KEY}&redirect_uri={REDIRECT_URL}";

        /// <summary>
        /// OAUTH URL
        /// </summary>
        public static readonly string OAUTH_URL = "https://kauth.kakao.com";

        /// <summary>
        /// API URL
        /// </summary>
        public static readonly string API_URL = "https://kapi.kakao.com";

        /// <summary>
        /// 인증 코드
        /// </summary>
        public static string AUTHENTICATION_CODE;

        /// <summary>
        /// 액세스 토큰
        /// </summary>
        public static string ACCESS_TOKEN;

        #endregion
    }
}

 

728x90

 

▶ LoginForm.cs

using System.Windows.Forms;

using Newtonsoft.Json.Linq;

using RestSharp;

namespace TestProject
{
    /// <summary>
    /// 로그인 폼
    /// </summary>
    public partial class LoginForm : Form
    {
        //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor
        ////////////////////////////////////////////////////////////////////////////////////////// Public
        
        #region 생성자 - LoginForm()

        /// <summary>
        /// 생성자
        /// </summary>
        public LoginForm()
        {
            InitializeComponent();

            this.webBrowser.DocumentCompleted += webBrowser_DocumentCompleted;

            this.webBrowser.Navigate(KakaoAPIHelper.LOGIN_URL);
        }

        #endregion

        //////////////////////////////////////////////////////////////////////////////////////////////////// Method
        ////////////////////////////////////////////////////////////////////////////////////////// Private
        //////////////////////////////////////////////////////////////////////////////// Event

        #region 웹 브라우저 문서 완료시 처리하기 - webBrowser_DocumentCompleted(sender, e)

        /// <summary>
        /// 웹 브라우저 문서 완료시 처리하기
        /// </summary>
        /// <param name="sender">이벤트 발생자</param>
        /// <param name="e">이벤트 인자</param>
        private void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            string authenticationCode = GetAuthenticationCode();

            if(authenticationCode != "")
            {
                KakaoAPIHelper.AUTHENTICATION_CODE = authenticationCode;

                KakaoAPIHelper.ACCESS_TOKEN = GetAccessToken();

                DialogResult = DialogResult.OK;

                Close();
            }
        }

        #endregion

        //////////////////////////////////////////////////////////////////////////////// Function

        #region 인증 코드 구하기 - GetAuthenticationCode()

        /// <summary>
        /// 인증 코드 구하기
        /// </summary>
        /// <returns>인증 코드</returns>
        private string GetAuthenticationCode()
        {
            string url = webBrowser.Url.ToString();

            string authenticationCode = url.Substring(url.IndexOf("=") + 1);

            if(url.CompareTo(KakaoAPIHelper.REDIRECT_URL + "?code=" + authenticationCode) == 0)
            {
                return authenticationCode;
            }
            else
            {
                return string.Empty;
            }
        }

        #endregion
        #region 액세스 토큰 구하기 - GetAccessToken()

        /// <summary>
        /// 액세스 토큰 구하기
        /// </summary>
        /// <returns>액세스 토큰</returns>
        private string GetAccessToken()
        {
            RestClient client = new RestClient(KakaoAPIHelper.OAUTH_URL);

            RestRequest request = new RestRequest("/oauth/token", Method.POST);

            request.AddParameter("grant_type"  , "authorization_code"              );
            request.AddParameter("client_id"   , KakaoAPIHelper.REST_API_KEY       );
            request.AddParameter("redirect_uri", KakaoAPIHelper.REDIRECT_URL       );
            request.AddParameter("code"        , KakaoAPIHelper.AUTHENTICATION_CODE);

            IRestResponse response = client.Execute(request);

            JObject responseObject = JObject.Parse(response.Content);

            return responseObject["access_token"].ToString();
        }

        #endregion
    }
}

 

반응형

 

▶ MainForm.cs

using Microsoft.Win32;
using System;
using System.Diagnostics;
using System.Windows.Forms;

using Newtonsoft.Json.Linq;

using RestSharp;

namespace TestProject
{
    /// <summary>
    /// 메인 폼
    /// </summary>
    public partial class MainForm : Form
    {
        //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor
        ////////////////////////////////////////////////////////////////////////////////////////// Public

        #region 생성자 - MainForm()

        /// <summary>
        /// 생성자
        /// </summary>
        public MainForm()
        {
            InitializeComponent();

            Load                   += Form_Load;
            this.loginButton.Click += loginButton_Click;
            this.sendButton.Click  += sendButton_Click;
        }

        #endregion

        //////////////////////////////////////////////////////////////////////////////////////////////////// Method
        ////////////////////////////////////////////////////////////////////////////////////////// Private
        //////////////////////////////////////////////////////////////////////////////// Event

        #region 폼 로드시 처리하기 - Form_Load(sender, e)

        /// <summary>
        /// 폼 로드시 처리하기
        /// </summary>
        /// <param name="sender">이벤트 발생자</param>
        /// <param name="e">이벤트 인자</param>
        private void Form_Load(object sender, EventArgs e)
        {
            string applicationFileName = Process.GetCurrentProcess().ProcessName + ".exe";

            SetRegistryKeyForWebBrowserControl(applicationFileName);
        }

        #endregion
        #region 로그인 버튼 클릭시 처리하기 - loginButton_Click(sender, e)

        /// <summary>
        /// 로그인 버튼 클릭시 처리하기
        /// </summary>
        /// <param name="sender">이벤트 발생자</param>
        /// <param name="e">이벤트 인자</param>
        private void loginButton_Click(object sender, EventArgs e)
        {
            if(this.loginButton.Text == "로그인")
            {
                LoginForm form = new LoginForm();

                if(form.ShowDialog() == DialogResult.OK)
                {
                    this.loginButton.Text = "로그아웃";
                }
            }
            else
            {
                RestClient client = new RestClient(KakaoAPIHelper.API_URL);

                RestRequest request = new RestRequest("/v1/user/unlink", Method.POST);

                request.AddHeader("Authorization", $"bearer {KakaoAPIHelper.ACCESS_TOKEN}");

                if(client.Execute(request).IsSuccessful)
                {
                    this.loginButton.Text = "로그인";
                }
            }
        }

        #endregion
        #region 보내기 버튼 클릭시 처리하기 - sendButton_Click(sender, e)

        /// <summary>
        /// 보내기 버튼 클릭시 처리하기
        /// </summary>
        /// <param name="sender">이벤트 발생자</param>
        /// <param name="e">이벤트 인자</param>
        private void sendButton_Click(object sender, EventArgs e)
        {
            if(this.customMessageRadioButton.Checked)
            {
                SendCustomMessageToMySelf(this.messageTextBox.Text);

                this.messageTextBox.Text = string.Empty;
            }
            else
            {
                SendTemplateMessageToMySelf();
            }
        }

        #endregion

        //////////////////////////////////////////////////////////////////////////////// Function

        #region 웹 브라우저 컨트롤용 레지스트 키 설정하기 - SetRegistryKeyForWebBrowserControl(applicationFileName)

        /// <summary>
        /// 웹 브라우저 컨트롤용 레지스트 키 설정하기
        /// </summary>
        /// <param name="applicationFileName">애플리케이션 파일명</param>
        /// <remarks>WebBrowser 컨트롤을 Internet Explorer 11 버전으로 동작하도록 해준다.</remarks>
        private void SetRegistryKeyForWebBrowserControl(string applicationFileName)
        {
            RegistryKey registryKey = null;

            try
            {
                registryKey = Registry.LocalMachine.OpenSubKey
                (
                    @"SOFTWARE\\Microsoft\\Internet Explorer\\Main\\FeatureControl\\FEATURE_BROWSER_EMULATION",
                    true
                );

                if(registryKey == null)
                {
                    MessageBox.Show(this, "해당 레지스트리 키를 찾을 수 없습니다.");

                    return;
                }

                string registryKeyValue = Convert.ToString(registryKey.GetValue(applicationFileName));

                if(registryKeyValue == "11001")
                {
                    registryKey.Close();

                    return;
                }

                if(string.IsNullOrEmpty(registryKeyValue))
                {
                    registryKey.SetValue(applicationFileName, unchecked((int)0x2AF9), RegistryValueKind.DWord);
                }

                registryKeyValue = Convert.ToString(registryKey.GetValue(applicationFileName));

                if(registryKeyValue == "11001")
                {
                    MessageBox.Show(this, "IE11 레지스트리 설정이 완료되었습니다.");
                }
                else
                {
                    MessageBox.Show(this, $"IE11 레지스트리 설정을 실패했습니다.\n키 값 : {registryKeyValue}");
                }
            }
            catch(Exception exception)
            {
                MessageBox.Show(this, $"IE11 레지스트리 설정시 에러가 발생했습니다.\n{exception}");
            }
            finally
            {
                if(registryKey != null)
                {
                    registryKey.Close();
                }
            }
        }

        #endregion
        #region 나에게 커스텀 메시지 보내기 - SendCustomMessageToMySelf(message)

        /// <summary>
        /// 나에게 커스텀 메시지 보내기
        /// </summary>
        /// <param name="message">메시지</param>
        private void SendCustomMessageToMySelf(string message)
        {
            JObject linkObject = new JObject();

            linkObject.Add("web_url"       , "https://icodebroker.tistory.com");
            linkObject.Add("mobile_web_url", "https://icodebroker.tistory.com");

            JObject templateObject = new JObject();

            templateObject.Add("object_type" , "text"       );
            templateObject.Add("text"        , message      );
            templateObject.Add("link"        , linkObject   );
            templateObject.Add("button_title", "링크로 이동");

            RestClient client = new RestClient(KakaoAPIHelper.API_URL);

            RestRequest request = new RestRequest("/v2/api/talk/memo/default/send", Method.POST);

            request.AddHeader("Authorization", $"bearer {KakaoAPIHelper.ACCESS_TOKEN}");

            request.AddParameter("template_object", templateObject);

            if(client.Execute(request).IsSuccessful)
            {
                MessageBox.Show(this, "커스텀 메시지 전송을 성공했습니다.");
            }
            else
            {
                MessageBox.Show(this, "커스텀 메시지 전송을 실패했습니다.");
            }
        }

        #endregion
        #region 나에게 템플리트 메시지 보내기 - SendTemplateMessageToMySelf()

        /// <summary>
        /// 나에게 템플리트 메시지 보내기
        /// </summary>
        private void SendTemplateMessageToMySelf()
        {
            RestClient client = new RestClient(KakaoAPIHelper.API_URL);

            RestRequest request = new RestRequest("/v2/api/talk/memo/send", Method.POST);

            request.AddHeader("Authorization", $"bearer {KakaoAPIHelper.ACCESS_TOKEN}");

            request.AddParameter("template_id", KakaoAPIHelper.MESAGE_TEMPLATE_ID);

            if(client.Execute(request).IsSuccessful)
            {
                MessageBox.Show(this, "템플리트 메시지 전송을 성공했습니다.");
            }
            else
            {
                MessageBox.Show(this, "템플리트 메시지 전송을 실패했습니다.");
            }
        }

        #endregion
    }
}

 

※ 관리자 권한으로 실행해야 한다.

728x90
반응형
그리드형(광고전용)
Posted by icodebroker

댓글을 달아 주세요