我如何使我的PHP应用程序从不要求提供Gmail API验证码?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了我如何使我的PHP应用程序从不要求提供Gmail API验证码?相关的知识,希望对你有一定的参考价值。

我希望该应用程序自动运行,但是在进行测试时,如果我们度过了一个周末而又不会在星期一碰到它,那么该应用程序要做的第一件事是:

在浏览器中打开以下链接:https://accounts.google.com/o/oauth2/(...)输入验证码:

我曾经在网上的某个地方看到有必要加粗下面代码中的选项;但无法正常工作。

use GuzzleHttp\Client;
require __DIR__ . '/vendor/autoload.php';
if (php_sapi_name() != 'cli') 
    throw new Exception('This application must be run on the command line.');


// @return Google_Client the authorized client object
function getClient()

    $guzzleClient = new GuzzleHttp\Client([
                'proxy' => '<my_ip_proxy_pfsense>:<port>',
                'verify' => false,
        ]);

$client = new Google_Client();
$client->setApplicationName('RS Gmail Check API PHP');
$client->setScopes(Google_Service_Gmail::GMAIL_READONLY);
$client->setAuthConfig('credentials.json');
**$client->setAccessType('offline');**
// Using "consent" ensures that your application always receives a refresh token.
// If you are not using offline access, you can omit this.
**$client->setApprovalPrompt("consent");
$client->setIncludeGrantedScopes(true);   // incremental auth**
//
$client->setPrompt('select_account consent');
$client->setHttpClient($guzzleClient);

$tokenPath = '/opt/gmail-check/token.json';
    if (file_exists($tokenPath)) 
        $accessToken = json_decode(file_get_contents($tokenPath), true);
        $client->setAccessToken($accessToken);
     else 
        $authUrl = $client->createAuthUrl();
        header('Location: ' . filter_var($authUrl, FILTER_SANITIZE_URL));
        if (isset($_GET['code'])) 
            $authCode = $_GET['code'];
            // Exchange authorization code for an access token.
            $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
            header('Location: ' . filter_var($this->redirectUri, 
            FILTER_SANITIZE_URL));

if(!file_exists(dirname($this->tokenFile))) 
                mkdir(dirname($this->tokenFile), 0700, true);
            

            file_put_contents($this->tokenFile, json_encode($accessToken));
        else
            exit('No code found');
        
        
    $client->setAccessToken($accessToken);
// If there is no previous token or it's expired.
    if ($client->isAccessTokenExpired()) 
        // Refresh the token if possible, else fetch a new one.
        if ($client->getRefreshToken()) 
            $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
         else 
$authUrl = $client->createAuthUrl();
            printf("Open the following link in your browser:\n%s\n", $authUrl);
            print 'Enter verification code: ';
            $authCode = trim(fgets(STDIN));

            // Exchange authorization code for an access token.
            $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
            $client->setAccessToken($accessToken);

            // Check to see if there was an error.
            if (array_key_exists('error', $accessToken)) 
                throw new Exception(join(', ', $accessToken));
             // */
        
        // Save the token to a file.
        if (!file_exists(dirname($tokenPath))) 
            mkdir(dirname($tokenPath), 0700, true);
        
        file_put_contents($tokenPath, json_encode($client->getAccessToken()));
    
    return $client;


// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Gmail($client);

// Print the labels in the user's account.
$user = 'me';
$inboxMessage = [];

function decodeBody($body) 
    $rawData = $body;
    $sanitizedData = strtr($rawData,'-_', '+/');
    $decodedMessage = base64_decode($sanitizedData);
    if(!$decodedMessage)
        $decodedMessage = FALSE;
    
    return $decodedMessage;

$list = $service->users_messages->listUsersMessages($user, ['maxResults' => 10, 'q' => $search]);
try
        foreach ($list->getMessages() as $mlist) 

            $message_id = $mlist->id;
            $optParamsGet2['format'] = 'full';
            $single_message = $service->users_messages->get('me', $message_id, $optParamsGet2);
            $payload = $single_message->getPayload();
            $headers = $single_message->getPayload()->getHeaders();
            $snippet = $single_message->getSnippet();

            foreach($headers as $single) 

            if ($single->getName() == 'Subject') 

                $message_subject = $single->getValue();

            
 else if ($single->getName() == 'Date') 

                $message_date = $single->getValue();
                $message_date = date('M jS Y h:i A', strtotime($message_date));
            

            else if ($single->getName() == 'From') 

                $message_sender = $single->getValue();
                $message_sender = str_replace('"', '', $message_sender);
            
        

            $inboxMessage = [
                'messageId' => $message_id,
                'messageSnippet' => $snippet,
                'messageSubject' => $message_subject,
                'messageDate' => $message_date,
                'messageSender' => $message_sender
                ];

            // With no attachment, the payload might be directly in the body, encoded.
            $body = $payload->getBody();
            $FOUND_BODY = decodeBody($body['data']);

            // If we didn't find a body, let's look for the parts
            if(!$FOUND_BODY) 
                $parts = $payload->getParts();
                foreach ($parts  as $part) 
                    if($part['body']) 
                        $FOUND_BODY = decodeBody($part['body']->data);
                    
                    // Last try: if we didn't find the body in the first parts,
                    // let's loop into the parts of the parts (as @Tholle suggested).
                    if($part['parts'] && !$FOUND_BODY) 


foreach ($part['parts'] as $p) 
                            // replace 'text/html' by 'text/plain' if you prefer
                            if($p['mimeType'] === 'text/html' && $p['body']) 
                                $FOUND_BODY = decodeBody($p['body']->data);
                            
                        
                    
                
            

Update:这个周末我花了一些时间使用Gmail API对另一个项目进行了测试,但是基于我在服务中使用的相同代码,即使我花了5多个小时没有运行该应用程序,多次要求提供令牌。 。最重要的区别在于,在服务中,GuzzleClient配置为与代理一起使用(这将是我们的pfsense防火墙)。我是否由于代理问题而在工作中过期了此令牌问题?

答案
  • 您需要对您的应用进行身份验证才能获得您的access token
  • 第一次运行应用程序或更改范围时,这是必需的

以上是关于我如何使我的PHP应用程序从不要求提供Gmail API验证码?的主要内容,如果未能解决你的问题,请参考以下文章

如何使我的开源 PHP 应用程序跨服务器?

如何使我的数据类型独立于c中的编译器

通过 php 代码访问我的 gmail 收件箱

如何使我的 Python 程序提供的功能可用于在同一台或其他计算机上运行的以其他语言编写的程序?

如何加快 1800 行 PHP 包含?它使我的页面加载速度降低到 10 秒/次

如何使我的登录页面易受 SQL 注入攻击?