■ 카카오 링크를 사용해 나에게 카카오톡 메시지를 보내는 방법을 보여준다.
▶ KakaoAPIHelper.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
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 } } |
▶ LoginForm.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 |
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 } } |
※ 관리자 권한으로 실행해야 한다.