Rust Google Play API库google-androidpublisher3的使用:管理Android应用发布与内购的Rust集成方案

Rust Google Play API库google-androidpublisher3的使用:管理Android应用发布与内购的Rust集成方案

google-androidpublisher3库提供了访问Google Android Publisher服务的所有功能。

功能特性

该库可以轻松处理以下资源:

  • 应用程序管理

    • 数据安全
    • 设备层级配置(创建/获取/列表)
  • 应用恢复

    • 添加定向
    • 应用恢复
    • 取消/创建/部署
  • 编辑管理

    • APK管理(添加外部托管/列表/上传)
    • 捆绑包管理(列表/上传)
    • 提交/删除
    • 国家可用性获取
    • 详情管理(获取/更新)
    • 扩展文件管理(获取/上传)
    • 图像管理(删除/上传)
    • 列表管理(删除/获取)
    • 测试者管理
    • 版本轨道管理
  • 外部交易

    • 创建/获取/退款外部交易
  • 生成APK

    • 下载/列表
  • 授权管理

    • 创建/删除/更新
  • 应用内商品

    • 批量操作(删除/获取/更新)
    • 单个操作(删除/获取/插入)
  • 内部应用分享

    • 上传APK/捆绑包
  • 订阅管理

    • 订阅创建/获取/更新
    • 基础计划管理
    • 订阅优惠管理

完整示例代码

以下是管理应用内商品(IAP)的完整示例代码:

extern crate hyper;
extern crate hyper_rustls;
extern crate google_androidpublisher3 as androidpublisher3;
use androidpublisher3::api::InAppProduct;
use androidpublisher3::{Result, Error};
use androidpublisher3::{AndroidPublisher, hyper_rustls, hyper_util, yup_oauth2};

#[tokio::main]
async fn main() -> Result<(), Error> {
    // 1. 设置OAuth2认证
    let secret = yup_oauth2::read_application_secret("client_secret.json")
        .await
        .expect("无法读取client_secret.json");
    
    let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
        secret,
        yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
    )
    .persist_tokens_to_disk("tokencache.json")
    .build()
    .await?;

    // 2. 创建HTTP客户端
    let client = hyper_util::client::legacy::Client::builder(
        hyper_util::rt::TokioExecutor::new()
    )
    .build(
        hyper_rustls::HttpsConnectorBuilder::new()
            .with_native_roots()
            .unwrap()
            .https_or_http()
            .enable_http1()
            .build()
    );

    // 3. 创建AndroidPublisher hub实例
    let hub = AndroidPublisher::new(client, auth);

    // 4. 创建应用内商品
    let package_name = "com.example.app";
    let mut in_app_product = InAppProduct::default();
    
    // 配置商品详情
    in_app_product.title = Some("高级会员".to_string());
    in_app_product.description = Some("解锁高级功能".to_string());
    in_app_product.default_price = Some(androidpublisher3::api::Price {
        price_micros: Some(9990000), // $9.99
        currency: Some("USD".to_string()),
        ..Default::default()
    });
    in_app_product.purchase_type = Some("managedUser".to_string());
    in_app_product.sku = Some("premium_membership".to_string());

    // 5. 插入商品到Google Play商店
    let result = hub.inappproducts()
        .insert(in_app_product, package_name)
        .auto_convert_missing_prices(true)
        .doit()
        .await;

    match result {
        Ok((response, inappproduct)) => {
            println!("成功创建IAP: {:?}", inappproduct.sku);
            println!("响应状态: {}", response.status());
        }
        Err(e) => {
            println!("创建IAP失败: {:?}", e);
            return Err(e);
        }
    }

    Ok(())
}

项目设置

在Cargo.toml中添加以下依赖:

[dependencies]
google-androidpublisher3 = "6.0.0"
hyper = "0.14"
hyper-rustls = "0.24"
tokio = { version = "1.0", features = ["full"] }
yup-oauth2 = "7.0"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"

错误处理

错误处理与之前示例类似,所有API调用都返回Result类型,可以处理各种可能的错误情况。

上传和下载

对于上传APK或应用包,可以使用upload方法:

let result = hub.edits()
    .apks_upload(package_name, edit_id)
    .upload(File::open("app-release.apk").unwrap(), "application/vnd.android.package-archive")
    .await;

自定义和回调

可以通过实现Delegate trait来自定义回调行为:

struct MyDelegate;
impl androidpublisher3::client::Delegate for MyDelegate {
    fn progress(&self, dltotal: f64, dlnow: f64, ultotal: f64, ulnow: f64) {
        println!("上传进度: {}/{} bytes", ulnow, ultotal);
    }
}

hub.delegate(Box::new(MyDelegate));

许可证

androidpublisher3库由Sebastian Thiel生成,采用MIT许可证。


1 回复

Rust Google Play API库google-androidpublisher3的使用指南

概述

google-androidpublisher3是一个Rust库,提供了与Google Play Developer API的集成,允许开发者通过Rust程序管理Android应用发布、内购商品和订阅等内容。

主要功能

  • 管理应用发布和更新
  • 处理应用内购买和订阅
  • 获取应用统计数据和评论
  • 管理测试版和Alpha/Beta发布渠道

安装

在Cargo.toml中添加依赖:

[dependencies]
google-androidpublisher3 = "3.0.0"
hyper = "0.14"
hyper-rustls = "0.23"
yup-oauth2 = "7.0"

基本使用方法

1. 认证设置

首先需要设置Google Play API的认证凭据:

use google_androidpublisher3::{AndroidPublisher, oauth2, hyper, hyper_rustls};

