<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
	<title type="html"><![CDATA[Серый форум &mdash; AHK: Google OAuth 2.0 и YouTube API]]></title>
	<link rel="self" href="http://forum.script-coding.com/extern.php?action=feed&amp;tid=17647&amp;type=atom" />
	<updated>2023-03-12T01:24:41Z</updated>
	<generator>PunBB</generator>
	<id>http://forum.script-coding.com/viewtopic.php?id=17647</id>
		<entry>
			<title type="html"><![CDATA[AHK: Google OAuth 2.0 и YouTube API]]></title>
			<link rel="alternate" href="http://forum.script-coding.com/viewtopic.php?pid=157084#p157084" />
			<content type="html"><![CDATA[<p>Так как Гугл прекратил поддержку авторизации с броузеров без включенного джаваскрипт,<br /><a href="https://security.googleblog.com/2018/10/announcing-some-security-treats-to.html">https://security.googleblog.com/2018/10 … ts-to.html</a><br />то автоматизировать, например, ютуб стало возможным только через апи.<br />Алгоритм:<br />Прежде всего нам надо зарегестрировать свое устройство.<br />Заходим в <a href="https://console.developers.google.com">https://console.developers.google.com</a><br />Создаем новый проект.<br />Выбираем созданный проект.<br />Переходим на вкладку OAuth consent screen, выбираем external, вписываем название апликации, имейлы -&gt; save and continue.<br />После чего в test users-&gt;add users-&gt; указываем свой имейл.<br />Переходим на вкладку Library.<br />Находим YouTube Data API v3, нажимаем на него, потом нажимаем на Enable.<br />Переходим на вкладку Credentials, нажимаем Create credentials-&gt;Api key.<br />Этот апи ключ нам надо сохранить и посылать каждый раз при использовании ютуб апи.<br />После чего нажимаем Create credentials-&gt;OAuth client ID.<br />Там выбираем Application type-&gt;Desktop Application.<br />Появляется окошко&nbsp; OAuth client created, в нем скачиваем json.<br />Скачиваем JSon.<br />Должен скачаться такой:<br /></p><div class="quotebox"><blockquote><p>{&quot;installed&quot;:{&quot;client_id&quot;:&quot;341870872-dgbbg66.apps.googleusercontent.com&quot;,&quot;project_id&quot;:&quot;certain-hau-29&quot;,&quot;auth_uri&quot;:&quot;https://accounts.google.com/o/oauth2/auth&quot;,&quot;token_uri&quot;:&quot;https://oauth2.googleapis.com/token&quot;,&quot;auth_provider_x509_cert_url&quot;:&quot;https://www.googleapis.com/oauth2/v1/certs&quot;,&quot;client_secret&quot;:&quot;JJN1OS7110v-j&quot;,&quot;redirect_uris&quot;:[&quot;http://localhost&quot;]}}</p></blockquote></div><p>В нем нам нужны client_id и client_secret.<br />Теперь нам надо разрешить доступ нашего устройства.<br />Создаем такой код со своими данными:<br /></p><div class="codebox"><pre><code>; изменяем данные
ClientId := &quot;341870872-dgbbg66.apps.googleusercontent.com&quot;
ClientSecret := &quot;JJN1OS7110v-j&quot;

; дальше не изменяем
RedirectUri := &quot;http://localhost&quot;
scope := &quot;https://www.googleapis.com/auth/youtube&quot;
msgbox % clipboard := &quot;https://accounts.google.com/o/oauth2/auth?redirect_uri=&quot; UriEncode(RedirectUri) &quot;&amp;response_type=code&amp;client_id=&quot; ClientId &quot;&amp;scope=&quot; UriEncode(scope) &quot;&amp;clientSecret=&quot; ClientSecret &quot;&amp;access_type=offline&amp;approval_prompt=force&quot;

UriEncode(Uri)
{
   VarSetCapacity(Var, StrPut(Uri, &quot;UTF-8&quot;), 0)
   StrPut(Uri, &amp;Var, &quot;UTF-8&quot;)
   f := A_FormatInteger
   SetFormat, IntegerFast, H
   While Code := NumGet(Var, A_Index - 1, &quot;UChar&quot;)
      If (Code &gt;= 0x30 &amp;&amp; Code &lt;= 0x39 ; 0-9
         || Code &gt;= 0x41 &amp;&amp; Code &lt;= 0x5A ; A-Z
         || Code &gt;= 0x61 &amp;&amp; Code &lt;= 0x7A) ; a-z
         Res .= Chr(Code)
      Else
         Res .= &quot;%&quot; . SubStr(Code + 0x100, -1)
   SetFormat, IntegerFast, %f%
   Return, Res
}</code></pre></div><p>Если нам надо получить доступ к нескольким scope, то их надо перечислять через пробел и без слеша в конце:<br /></p><div class="codebox"><pre><code>scope := &quot;https://mail.google.com https://www.googleapis.com/auth/calendar&quot;</code></pre></div><p>Запускаем код, полученную ссылку вставляем в браузер, переходим по ней.<br />Разрешаем использовать наше устройство и в итоге будет перенаправление на 404 страницу.<br />Копируем из адресной строки часть http://localhost/?code=<strong>4/7wCaeBV61IBslGg5pU9AZZ-XvrtJp7Dmnfh_khOlv6Co-sUuL0OMd7jt5s</strong>&amp;scope.<br />Это код авторизации.<br />После чего создаем и запускаем следующий скрипт:<br /></p><div class="codebox"><pre><code>; изменяем данные
ClientId := &quot;341870872-dgbbg66.apps.googleusercontent.com&quot;
ClientSecret := &quot;JJN1OS7110v-j&quot;
AuthorizationCode := &quot;4/7wCaeBV61IBslGg5pU9AZZ-XvrtJp7Dmnfh_khOlv6Co-sUuL0OMd7jt5s&quot;

; дальше не изменяем
RedirectUri := &quot;http://localhost&quot;
Request := &quot;grant_type=authorization_code&amp;code=&quot; AuthorizationCode &quot;&amp;redirect_uri=&quot; UriEncode(RedirectUri) &quot;&amp;client_id=&quot; ClientId &quot;&amp;client_secret=&quot; ClientSecret
WinHTTP := ComObjCreate(&quot;WinHTTP.WinHTTPRequest.5.1&quot;)
WinHTTP.Open(&quot;POST&quot;, &quot;https://accounts.google.com/o/oauth2/token&quot;, true)
WinHTTP.SetRequestHeader(&quot;Content-Type&quot;, &quot;application/x-www-form-urlencoded&quot;)
WinHTTP.Send(Request)
WinHTTP.WaitForResponse()
msgbox % clipboard := WinHTTP.ResponseText

UriEncode(Uri)
{
   VarSetCapacity(Var, StrPut(Uri, &quot;UTF-8&quot;), 0)
   StrPut(Uri, &amp;Var, &quot;UTF-8&quot;)
   f := A_FormatInteger
   SetFormat, IntegerFast, H
   While Code := NumGet(Var, A_Index - 1, &quot;UChar&quot;)
      If (Code &gt;= 0x30 &amp;&amp; Code &lt;= 0x39 ; 0-9
         || Code &gt;= 0x41 &amp;&amp; Code &lt;= 0x5A ; A-Z
         || Code &gt;= 0x61 &amp;&amp; Code &lt;= 0x7A) ; a-z
         Res .= Chr(Code)
      Else
         Res .= &quot;%&quot; . SubStr(Code + 0x100, -1)
   SetFormat, IntegerFast, %f%
   Return, Res
}</code></pre></div><p>Ответ должен прийти c access_token и refresh_token:<br /></p><div class="codebox"><pre><code>{
  &quot;access_token&quot;: &quot;ya29.GluuBhDBPs66aSxf3TR0k7VetBWezYD_GXBcyKIBMIIOjWkkfsPcNDDh4pVCXy5U4C-g3Y1GxxF_26&quot;,
  &quot;expires_in&quot;: 3600,
  &quot;refresh_token&quot;: &quot;1/SjYrJK9Ja2N57TxxIdoxvMTrrj2vDReeFK7yMOTLgA6fLsJp&quot;,
  &quot;scope&quot;: &quot;https://www.googleapis.com/auth/youtube&quot;,
  &quot;token_type&quot;: &quot;Bearer&quot;
}</code></pre></div><p>После чего можно подключиться к управлению апи ютуба.<br />Следующий код добавляет видео в плейлист:<br /></p><div class="codebox"><pre><code>; изменяем данные
videoId := &quot;A_QfO7g1YsI&quot;
playlistId := &quot;PLp9-Tn608wZdTS44vpp9hYhke&quot;
YoutubeApiKey := &quot;AIzaS9999999999999nm4rYaTA3EC397_ik&quot;
access_token := &quot;ya29.GluuBhDBPs66aSxf3TR0k7VetBWezYD_GXBcyKIBMIIOjWkkfsPcNDDh4pVCXy5U4C-g3Y1GxxF_26&quot;
refresh_token := &quot;1/SjYrJK9Ja2N57TxxIdoxvMTrrj2vDReeFK7yMOTLgA6fLsJp&quot;

; дальше не изменяем
url := &quot;https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&amp;key=&quot; YoutubeApiKey
Json = {&#039;snippet&#039;: {&#039;playlistId&#039;: &#039;%playlistId%&#039;, &#039;resourceId&#039;: {&#039;kind&#039;: &#039;youtube#video&#039;, &#039;videoId&#039;: &#039;%videoId%&#039;}}}

WinHTTP := ComObjCreate(&quot;WinHTTP.WinHTTPRequest.5.1&quot;)
WinHTTP.Open(&quot;POST&quot;, url, true)
WinHTTP.SetRequestHeader(&quot;Authorization&quot;, &quot;Bearer &quot; access_token)
WinHTTP.SetRequestHeader(&quot;User-Agent&quot;, &quot;Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko&quot;)
WinHTTP.SetRequestHeader(&quot;Content-Type&quot;, &quot;application/json&quot;)
WinHTTP.Send(Json)
WinHTTP.WaitForResponse()
msgbox % WinHTTP.ResponseText</code></pre></div><p>Обновлять токен так:<br /></p><div class="codebox"><pre><code>; изменяем данные
ClientId := &quot;341870872-dgbbg66.apps.googleusercontent.com&quot;
ClientSecret := &quot;JJN1OS7110v-j&quot;
RefreshToken := &quot;1/SjYrJK9Ja2N57TxxIdoxvMTrrj2vDReeFK7yMOTLgA6fLsJp&quot;

; дальше не изменяем
Request := &quot;refresh_token=&quot; RefreshToken &quot;&amp;client_id=&quot; ClientId &quot;&amp;client_secret=&quot; ClientSecret &quot;&amp;grant_type=refresh_token&quot;
WinHTTP := ComObjCreate(&quot;WinHTTP.WinHTTPRequest.5.1&quot;)
WinHTTP.Open(&quot;POST&quot;, &quot;https://accounts.google.com/o/oauth2/token&quot;, true)
WinHTTP.SetRequestHeader(&quot;Content-Type&quot;, &quot;application/x-www-form-urlencoded&quot;)
WinHTTP.Send(Request)
WinHTTP.WaitForResponse()
msgbox % clipboard := WinHTTP.ResponseText</code></pre></div><p><a href="http://forum.script-coding.com/viewtopic.php?id=14569">Тема для обсуждения</a></p>]]></content>
			<author>
				<name><![CDATA[Malcev]]></name>
				<uri>http://forum.script-coding.com/profile.php?id=26930</uri>
			</author>
			<updated>2023-03-12T01:24:41Z</updated>
			<id>http://forum.script-coding.com/viewtopic.php?pid=157084#p157084</id>
		</entry>
</feed>
