2016-12-05 4 views
0

내 목표는 내 도메인에서 모든 사용자 이메일 서명을 업데이트하는 것입니다.내 G 스위트 도메인에있는 사용자의 서명 업데이트

전 도메인 위임 권한을 가진 서비스 계정을 설정했습니다. 는하지만이 오류와 함께 붙어있어 :

{ 
"error": { 
    "errors": [ 
    {\n 
    "domain": "global", 
    "reason": "failedPrecondition", 
    "message": "Bad Request" 
    } 
    ], 
    "code": 400, 
    "message": "Bad Request" 
} 
} 

나는 API 탐색기에 의해 실행 된 것보다 같은 요청을 사용하고 있습니다. 그것은 잘 포맷 된해야한다 그래서 ... API를 탐색기에서

이 제대로 나는이 대답을 보내고있어, 하나 작동하지 않습니다 : 내가 권한 문제가 있지만 내가 할 수처럼

{ 
"error": { 
    "errors": [ 
    { 
    "domain": "global", 
    "reason": "forbidden", 
    "message": "Delegation denied for [email protected]" 
    } 
    ], 
    "code": 403, 
    "message": "Delegation denied for [email protected]" 
} 
} 

보인다 왜 그런지 알아 내지 못 하죠.

public function updateSignAction(){ 

    putenv('GOOGLE_APPLICATION_CREDENTIALS='.$this->get('kernel')->getRootDir().'/../app/Resources/files/mydomain.json'); 

    $client = new \Google_Client(); 
    $client->useApplicationDefaultCredentials(); 
    $client->setApplicationName("demo"); 
    $client->addScope([ 
     "https://www.googleapis.com/auth/gmail.settings.basic", 
     "https://www.googleapis.com/auth/gmail.settings.sharing" 
    ]); 
    //$client->setSubject('[email protected]'); 
    $httpClient = $client->authorize(); 

    $response = $httpClient->put(
     'https://www.googleapis.com/gmail/v1/users/[email protected]/settings/sendAs/test', 
     [ 
      'json' => [ 
       'signature' => "test-via-api" 
      ] 
     ] 
    ); 

    return $this->render('AdminBundle:GoogleApi:user/update.html.twig', array(
     'response' => $response->getBody()->getContents(), 
    )); 
} 
+0

클라이언트 라이브러리를 사용하려는 경우 왜 HTTP 요청을 직접 보내고 있습니까? – DaImTo

+0

'Google_Service_Gmail' 클래스를 사용 하시겠습니까? 나는 그것과 같은 문제가 있는데, 나는 방금 다른 방법을 시도했다. – Vivien

답변

0

당신은 API를 인증해야합니다

여기 정보에 대한 내 PHP 테스트 코드입니다. 이렇게하려면 두 가지 방법이 있습니다 :

  • OAuth를 사용 - 서버들이, 로그인 앱에 권한을 부여하고
  • 서비스 계정에 다시 토큰을 전달할 수 있습니다 구글의 서버로 사용자를 리디렉션 . 다음은 조금 더 복잡합니다.
  • 먼저 앱을 설정해야합니다 (완료)
  • 두 번째로 서비스 계정을 설정해야합니다. 앱이 Google에 인증되는 방식입니다. 인증을 위해 개인 키가 포함되어 있습니다.
  • 세 번째로, 사용자는 애플리케이션을 대신하여 액세스하도록 애플리케이션에 권한을 부여해야합니다. 이것이 아직하지 못한 요점입니다.

현재 서비스 계정에서 메일을 보내는 것이지만 Gmail 계정이 아닙니다.

참고 : 일반 Gmail 계정의 경우 '서비스 계정'을 사용할 수 없습니다. OAuth를 사용해야합니다. 서비스 계정을 사용하려면 Google Apps 고객이어야합니다.

GMail/Google Apps 계정을 대신하여 서비스 계정 권한을 부여하려면 this document을 따르십시오. 하나 이상의 API 범위의 경우 https://mail.google.com/,https://www.googleapis.com/auth/gmail.modify,https://www.googleapis.com/auth/gmail.compose,https://www.googleapis.com/auth/gmail.send을 입력해야합니다.

당신이 설정이를 한 후에는 다음과 같이 단지 코드를 수정, 메일을 보낼 수있다 :

$results = $service->users_messages->send("me", $msg); 

작동하지 않습니다,하는 수 없습니다, 서비스 계정에 '나'referrs 때문에 메일을 보내십시오 (위 참조). 우편물 전송되어야하는 :

$results = $service->users_messages->send("[email protected]", $msg); 

을 다음 계정의 사용자 ID (메일 주소)와 me 교체, 당신은 질문이있는 경우

$cred->sub = '[email protected]'; 
below 

$cred = new \Google_Auth_AssertionCredentials(
    $service_account_name, 
    array('https://www.googleapis.com/auth/gmail.send', 'https://www.googleapis.com/auth/gmail.compose'), 
    $key 
); 

<?php 
require_once realpath(dirname(__FILE__) . '/../src/Google/autoload.php'); 
$client_id = '*censored*.apps.googleusercontent.com'; 
$service_account_name = '*censored*@developer.gserviceaccount.com'; 
$key_file_location = '/tmp/apiKey.p12'; 

$userid_from='*censored*'; 
$client = new \Google_Client(); 
$client->setApplicationName("Client_Library_Examples"); 

if (isset($_SESSION['service_token'])) { 
    $client->setAccessToken($_SESSION['service_token']); 
} 

$key = file_get_contents($key_file_location); 
$cred = new \Google_Auth_AssertionCredentials(
    $service_account_name, 
    array('https://www.googleapis.com/auth/gmail.send', 'https://www.googleapis.com/auth/gmail.compose', 'https://www.googleapis.com/auth/gmail.modify','https://www.googleapis.com/auth/gmail.readonly'), 
    $key 
); 
$cred->sub=$userid_from; 
$client->setAssertionCredentials($cred); 

if ($client->getAuth()->isAccessTokenExpired()) { 
    $client->getAuth()->refreshTokenWithAssertion($cred); 
} 

$mime = "*censored*"; 

$service = new \Google_Service_Gmail($client); 

$msg = new \Google_Service_Gmail_Message(); 
$msg->setRaw($mime); 

try { 
    $results = $service->users_messages->send($userid_from, $msg); 
    print 'Message with ID: ' . $results->id . ' sent.'; 
} catch (\Exception $e) { 
    print 'An error occurred: ' . $e->getMessage(); 
} 

를 추가해야합니다 왼쪽, 물어보십시오!

+0

나는 당신의 예제를 따라 갔지만, 몇몇 코드 업데이트 [upgrading.md] (https://github.com/google/google-api-php-client/blob/master)를 따라 갔다. /UPGRADING.md#google_auth_assertioncredentials-has-been-removed). { "error": "unauthorized_client", "error_description": "요청한 권한이없는 클라이언트 또는 범위."라는 오류가 있습니다. }' – Vivien

+0

그리고 관리자 패널의 '고급 설정> 인증'아래에 아무 것도 없습니다. 문제가 될 수 있습니까? – Vivien