The system integrates the functions of authorizing posts and getting comments from posts on Facebook.

Keywords: PHP SDK Google SSL

The company's business and foreign trade are closely linked, and the project needs to dock Facebook, Google and Twitter API s. Here's a detailed description of the problems we encounter in docking Facebook.

1. Registering a Facebook account is still troublesome. There are IP restrictions. An IP can't register multiple accounts and can easily be blocked. After registration, there will be an identity review process, which tries to use the real identity, after the audit is successful, you can apply to become a Facebook developer.

2. After becoming a Facebook developer, create applications, obtain application numbers and application keys, and improve official information such as email.

3. Complete company validation and sign contract terms

4. Create test accounts. The project needs to create several more test accounts and make friends with each other.

The test account can be used in local development without any restriction of authority. All functional modules can be implemented through the test account. After the function development is completed, the test environment deployed to an online site is checked by Facebook. The online domain name must be encrypted with SSL.

5. Adding Fackbook login, Facebook login API provides SDK and graphics for login. In actual development, the two methods need to be combined. We use downloaded version of PHP SDK, and use Composer to get dependency packages. It is recommended that Git not be used to pull the replacement code. Some dependency packages may need to be manually developed. Installation to avoid obvious errors. Here's the official SDK

https://developers.facebook.com/docs/reference/php

 

6. Adding Fackbook login requires creating an application

Effective jump URIs are added here, where jump links are deployed to the online environment for submission to facebook audits, and local tests are not required, such as local locahost:8080 can not add jump URIs.

Facebook officially requests an exit entry to cancel the authorization. As for the data deletion request address here, the author finds that it is not necessary, so it is enough to provide an exit entry so as not to pass the audit.

7. Facebook privilege list

https://developers.facebook.com/docs/facebook-login/permissions/

Reasonable application should be made according to the needs of the project. Do not apply for unnecessary rights. If the project needs more rights, try to apply for no more than two rights at a time.

The steps of the application are as follows:

1. Adding the reason for the application is to describe the project's use of this authority and what role it will bring to users. Describe it in English as far as possible, because the auditing platform is Facebook's customer service in the United States, and you can't read Chinese!

2. Video recording. Video recording software is needed here. It is recommended by the government. https://www.apowersoft.cn/free-online-screen-recorder A very useful video recording software

3. Application submission, Facebook review time is still very timely, generally no more than three days, two working days almost to reply, but the reply is too official, not detailed enough, need to spend more time to ponder!

Here is our right to apply for success, the first time novice docking, feeling too south, too south...

8, summarize here, by the way, Facebook API, no Google write details, some functions are not, API also did not declare, encountered many pits, for a long time, it is best to hear it because privacy policy is not given, MMP.

Finally, I mention the OAuth authorization process used here. Students who have not contacted will go to know it first. I'll talk about it here.

The application number and the application key can be obtained from the previous creation. A token valid for three months can be obtained from both. Each time the Facebook API is requested, the token must be taken to obtain a temporary token, and then the final interface data can be requested through the temporary token.

Here I'll post the php code.

Authorize login and obtain temporary access passwords:

 1      $appId = facebook appId;
 2         $appSecret = facebook appSecret;
 3         $callbackUrl = facebook callbackUrl;
 4         $fb = new Facebook\Facebook([
 5             'app_id' => $appId,
 6             'app_secret' => $appSecret,
 7             'default_graph_version' => 'v2.10',
 8         ]);
 9 
10         $helper = $fb->getRedirectLoginHelper();
11         try {
12             $accessToken = $helper->getAccessToken();
13         } catch(Facebook\Exceptions\FacebookResponseException $e) {
14             echo 'Graph returned an error: ' . $e->getMessage();
15             exit;
16         } catch(Facebook\Exceptions\FacebookSDKException $e) {
17             echo 'Facebook SDK returned an error: ' . $e->getMessage();
18             exit;
19         }
20 
21         if (! isset($accessToken)) {
22             if ($helper->getError()) {
23                 header('HTTP/1.0 401 Unauthorized');
24                 echo 'Please check the account settings. Facebook Account cannot be authorized. Details:' . $helper->getError()   . ' ' . $helper->getErrorCode() . ' ' . $helper->getErrorReason()  . ' ' . $helper->getErrorDescription() . "\n";
25             } else {
26                 header('HTTP/1.0 400 Bad Request');
27                 echo 'Bad request';
28             }
29             exit;
30         }
31 
32         $accessToken = $accessToken->getValue();
33         $oAuth2Client = $fb->getOAuth2Client();
34         $tokenMetadata = $oAuth2Client->debugToken($accessToken);
35         $tokenMetadata->validateAppId($appId);
36         $tokenMetadata->validateExpiration();
37 
38         $appId = $tokenMetadata->getField('app_id');
39         $type = $tokenMetadata->getField('type');
40         $userId = $tokenMetadata->getField('user_id');
41         $application = $tokenMetadata->getField('application');
42         $isValid = $tokenMetadata->getField('is_valid');
43         $expiresAt = $tokenMetadata->getField('data_access_expires_at');
44         $metadata = [
45             "app_id" => $appId,
46             "type"=> $type,
47             "user_id" => $userId,
48             "application" => $application,
49             "expires_at" => $expiresAt,
50             "is_valid" => $isValid
51         ];
52 
53         $auth = new Facebook\Authentication\AccessToken($accessToken);
54         if (! $auth->isLongLived()) {
55             try {
56                 $accessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
57             } catch (Facebook\Exceptions\FacebookSDKException $e) {
58                 echo "<p>Error getting long-lived access token: " . $e->getMessage() . "</p>\n\n";
59                 exit;
60             }
61         }
62 
63         
65         $this->cache->set($this->facebookAccessTokenKey,(string) $accessToken );
66         $this->cache->set($this->facebookKey, json_encode($metadata));
67 
68         header("Location: {$callbackUrl}");  
 1   /**
 2      * Get a temporary access password
 3      * @param $pageId
 4      * @param $access_token
 5      * @return mixed
 6      */
 7     public function getPageAccessToken($pageId, $access_token)
 8     {
 9         $accessTokenUrl = "https://graph.facebook.com/v4.0/{$pageId}?fields=access_token&access_token={$access_token}";
10         $pageAccessTokenInfo = curl($accessTokenUrl);
11         try{
12             $pageAccessTokenInfo = json_decode($pageAccessTokenInfo, true);
13             $pageAccessToken = $pageAccessTokenInfo['access_token'];
14         }catch (Exception $e) {
15             $this->showResults(-1, null, 'Obtain page_access_token Failure!');
16         }
17 
18         return $pageAccessToken;
19     }

