一、背景
最近公司的某個APP需要接入Google Pay,以此記錄一下相關(guān)信息
二锰什、客戶端
Google Pay全部的支付操作都是由客戶端完成,再將支付結(jié)果發(fā)送給服務(wù)端
三掏愁、服務(wù)端防刷
因為服務(wù)端只接收支付結(jié)果歇由,所以需要進行校驗,以防被刷果港;防刷的方式是通過Google API發(fā)送申請沦泌,獲取該訂單的相關(guān)信息,從而判斷該訂單是否重復(fù)
1辛掠、創(chuàng)建OAuth 2.0憑據(jù)
https://console.developers.google.com/apis/credentials
添加的域名必須已被授權(quán)
創(chuàng)建完成客戶獲得client_id谢谦,client_secrert释牺,redirect_url
2、生成Authorization Code
Google中心登陸狀態(tài)回挽,另訪問https://accounts.google.com/o/oauth2/auth?scope=https://www.googleapis.com/auth/androidpublisher&response_type=code&access_type=offline&redirect_uri={REDIRECT_URIS}&client_id={CLIENT_ID}
同意授權(quán)之后會跳轉(zhuǎn)到redirect_url没咙,redirect_url之后的code參數(shù)即為Authorization Code
3、獲取refresh_token
請求地址:https://accounts.google.com/o/oauth2/token
請求參數(shù):code, client_id, client_secret, redirect_uri, grant_type千劈;必須為POST請求
其中g(shù)rant_type值為?authorization_code
返回的結(jié)果為JSON結(jié)構(gòu)祭刚,其中refresh_token需要永久保存
4、獲取access_token
請求地址:https://accounts.google.com/o/oauth2/token
請求參數(shù):client_id, client_secret, refresh_toke, grant_type墙牌;必須為POST請求
grant_type 值固定為 refresh_token
返回的JSON涡驮,access_token有效期為3600
{
? "access_token": "ya29.ImCpB-UBTisiQeeipoEAT8-ufAHtKeRCC9Wlft297PnOGGPh8qRCIfg6QjMPLVq7tYkMByxn--QOKbVimiJTuL1_syMZMMFQfSEYvj2zM39awG8EvOz7axdIpAWJSYLu-SM",
? "expires_in": 3600,
? "scope": "https://www.googleapis.com/auth/androidpublisher",
? "token_type": "Bearer"
}
5、使用access_token調(diào)用Google API校驗訂單
https://www.googleapis.com/androidpublisher/v3/applications/packageName/purchases/products/productId/tokens/purchaseToken?access_token=access_token
v1喜滨、v2接口在20191231會被停用捉捅,所以這里建議直接使用v3
packageName:包名,類似com.some.thing
productId:商品id虽风,類似com.some.thing.inapp1
purchaseToken:訂單支付成功生成
返回的JSON棒口,其中purchaseState即為訂單是否已支付,orderId為用戶所見訂單號辜膝,建議保存用以對賬
{
"kind": "androidpublisher#productPurchase",
"purchaseTimeMillis": "1571447997364",
"purchaseState": 0,
"consumptionState": 1,
"developerPayload": "",
"orderId": "GPA.3323-0287-6492-61582",
"purchaseType": 0,
"acknowledgementState": 1
}
四无牵、服務(wù)端邏輯
1、客戶端發(fā)送packageName内舟,productId合敦,purchaseToken
2、服務(wù)端首先通過purchaseToken判斷該請求是否已發(fā)貨验游,已處理直接返回
3充岛、獲取access_token
4、Google API校驗耕蝉,驗證通過進行發(fā)貨
5崔梗、保存該訂單已發(fā)貨,后續(xù)收到請求不在處理
五垒在、其他
Google API使用時可能會遇到兩個問題
1蒜魄、Access Not Configured:需要給APP啟用Google Play Android Developer API
2、projectNotLinked:需要在Google Play Developer Console關(guān)聯(lián)APP
參考:
https://www.cnblogs.com/android-blogs/p/6380725.html?utm_source=itdadao&utm_medium=referral