Last active
August 29, 2015 14:14
-
-
Save liuzxc/0fcba06588ae2111da88 to your computer and use it in GitHub Desktop.
Checks the android purchase and consumption status
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- encoding : utf-8 -*- | |
require 'net/http' | |
require 'json' | |
module CheckPurchaseStatus | |
CLIENT_ID = "xxxxxxxxxxxx" | |
CLIENT_SECRET = "xxxxxxxxxx" | |
REDIRECT_URIS = "https://xxxxxxxxxx" | |
GOOGLE_TOKEN_INFO_API = 'https://www.googleapis.com/oauth2/v1/tokeninfo' | |
ANDROID_PUBLISHER_API = 'https://www.googleapis.com/androidpublisher/v1.1/applications' | |
GOOGLE_TOKEN_API = 'https://accounts.google.com/o/oauth2/token' | |
REFRESH_TOKEN = "1/7a5WBPMM_hi1ZB7C3KT6gWxckXFzuXvcHxYiZ12Fyoc" | |
def check_token_from_google(token) | |
uri = URI(GOOGLE_TOKEN_INFO_API) | |
uri.query = URI.encode_www_form({access_token: token}) | |
res = Net::HTTP.get_response(uri) | |
JSON.parse(res.body)["expires_in"].to_i > 100 | |
end | |
def get_refresh_token_from_google | |
params = { | |
grant_type: "refresh_token", | |
client_id: CLIENT_ID, | |
client_secret: CLIENT_SECRET, | |
refresh_token: REFRESH_TOKEN, | |
} | |
res = Net::HTTP.post_form(URI(GOOGLE_TOKEN_API), params) | |
JSON.parse(res.body)["access_token"] | |
end | |
def get_token | |
token = $redis.get("GOODLE_API_TOKEN") | |
valid_token = true | |
valid_token = check_token_from_google(token) if token | |
if token.nil? or valid_token != true | |
token = get_refresh_token_from_google | |
$redis.set("GOODLE_API_TOKEN", token) | |
end | |
token | |
end | |
def confirm_google_play_payment(product_id, purchase_token) | |
package_name = "xxxxxxxx" | |
# url = "#{ANDROID_PUBLISHER_API}/#{package_name}/inapp/#{product_id}/purchases/#{purchase_token}" | |
url = "https://www.googleapis.com/androidpublisher/v2/applications/#{package_name}/purchases/products/#{product_id}/tokens/#{purchase_token}" | |
puts get_token | |
begin | |
uri = URI(url) | |
uri.query = URI.encode_www_form({access_token: token}) | |
res = Net::HTTP.get_response(uri) | |
rescue => e | |
puts e.inspect | |
end | |
return if res.nil? | |
if res.code == '200' | |
JSON.parse(res.body)["purchaseState"].to_i | |
else | |
JSON.parse(res.body)["error"] | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment