如何更新谷歌应用程序控制台上的应用程序列表

问题描述 投票:1回答:1

我想在google开发者控制台中更新我的应用的标题,简短描述和完整描述。

我不能用PHP做,我在python中找到了一些例子,但我需要在PHP中。

这是我到目前为止所做的事情:

    function updateListing($configFileJSON) {
            echo "Updating Listings"."\n";

            $packageName = 'com.mycompany.myapp';

            $client = new Google_Client(); 
            $client->setApplicationName($packageName);

            $client->setClientId('100......usercontent.com');
            $key = "Rdhmg......5_t"; 

            $client->setClientSecret($key);
            $client->setScopes(array('https://www.googleapis.com/auth/androidpublisher') );

            try {  
            $service = new Google_Service_AndroidPublisher($client); 
            $app_edit = new Google_Service_AndroidPublisher_AppEdit(); 

            $edits = $service->edits;
            $edit_request = $edits->insert($packageName,$app_edit);
            $edit = $edit_request->execute();
            $editId = $edit->getId();
            echo ("Created edit with id: $editId");

            $listing = $service->listings;

            $listing.setTitle("WWW");
            $listing.setFullDescription("WWW");
            $listing.setShortDescription("WWW");
    //        $listing.setVideo("WWW");


            $updateListingsRequest = $edits->listings()->update($packageName,$editId,"af", $listing);
            $updatedUsListing = $updateListingsRequest->execute();

            echo("Created new AF app listing with title: " . $$updatedUsListing->getTitle());       
} catch (Exception $e) {  
       var_dump( $e->getMessage() ); 
       }

 echo "ENDING"."\n";
        }

我知道仍然有一些代码缺失,但直到现在我得到:

string(238) "{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "required",
    "message": "Login Required",
    "locationType": "header",
    "location": "Authorization"
   }
  ],
  "code": 401,
  "message": "Login Required"
 }
}

python中的示例是:

def main(argv):
  # Authenticate and construct service.
  service, flags = sample_tools.init(
      argv,
      'androidpublisher',
      'v2',
      __doc__,
      __file__, parents=[argparser],
      scope='https://www.googleapis.com/auth/androidpublisher')

  # Process flags and read their values.
  package_name = flags.package_name

  try:
    edit_request = service.edits().insert(body={}, packageName=package_name)
    result = edit_request.execute()
    edit_id = result['id']

    listing_response_us = service.edits().listings().update(
        editId=edit_id, packageName=package_name, language='af',
        body={'fullDescription': 'Dessert trunk truck',
              'shortDescription': 'Bacon ipsum',
              'title': 'App Title US'}).execute()

    print ('Listing for language %s was updated.'
           % listing_response_us['language'])

    listing_response_gb = service.edits().listings().update(
        editId=edit_id, packageName=package_name, language='am',
        body={'fullDescription': 'Pudding boot lorry',
              'shortDescription': 'Pancetta ipsum',
              'title': 'App Title UK'}).execute()

    print ('Listing for language %s was updated.'
           % listing_response_gb['language'])

    commit_request = service.edits().commit(
        editId=edit_id, packageName=package_name).execute()

   # print 'Edit "%s" has been committed' % (commit_request['id'])

  except client.AccessTokenRefreshError:
    print ('The credentials have been revoked or expired, please re-run the '
           'application to re-authorize')

if __name__ == '__main__':
  main(sys.argv)

我在认证部分缺少什么?有没有人在PHP中更新应用程序列表?

谢谢

php android google-apps-script google-api-php-client google-play-console
1个回答
0
投票

您的代码似乎缺少整个身份验证部分。

Oauth2Authentication.php

require_once __DIR__ . '/vendor/autoload.php';
/**
 * Gets the Google client refreshing auth if needed.
 * Documentation: https://developers.google.com/identity/protocols/OAuth2
 * Initializes a client object.
 * @return A google client object.
 */
function getGoogleClient() {
    $client = getOauth2Client();
    // Refresh the token if it's expired.
    if ($client->isAccessTokenExpired()) {
        $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
        file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
    }
return $client;
}
/**
 * Builds the Google client object.
 * Documentation: https://developers.google.com/identity/protocols/OAuth2
 * Scopes will need to be changed depending upon the API's being accessed.
 * Example:  array(Google_Service_Analytics::ANALYTICS_READONLY, Google_Service_Analytics::ANALYTICS)
 * List of Google Scopes: https://developers.google.com/identity/protocols/googlescopes
 * @return A google client object.
 */
function buildClient(){

    $client = new Google_Client();
    $client->setAccessType("offline");        // offline access.  Will result in a refresh token
    $client->setIncludeGrantedScopes(true);   // incremental auth
    $client->setAuthConfig(__DIR__ . '/client_secrets.json');
    $client->addScope([YOUR SCOPES HERE]);
    $client->setRedirectUri(getRedirectUri());  
    return $client;
}
/**
 * Builds the redirect uri.
 * Documentation: https://developers.google.com/api-client-library/python/auth/installed-app#choosingredirecturi
 * Hostname and current server path are needed to redirect to oauth2callback.php
 * @return A redirect uri.
 */
function getRedirectUri(){
    //Building Redirect URI
    $url = $_SERVER['REQUEST_URI'];                    //returns the current URL
    if(strrpos($url, '?') > 0)
        $url = substr($url, 0, strrpos($url, '?') );  // Removing any parameters.
    $folder = substr($url, 0, strrpos($url, '/') );   // Removeing current file.
    return (isset($_SERVER['HTTPS']) ? "https" : "http") . '://' . $_SERVER['HTTP_HOST'] . $folder. '/oauth2callback.php';
}
/**
 * Authenticating to Google using Oauth2
 * Documentation:  https://developers.google.com/identity/protocols/OAuth2
 * Returns a Google client with refresh token and access tokens set. 
 *  If not authencated then we will redirect to request authencation.
 * @return A google client object.
 */
function getOauth2Client() {
    try {

        $client = buildClient();

        // Set the refresh token on the client. 
        if (isset($_SESSION['refresh_token']) && $_SESSION['refresh_token']) {
            $client->refreshToken($_SESSION['refresh_token']);
        }

        // If the user has already authorized this app then get an access token
        // else redirect to ask the user to authorize access to Google Analytics.
        if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {

            // Set the access token on the client.
            $client->setAccessToken($_SESSION['access_token']);                 

            // Refresh the access token if it's expired.
            if ($client->isAccessTokenExpired()) {              
                $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
                $client->setAccessToken($client->getAccessToken()); 
                $_SESSION['access_token'] = $client->getAccessToken();              
            }           
            return $client; 
        } else {
            // We do not have access request access.
            header('Location: ' . filter_var( $client->getRedirectUri(), FILTER_SANITIZE_URL));
        }
    } catch (Exception $e) {
        print "An error occurred: " . $e->getMessage();
    }
}

oauth2callback.php

require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/Oauth2Authentication.php';
// Start a session to persist credentials.
session_start();
// Handle authorization flow from the server.
if (! isset($_GET['code'])) {
    $client = buildClient();
    $auth_url = $client->createAuthUrl();
    header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
    $client = buildClient();
    $client->authenticate($_GET['code']); // Exchange the authencation code for a refresh token and access token.
    // Add access token and refresh token to seession.
    $_SESSION['access_token'] = $client->getAccessToken();
    $_SESSION['refresh_token'] = $client->getRefreshToken();    
    //Redirect back to main script
    $redirect_uri = str_replace("oauth2callback.php",$_SESSION['mainScript'],$client->getRedirectUri());    
    header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
© www.soinside.com 2019 - 2024. All rights reserved.