async fn get_android_publisher() -> Result<AndroidPublisher, Box<dyn std::error::Error>> {
    let secret: oauth2::ServiceAccountKey = oauth2::read_service_account_key("service-account.json")
        .await?;
    
    let auth = oauth2::ServiceAccountAuthenticator::builder(secret)
        .build()
        .await?;
    
    let hub = AndroidPublisher::new(
        hyper::Client::builder().build(
            hyper_rustls::HttpsConnectorBuilder::new()
                .with_native_roots()
                .https_or_http()
                .enable_http1()
                .build()
        ),
        auth
    );
    
    Ok(hub)
}

2. 获取应用信息

async fn get_app_info(package_name: &str) -> Result<(), Box<dyn std::error::Error>> {
    let hub = get_android_publisher().await?;
    
    let result = hub.apps().get(package_name)
        .doit()
        .await?;
    
    println!("App Info: {:?}", result.1);
    Ok(())
}

3. 上传APK

async fn upload_apk(package_name: &str, apk_path: &str) -> Result<(), Box<dyn std::error::Error>> {
    let hub = get_android_publisher().await?;
    
    let mut apk_file = std::fs::File::open(apk_path)?;
    let mut apk_data = Vec::new();
    apk_file.read_to_end(&mut apk_data)?;
    
    let result = hub.edits()
        .apks_upload(package_name, &Default::default())
        .upload(apk_data, "application/vnd.android.package-archive".parse()?)
        .await?;
    
    println!("Uploaded APK: {:?}", result.1);
    Ok(())
}

4. 管理内购商品

async fn list_in_app_products(package_name: &str) -> Result<(), Box<dyn std::error::Error>> {
    let hub = get_android_publisher().await?;
    
    let result = hub.inappproducts()
        .list(package_name)
        .doit()
        .await?;
    
    println!("In-app products: {:?}", result.1);
    Ok(())
}

高级用法

发布新版本

async fn publish_release(package_name: &str, version_code: i32, track: &str) -> Result<(), Box<dyn std::error::Error>> {
    let hub = get_android_publisher().await?;
    
    // 1. 创建新的编辑
    let edit = hub.edits().insert(package_name, &Default::default())
        .doit()
        .await?;
    let edit_id = edit.1.id.as_ref().unwrap();
    
    // 2. 更新轨道
    let track_update = google_androidpublisher3::api::Track {
        track: Some(track.to_string()),
        version_codes: Some(vec![version_code]),
        ..Default::default()
    };
    
    hub.edits().tracks_update(track_update, package_name, edit_id, track)
        .doit()
        .await?;
    
    // 3. 提交编辑
    hub.edits().commit(package_name, edit_id)
        .doit()
        .await?;
    
    println!("Successfully published version {} to {} track", version_code, track);
    Ok(())
}

完整示例代码

use google_androidpublisher3::{AndroidPublisher, oauth2, hyper, hyper_rustls};
use std::fs::File;
use std::io::Read;

// 认证设置
async fn get_android_publisher() -> Result<AndroidPublisher, Box<dyn std::error::Error>> {
    let secret: oauth2::ServiceAccountKey = oauth2::read_service_account_key("service-account.json")
        .await?;
    
    let auth = oauth2::ServiceAccountAuthenticator::builder(secret)
        .build()
        .await?;
    
    let hub = AndroidPublisher::new(
        hyper::Client::builder().build(
            hyper_rustls::HttpsConnectorBuilder::new()
                .with_native_roots()
                .https_or_http()
                .enable_http1()
                .build()
        ),
        auth
    );
    
    Ok(hub)
}

// 完整应用管理示例
async fn manage_android_app(package_name: &str, apk_path: Option<&str>) -> Result<(), Box<dyn std::error::Error>> {
    // 1. 获取API客户端
    let hub = get_android_publisher().await?;
    
    // 2. 获取应用信息
    let app_info = hub.apps().get(package_name)
        .doit()
        .await?;
    println!("应用信息: {:?}", app_info.1);
    
    // 3. 如果有APK路径,则上传APK
    if let Some(path) = apk_path {
        let mut apk_file = File::open(path)?;
        let mut apk_data = Vec::new();
        apk_file.read_to_end(&mut apk_data)?;
        
        let upload_result = hub.edits()
            .apks_upload(package_name, &Default::default())
            .upload(apk_data, "application/vnd.android.package-archive".parse()?)
            .await?;
        println!("APK上传结果: {:?}", upload_result.1);
    }
    
    // 4. 获取内购商品列表
    let products = hub.inappproducts()
        .list(package_name)
        .doit()
        .await?;
    println!("内购商品列表: {:?}", products.1);
    
    Ok(())
}

#[tokio::main]
async fn main() {
    let package_name = "com.example.myapp";
    
    if let Err(e) = manage_android_app(package_name, Some("path/to/app.apk")).await {
        eprintln!("应用管理出错: {}", e);
        if let Some(source) = e.source() {
            eprintln!("错误原因: {}", source);
        }
    }
}

注意事项

  1. 需要先在Google Play Console中设置服务账号并下载JSON凭证文件
  2. 服务账号需要有适当的权限(如"Release Manager"或"Financial Data"等)
  3. 某些操作可能需要等待Google Play处理完成才能看到效果

错误处理

建议对API调用进行适当的错误处理:

match hub.apps().get(package_name).doit().await {
    Ok((_response, app_info)) => {
        println!("App info: {:?}", app_info);
    }
    Err(e) => {
        eprintln!("Error getting app info: {}", e);
        if let Some(err) = e.source() {
            eprintln!("Caused by: {}", err);
        }
    }
}

这个库提供了对Google Play Developer API的全面访问,可以自动化许多应用发布和管理任务。

回到顶部