Wake up the authorization dialog box. Our business permission is to ___________. manage_pages And publish_pages Various permissions are changed by themselves! ___________.

   /**
     * Get the facebook authorization code
     */
    public function bindAction(){
        $redirectUrl = facebook redirectUrl;
        $appId = facebook appId;
        $appSecret = facebook appSecret;
        $fb = new Facebook\Facebook([
            'app_id' => $appId,
            'app_secret' => $appSecret,
            'default_graph_version' => 'v2.10',
        ]);
        $helper = $fb->getRedirectLoginHelper();
        $permissions = ['manage_pages','publish_pages'];
        $codeUrl = $helper->getLoginUrl($redirectUrl, $permissions);
        $this->showResults(1, ['url' => $codeUrl]);
    }

Complete posting code

  /**
     * facebook Shared Publishing
     */
    public function facebookShareAction()
    {
        $data = getPost('data');//There can only be one option in a request: 1, Share Links, 2 Single Picture Links, 3 Multiple Pictures ID
        $content['message'] = $data['message'];
        if ($data['link']) {
            $content['link'] = $data['link'];
        } else if ($data['url']) {
            $content['link'] = '';
            $content['url'] = $data['url'];
        } else if ($data['attached_media']) {
            $content['link'] = '';
            $content['url'] = '';

            $media = explode(',', $data['attached_media']);
            if (count($media) >= 10) {
                $this->showResults(-2, null, 'Upload no more than 9 pictures at a time!');
            }
            foreach ($media as $mediaId) {
                $temp[] = ['media_fbid' => $mediaId];
            }

            $content['attached_media'] = json_encode($temp);
        }

        $appId = facebook appId;
        $appSecret = facebook appSecret;
        $fbAccessToken = $this->cache->get($this->facebookAccessTokenKey);
        if (!$fbAccessToken) {
            $this->showResults(-1, null, 'Please bind first Facebook Account number!');
        }

        $fb = new Facebook\Facebook([
            'app_id' => $appId,
            'app_secret' => $appSecret,
            'default_graph_version' => 'v2.3',
        ]);

        try {
            $response = $fb->get(
                '/me/accounts',
                $fbAccessToken
            );
        } catch(FacebookExceptionsFacebookResponseException $e) {
            echo 'Graph returned an error: ' . $e->getMessage();
            exit;
        } catch(FacebookExceptionsFacebookSDKException $e) {
            echo 'Facebook SDK returned an error: ' . $e->getMessage();
            exit;
        }

        $accountInfo = $response->getBody();
        $accountInfo = json_decode($accountInfo, true);
        $pageId =  $accountInfo['data'][0]['id'];
        $accessToken =  $accountInfo['data'][0]['access_token'];
        $pageAccessToken = $this->getPageAccessToken($pageId, $accessToken);
        try {
            $response = $fb->post(
                '/' . $pageId . '/feed',
                $content,
                $pageAccessToken
            );
        } catch(FacebookExceptionsFacebookResponseException $e) {
            echo 'Graph returned an error: ' . $e->getMessage();
            exit;
        } catch(FacebookExceptionsFacebookSDKException $e) {
            echo 'Facebook SDK returned an error: ' . $e->getMessage();
            exit;
        }

        $info = $response->getBody();
        $info = json_decode($info, true);
        $this->showResults(1, ['data' => ['id' => $info['id']]]);
    }

 

Finally, I wish you all success in docking API!

Posted by gojiita on Mon, 02 Sep 2019 20:51:09 -0700