728x90
반응형
728x170
▶ 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
반응형
그리드형(광고전용)
'C# > WinForm' 카테고리의 다른 글
[C#/WINFORM] 누겟 설치 : CefSharp.WinForms (0) | 2021.11.23 |
---|---|
[C#/WINFORM] 누겟 설치 : CefSharp.Common (0) | 2021.11.23 |
[C#/WINFORM] WebBrowser 클래스 : Internet Explorer의 브라우저 에뮬레이션 모드 구하기 (0) | 2021.11.23 |
[C#/WINFORM] WebBrowser 클래스 : Internet Explorer 버전 11 사용하기 (0) | 2021.11.23 |
[C#/WINFORM] 카카오 링크를 사용해 나에게 카카오톡 메시지 보내기 (기능 개선) (0) | 2021.11.23 |
[C#/WINFORM] PrintWindow API 함수를 사용해 윈도우 비트맵 구하기 (0) | 2021.11.14 |
[C#/WINFORM] 3D 차트 사용하기 (0) | 2021.10.22 |
[C#/WINFORM] 가상 데스크톱 전환하기 (0) | 2021.09.10 |
[C#/WINFORM] Screen 클래스 : FromHandle 정적 메소드를 사용해 특정 윈도우가 속한 화면 구하기 (0) | 2021.09.04 |
[C#/WINFORM] Form 클래스 : MouseDown/MouseMove/MouseUp 이벤트를 사용해 테두리 없는 폼 만들기 (0) | 2021.08.30 |
댓글을 달아 주세요