1+ <?php
2+ /**
3+ * Make a a curl call to an endpoint with params
4+ *
5+ * @param string $endpoint we are hitting
6+ * @param string $type of request
7+ * @param array $params to send along with the request
8+ *
9+ * @return array with the api response
10+ */
11+ function makeApiCall ( $ endpoint , $ type , $ params ) {
12+ // initialize curl
13+ $ ch = curl_init ();
14+
15+ // create endpoint with params
16+ $ apiEndpoint = $ endpoint . '? ' . http_build_query ( $ params );
17+
18+ // set other curl options
19+ curl_setopt ( $ ch , CURLOPT_URL , $ apiEndpoint );
20+ curl_setopt ( $ ch , CURLOPT_RETURNTRANSFER , true );
21+
22+ // get response
23+ $ response = curl_exec ( $ ch );
24+
25+ // close curl
26+ curl_close ( $ ch );
27+
28+ return array ( // return data
29+ 'type ' => $ type ,
30+ 'endpoint ' => $ endpoint ,
31+ 'params ' => $ params ,
32+ 'api_endpoint ' => $ apiEndpoint ,
33+ 'data ' => json_decode ( $ response , true )
34+ );
35+ }
36+
37+ /**
38+ * Get facebook api login url that will take the user to facebook and present them with login dialog.
39+ *
40+ * Endpoint: https://www.facebook.com/{fb-graph-api-version}/dialog/oauth?client_id={app-id}&redirect_uri={redirect-uri}&state={state}&scope={scope}&auth_type={auth-type}
41+ *
42+ * @param string $scope comma separated list of permissions being requested from the user..
43+ * @param string $state random generated to verify request is from facebook.
44+ * @return string
45+ */
46+ function getFacebookLoginUrl ( $ permissions , $ state ) {
47+ // endpoint for facebook login dialog
48+ $ endpoint = 'https://www.facebook.com/ ' . FB_GRAPH_VERSION . '/dialog/oauth ' ;
49+
50+ $ params = array ( // login url params required to direct user to facebook and promt them with a login dialog
51+ 'client_id ' => FB_APP_ID ,
52+ 'redirect_uri ' => FB_REDIRECT_URI ,
53+ 'state ' => $ state ,
54+ 'scope ' => $ permissions ,
55+ 'auth_type ' => 'rerequest '
56+ );
57+
58+ // return login url
59+ return $ endpoint . '? ' . http_build_query ( $ params );
60+ }
61+
62+ /**
63+ * Get an access token with the code from facebook.
64+ *
65+ * Endpoint https://graph.facebook.com/{fb-graph-version}/oauth/access_token?client_id{app-id}&client_secret={app-secret}&redirect_uri={redirect_uri}&code={code}
66+ *
67+ * @param string $code code returned from facebook, exchange for access token
68+ * @return array $response
69+ */
70+ function getAccessTokenWithCode ( $ code ) {
71+ // endpoint for getting an access token with code
72+ $ endpoint = FB_GRAPH_DOMAIN . FB_GRAPH_VERSION . '/oauth/access_token ' ;
73+
74+ $ params = array ( // params for the endpoint
75+ 'client_id ' => FB_APP_ID ,
76+ 'client_secret ' => FB_APP_SECRET ,
77+ 'redirect_uri ' => FB_REDIRECT_URI ,
78+ 'code ' => $ code
79+ );
80+
81+ // make the api call
82+ return makeApiCall ( $ endpoint , 'GET ' , $ params );
83+ }
0 commit comments