Skip to content

Instantly share code, notes, and snippets.

@safu9
Last active October 20, 2022 10:55
Show Gist options
  • Select an option

  • Save safu9/b4cd6d674f64c2af6e0cefbe02caf74c to your computer and use it in GitHub Desktop.

Select an option

Save safu9/b4cd6d674f64c2af6e0cefbe02caf74c to your computer and use it in GitHub Desktop.
AAB (Android App Bundle) Uploader for Unity
// Original: https://medium.com/@espresso3389/7d39c2258723
using Google.Apis.AndroidPublisher.v3;
using Google.Apis.AndroidPublisher.v3.Data;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Upload;
using System;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
public class AppUploader {
public static void UploadAAB() {
var packageName = Application.identifier;
var aabPath = GetProjectPath() + "/Build/your-file.aab";
// Load service account key
if (!TryGetEnv("GOOGLE_PLAY_API_KEY", out var apiKey)) {
Debug.LogWarning("No credentials found.");
return;
}
var cred = GoogleCredential.FromJson(File.ReadAllText(apiKey))
.CreateScoped(new[] { AndroidPublisherService.Scope.Androidpublisher });
// Create the AndroidPublisherService
var androidPublisherService = new AndroidPublisherService(new BaseClientService.Initializer { HttpClientInitializer = cred });
// Create a new edit to make changes to your listing.
var edit = androidPublisherService.Edits
.Insert(null, packageName)
.Execute();
// Upload new apk to developer console
androidPublisherService.HttpClient.Timeout = TimeSpan.FromMinutes(30);
var uploadRequest = androidPublisherService.Edits.Bundles.Upload(
packageName,
edit.Id,
new FileStream(aabPath, FileMode.Open),
"application/octet-stream"
);
uploadRequest.ResponseReceived += (bundle) => {
if (bundle == null) {
return;
}
// Assign apk to production track.
var bundleVersionCodes = new List<long?> { (long?)bundle.VersionCode };
var updatedTrack = androidPublisherService.Edits.Tracks.Update(
new Track() { Releases = new TrackRelease[] { new TrackRelease() { VersionCodes = bundleVersionCodes } } },
packageName,
edit.Id,
"production" // 'alpha', beta', 'internal' or 'production'
).Execute();
// Commit changes for edit.
// androidPublisherService.Edits.Commit(packageName, edit.Id);
};
var result = uploadRequest.Upload();
if (result.Exception != null) {
throw result.Exception;
}
if (result.Status != UploadStatus.Completed) {
Debug.LogWarning("Failed to upload AAB");
return;
}
Debug.Log("AAB uploaded to Play Console");
}
static string GetProjectPath() {
return Path.GetFullPath(Application.dataPath + "/..");
}
static bool TryGetEnv(string key, out string value) {
value = Environment.GetEnvironmentVariable(key);
return !string.IsNullOrEmpty(value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment