前置知識
- RESTful API 格式
- Google API OAuth 2種認證方式
User Story
我們想通過訪問 GooglePlay Voided Purchase API 獲取某個應用的用戶退款信息。而Google則提供了一個無效購買的查詢接口宋雏。
分析
先來看看這個 API 的用例
GET https://www.googleapis.com/androidpublisher/v2/applications/
[your_package_name]/purchases/voidedpurchases?access_token=[your_auth_token]
Voided Purchase API 的請求方式為GET芜飘,url需要的參數(shù)有2個,
your_package_name 對應查詢應用的包名磨总,類似 com.google.android.apps.map 查詢開發(fā)者賬戶設置的包名可知
your_auth_token ,身份認證所需的token嗦明,也就是本文的獲取重點。
簡要訪問步驟
1.獲取服務賬戶 Service Account
2.創(chuàng)建訪問程序蚪燕,加載Service Account文件娶牌,獲取token并訪問請求API
如何創(chuàng)建服務賬戶 Service Account?
Google API Console 的界面會有不定期的改動馆纳,因此功能位置有可能變動
登錄開發(fā)者的賬號后诗良, 在Google API Console的頁面
根據(jù)指南,創(chuàng)建/選擇 工程(project)鲁驶,然后創(chuàng)建服務帳戶
創(chuàng)建認證文件
選擇JSON鉴裹,并好好保存。
注: 因為對于Voided Purchase API钥弯,我們需要讀取財務數(shù)據(jù)径荔,還需要對這個Service Account授予“查看財務報告(View financial reports)”的權限
在程序中使用認證文件獲取Token
示例代碼
import java.io.FileInputStream;
import java.util.Arrays;
import java.util.List;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
public class GoogleOAuth2ServiceAccountSample {
/** OAuth 2.0 scopes. 重要,規(guī)范訪問者的查看范圍*/
private static final List<String> SCOPES = Arrays.asList(
"https://www.googleapis.com/auth/androidpublisher");
public static void main(String[] args) {
try {
// 根據(jù)Service Account文件構造認證實例 GoogleCredential
GoogleCredential credential = GoogleCredential
.fromStream(new FileInputStream(
"Google_Wallet-94e38f1f23f7.json"))// 加載服務帳戶認證文件
.createScoped(SCOPES);
// 刷新token
credential.refreshToken();
// 獲取token
System.out.println(credential.getAccessToken());
} catch (Exception e) {
e.printStackTrace();
}
}
}
參考資料
無效購買API 指南(英語)
Voided Purchase API
Google API 入門(繁體)
【JSDC客座文章】第一次接觸Google API就上手
各種坑
Google API的訪問資料都比較分散脆霎,我查看了好幾個示例代碼都沒有提及獲取token的方法总处,以及多數(shù)是使用OAtuh2回調訪問的教程(即類似跳轉到Google登錄界面,需要確認登錄/授權xx應用的那種睛蛛。)
此外鹦马,雖然知道getAccessToken可以獲取到token, 但一直是null, 查了StackOverFlow才知道需要先調用refreshToken.
關于SCOPE,很多示例和代碼都是提及username和mail address. 實際上對于Google內置API的訪問忆肾,需要用到androidpublisher荸频,否則一直返回403,沒有授權客冈。