Facebook API |
It provides a standard method to perform common Facebook operations. Most functions have a limit in the number of times that can be called or in the number of bytes returned in a given time period. Esta proporciona una método estándar para ejecutar operaciones comunes en Facebook. La mayoría de las funciones tienen un límite en el número de veces que pueden llamarse o en el número de bytes que regresan en un periodo de tiempo dado. |
Problem 1 |
For this problem you will need a Facebook account, if you do not have one, create one first at www.facebook.com. Then, go to https://developers.facebook.com/ to create a Facebok developer account. At this point, you can create your first App. Assign a name to your App, you will get be able to obtain an App ID (store this number as it will be used later). Para este problema usted necesitará una cuenta de Facebook, si usted no tiene una, cree una primero en www.facebook.com. Entonces, navegue a https://developers.facebook.com/ para crear una cuenta de desarrollador de Facebook. Entonces, usted puede crear su primer App. Asigne un nombre a su App, usted podrá obtener una App ID (almacene este número ya que se usará después). |
Problem 2 |
Set up the Application settings in App Dashboard. Open: https://developers.facebook.com/ and select the Application you would like to configure. Fijar la configuración de la Application en AppDashboard. Abra: https://developers.facebook.com/ y selecciones la Aplicación que usted quiere configurar. |
Step A |
Click on Settings > Advanced and add the localhost IP address in the Domain Manager as shown. The next problems will assume that the Facebook login redirection is at port 80. If you are running Microsoft IIS (or Apache HTTP server) in your computer, you need to stop these Web Servers for these examples to run. Haga clic en Settings > Advanced y agregue la dirección IP del host local en el Domain Manager como se muestra. Los próximos problemas asumirán que la redirección de Login de Facebook es en el puerto 80. Si usted está ejecutando Microsoft IIS (o Apache HTTP server) en su computadora, usted necesita detener estos Servidores Web para correr estos ejemplos. |
Graph API Explorer |
Facebook Graph API Explorer is a tool specially designed for developer to test Facebook API. Facebook Graph API Explorer is available at https://developers.facebook.com/tools/explorer/. El Explorador de la API Graph para Facebook es una herramienta especialmente diseñada para los programadores para probar la API de Facebook. El Explorador de la API Graph para Facebook está disponible en https://developers.facebook.com/tools/explorer/. |
Facebook Login Flow |
The figure below shows how to get an access_token using the Facebook login dialog, you can review: https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow. La figura debajo muestra cómo obtener un access_token usando el diálogo de Facebook para login, usted puede revisar: https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow. |
Problem 3 |
Create a Wintempla Dialog application called FaceLink to obtain to Facebook access_token. We will use WinHTTP to connect to Facebook, you can also use WinINet or sockets. Cree una aplicación de Diálogo de Wintempla llamada FaceLink para conseguir un Facebook access_token. Nosotros usaremos WinHTTP para conectarnos a Facebook, usted también puede usar WinINet o sockets. |
Step A |
Open: https://developers.facebook.com/. Then copy: the App ID and the App Secret as shown. Fijar la configuración de la Application en AppDashboard. Abra: https://developers.facebook.com/. Entonces copie: el App ID y la App Secret como se muestra. |
Step B |
Edit the stdafx.h file to enable: Sockets, Cryptography (using Windows Cryptography) and WinHTTP. Edite el archivo stdafx.h para habilitar: Sockets, Cryptography (usando Windows Cryptography) y WinHTTP. |
stdafx.h |
... //_________________________________________ Sockets & Cryptography #define WIN_SOCKETS_SUPPORT //_________________________________________ DirectX //#define WIN_DIRECTX //_________________________________________ Cryptography #define WIN_CRYPTOGRAPHY //_________________________________________ WinHTTP #define WIN_WINHTTP ... |
Step C |
Choose a location of your hard drive for wwwroot for the local Web server. Place an index.htm file in this location. This file will be shown to the user after the Facebook HTTP redirect. The index.htm file may contain a simple text indicating the user to CLOSE that window. If the user does not close the window, some Internet Browsers will keep a connection open with the Web Server and the Web Server will not be able to stop. Escoja una ubicación en su disco duro para el wwwroot para el servidor Web local. Coloque un archivo index.htm en esta ubicación. Este archivo será mostrado al usuario después del HTTP redirect de Facebook. El archivo index.htm puede contener un texto simple indicándole al usuario que CIERRE esa ventana. Si el usuario no cierra la ventana, algunas Exploradores de la Internet mantendrán una conexión abierta con el Servidor Web y el Servidor Web no podrá detenerse. |
Step D |
Edit the FaceLink.h file as shown. Edite el archivo FaceLink.h como se muestra. |
FaceLink.h |
#pragma once //______________________________________ FaceLink.h #include "Resource.h" #define FACEBOOK_LOGIN_OK 0 #define FACEBOOK_LOGIN_ERROR 1 #define FACEBOOK_LOGIN_PENDING 2 #define FACEBOOK_REDIRECT_URI L"http://127.0.0.1/" class FaceLink: public Win::Dialog { public: FaceLink() { comfirmingIdentity = false; } ~FaceLink() { } bool comfirmingIdentity; wstring facebook_code; Web::Server web_server; // It returns: FACEBOOK_LOGIN_OK, FACEBOOK_LOGIN_ERROR, FACEBOOK_LOGIN_PENDING int GetLoginResult(Web::HttpRequest& httpRequest, wstring& out_resultText); bool ConfirmeIdentity(); protected: ... }; |
Step E |
Edit the FaceLink.cpp file as shown. Edite el archivo FaceLink.cpp como se muestra. |
FaceLink.cpp |
... void FaceLink::Window_Open(Win::Event& e) { } void FaceLink::btLogin_Click(Win::Event& e) { if (tbxAppID.GetTextLength() <= 0) { tbxAppID.ShowBalloonTip(L"Facebook", L"You need to register an APP to get an APP ID", TTI_ERROR); return; } facebook_code.clear(); comfirmingIdentity = false; //_____________________________________________________________________ 1. Run the Web Server to capture Facebook redirection tbxOutput.Text = L"Starting local Web server ...\r\n"; const wchar_t* error = web_server.Start(L"C:\\selo", 80, 80, hWnd, WM_USER, true); if (error == NULL) { tbxOutput.Text += L"Web server is running ...\r\n"; tbxOutput.Text += L"Waiting for Facebook ...\r\n"; //____________________________________________________________________ 2. Create URL wstring url = L"https://www.facebook.com/v2.12/dialog/oauth?client_id="; url += tbxAppID.Text; url += L"&redirect_uri="; wstring text; Sys::Convert::UrlEncode(FACEBOOK_REDIRECT_URI, true, text); url += text; url += L"&state=df3FDDFe43reXZZEqes"; url += L"&response_type=code"; // token, code or code%20token //___________________________________________________________________ 3. Open URL if (Sys::Process::OpenFile(url) == false) { this->MessageBox(L"Unable to open URL", L"FaceLink", MB_OK | MB_ICONERROR); web_server.Stop(); } } else { this->MessageBox(error, L"FaceLink", MB_OK | MB_ICONERROR); } } void FaceLink::Window_User(Win::Event& e) { switch (LOWORD(e.lParam)) { case WEB_SERVER_MAIN_THREAD: if (HIWORD(e.lParam) == WIN_THREAD_STOPPED) { web_server.WaitForExit(); tbxOutput.Text += L"Web server has stopped ...\r\n"; } break; case WEB_SERVER_WORKER_THREAD: if (HIWORD(e.lParam) == WEB_SERVER_REQUEST) { tbxOutput.Text += L"Receiving request from Facebook ...\r\n"; } else if (HIWORD(e.lParam) == WIN_THREAD_STOPPED) { vector<Web::HttpRequest> httpRequest; web_server.httpRequestCollection.PopAllItems(httpRequest); const size_t count = httpRequest.size(); int result = FACEBOOK_LOGIN_ERROR; wstring loginText; for (size_t i = 0; i < count; i++) { result = GetLoginResult(httpRequest[i], loginText); if (result == FACEBOOK_LOGIN_OK) { facebook_code = loginText; web_server.Stop(); tbxOutput.Text += L"Facebook 'code' received\r\n"; break; } else if (result == FACEBOOK_LOGIN_ERROR) { facebook_code.clear(); web_server.Stop(); tbxOutput.Text += L"Facebook Access denied\r\n"; break; } } if (facebook_code.empty() == false) { if (comfirmingIdentity == false) ConfirmeIdentity(); } } break; } } int FaceLink::GetLoginResult(Web::HttpRequest& httpRequest, wstring& out_resultText) { if (httpRequest.query_wstring.empty()) return FACEBOOK_LOGIN_PENDING; //_______________________________________________________________ 1. Read all variables in the HTTP request multimap<wstring, wstring> value; Web::HttpConnector::ReadVariables(httpRequest.query_string.c_str(), (DWORD)httpRequest.query_string.size(), value); multimap<wstring, wstring>::iterator p; //_______________________________________________________________ 2. Try to find Facebook 'code' p = value.find(L"code"); if (p != value.end()) { out_resultText = p->second; return FACEBOOK_LOGIN_OK; } //_______________________________________________________________ 3. Did the user cancel? p = value.find(L"error"); if (p != value.end()) { out_resultText = p->second; return FACEBOOK_LOGIN_ERROR; } return FACEBOOK_LOGIN_PENDING; } bool FaceLink::ConfirmeIdentity() { if (facebook_code.empty()) return false; comfirmingIdentity = true; tbxOutput.Text += L"Confirming identity ...\r\n"; Web::HttpTransaction transaction; Web::HttpAssistant assistant; assistant.synchronous = true; assistant.user_agent = L"FaceLink 1.0"; transaction.request.Method = L"GET"; transaction.request.serverName = L"graph.facebook.com"; transaction.request.useHTTPS = true; transaction.request.resource = L"/v2.12/oauth/access_token"; transaction.request.AddQueryStringVariable(L"client_id", tbxAppID.Text.c_str()); transaction.request.AddQueryStringVariable(L"redirect_uri", FACEBOOK_REDIRECT_URI); //______________________________________________________________________ client_secret // Your unique APP SECRET, shown on the App Dashboard. This app secret should never be // included in client-side code or in binaries that could be decompiled. It is extremely // important that it remains completely secret as it is the core of the security of your // app and all the people using it. transaction.request.AddQueryStringVariable(L"client_secret", tbxAppSecret.Text.c_str()); transaction.request.AddQueryStringVariable(L"code", facebook_code.c_str()); Sys::Error error = assistant.SendRequest(transaction); if (error == true) { wstring tmp; error.GetInformation(tmp); tbxOutput.Text += tmp; tbxOutput.Text += L"\r\n"; return false; } wstring text; transaction.response.data.GetText(text, true); Sys::Json json; const wchar_t* error_desc = json.CreateFromString(text.c_str()); if (error_desc != NULL) { tbxOutput.Text += error_desc; tbxOutput.Text += L"\r\n"; return false; } if (json.IsObject() == false) { tbxOutput.Text += L"The Json content must have a set of objects\r\n"; return false; } unordered_map<wstring, Sys::Json>::iterator p; p = json.ObjectValue.find(L"access_token"); if ( p == json.ObjectValue.end()) { tbxOutput.Text += L"The access_token was not found\r\n"; } else { if (p->second.IsString() == false) { tbxOutput.Text += L"The access_token must be a string\r\n"; return false; } tbxOutput.Text += L"Access Token: \r\n"; tbxOutput.Text += p->second.StringValue; tbxOutput.Text += L"\r\n"; return true; } return false; } |
Problem 4 |
Create a Wintempla Dialog application called FaceWin to list the post of one Facebook page. We will use WinHTTP to connect to Facebook, you can also use WinINet or sockets. You will need the access_token returned by Facebook; run the previous program and use Ctrl+C to copy (from the textbox) the access_token to the clipboard. Then, you can paste the access_token for this problem. Cree una aplicación de Diálogo de Wintempla llamada FaceWin para listar las publicaciones en una página de Facebook. Nosotros usaremos WinHTTP para conectarnos a Facebook, usted también puede usar WinINet o sockets. Usted necesitará el access_token regresado por Facebook; ejecute el programa previo y use Ctrl+C para copiar (de la caja de texto) el access_token al portapapeles. Entonces, usted puede pegar el access_token a este problema. |
Step A |
Edit the stdafx.h file to enable: Sockets, Cryptography (using Windows Cryptography) and WinHTTP. Edite el archivo stdafx.h para habilitar: Sockets, Cryptography (usando Windows Cryptography) y WinHTTP. |
stdafx.h |
... //_________________________________________ Sockets & Cryptography #define WIN_SOCKETS_SUPPORT //_________________________________________ DirectX //#define WIN_DIRECTX //_________________________________________ Cryptography #define WIN_CRYPTOGRAPHY //_________________________________________ WinHTTP #define WIN_WINHTTP ... |
Step B |
Edit the FaceWin.cpp file as shown. Edite el archivo FaceWin.cpp como se muestra. |
FaceWin.cpp |
... void FaceWin::Window_Open(Win::Event& e) { Web::HttpTransaction transaction; Web::HttpAssistant assistant; assistant.synchronous = true; assistant.user_agent = L"FaceWin 1.0"; transaction.request.Method = L"GET"; transaction.request.serverName = L"graph.facebook.com"; transaction.request.useHTTPS = true; //___________________________________________________________________________ Facebook Search transaction.request.resource = L"/v2.12/search"; transaction.request.AddQueryStringVariable(L"q", L"NASA"); transaction.request.AddQueryStringVariable(L"type", L"page"); transaction.request.AddQueryStringVariable(L"access_token", L"PASTE HERE THE ACCESS TOKEN"); Sys::Error error = assistant.SendRequest(transaction); if (error == true) { error.Display(hWnd, L"FaceLink"); return; } wstring text; transaction.response.data.GetText(text, true); tbxOutput.Text = text; } |
Problem 5 |
Modify the code of the previous problem to display the posts in a Facebook page. Modifique el código del problema previo para mostrar las publicaciones en una página de Facebook. |
FaceWin.cpp |
... void FaceWin::Window_Open(Win::Event& e) { Web::HttpTransaction transaction; Web::HttpAssistant assistant; assistant.synchronous = true; assistant.user_agent = L"FaceWin 1.0"; transaction.request.Method = L"GET"; transaction.request.serverName = L"graph.facebook.com"; transaction.request.useHTTPS = true; //___________________________________________________________________________ Facebook page posts transaction.request.resource = L"/v2.12/NASA"; transaction.request.AddQueryStringVariable(L"fields", L"posts"); transaction.request.AddQueryStringVariable(L"access_token", L"PASTE HERE THE ACCESS TOKEN"); Sys::Error error = assistant.SendRequest(transaction); if (error == true) { error.Display(hWnd, L"FaceLink"); return; } wstring text; transaction.response.data.GetText(text, true); tbxOutput.Text = text; } |