- PVSM.RU - https://www.pvsm.ru -
Хочу поделиться опытом подключения платежей с проверкой на сервере к приложению из Google Play.
Итак. У нас есть приложение, готовое для публикации (ссылка [1]). Так же создан платёжный проект (ссылка [2]) и связан с приложением.
Далее по пунктам.
1. Нужно перейти на вкладку Credential;
2. Создать ClientID как Web-Application и указать redirect_uri на наш сервер (например, server.ru [3] и Callback server.ru/callback [4]);
3. Создать ключ типа ServerKey (можно и с пустыми данными).
На сервере делаем обработчик входящей переменной code по адресу server.ru/callback [4].
Она придёт как GET запрос.
Вот пример обработки на языке Python [5] с хранением данных в Редисе [6].
import requests, redis
Redis = redis.Redis()
data = requests.post('https://accounts.google.com/o/oauth2/token',{'code':code,'grant_type':'authorization_code','client_id':client_id,'client_secret':client_secret,'redirect_uri':'http://server.ru/callback/'})
jdata = data.json()
if 'access_token' in jdata and 'token_type' in jdata and 'expires_in' in jdata:
Redis.setex('GooglePayAccess',jdata['access_token'],jdata['expires_in'])
Redis.setex('GooglePayType',jdata['token_type'],jdata['expires_in'])
if "refresh_token" in jdata:
Redis.set('GooglePayRefresh',jdata['refresh_token'])
Далее необходимо заполнить страницу «Consent screen», а так же активировать API «Google Play Android Developer API».
Теперь нужно авторизовать сервис на нашем сервере.
Обязательно это нужно сделать с того аккаунта, с которого был создан платёжный проект.
Далее переходим под этим аккаунтом по ссылке [7], подставив вместо ……. наш ClientID.
https://accounts.google.com/o/oauth2/auth?scope=https://www.googleapis.com/auth/androidpublisher&response_type=code&access_type=offline&redirect_uri=http://server.ru/callback/&client_id=……………………………………
Эта ссылка как раз и отправит на наш колбэк переменную code.
После активации аккаунта можем работать с платежами.
Передаём на сервер данные о платеже, полученные клиентом от Google, и проверяем их со своей стороны.
import requests, redis
Redis = redis.Redis()
access_token = Redis.get('GooglePayAccess')
token_type = Redis.get('GooglePayType')
if not access_token or not token_type:
refresh_token = Redis.get('GooglePayRefresh')
data = requests.post('https://accounts.google.com/o/oauth2/token',{'grant_type':'refresh_token','client_id':client_id,'client_secret':client_secret,'refresh_token':refresh_token})
jdata = data.json()
if 'access_token' in jdata and 'token_type' in jdata and 'expires_in' in jdata:
access_token = jdata['access_token']
token_type = jdata['token_type']
Redis.setex('GooglePayAccess',access_token,jdata['expires_in'])
Redis.set('GooglePayType',token_type,jdata['expires_in'])
url = 'https://www.googleapis.com/androidpublisher/v2/applications/%s/purchases/products/%s/tokens/%s?key=%s' % (packageName,productId,purchaseToken,api_key)
response = requests.get(url,headers={"Authorization":"%s %s" % (token_type,access_token)})
jdata2 = response.json()
Если принятые от клиента данные совпадают с данными от Google, то можем смело начислять пользователю виртуальную валюту.
Удачных продаж!
Автор: kovalyov_makc
Источник [8]
Сайт-источник PVSM.RU: https://www.pvsm.ru
Путь до страницы источника: https://www.pvsm.ru/python/71668
Ссылки в тексте:
[1] ссылка: https://play.google.com/apps/publish/
[2] ссылка: https://console.developers.google.com/project
[3] server.ru: http://server.ru
[4] server.ru/callback: http://server.ru/callback
[5] Python: http://python.org
[6] Редисе: http://redis.io
[7] ссылке: https://accounts.google.com/o/oauth2/auth?scope=https://www.googleapis.com/auth/androidpublisher&response_type=code&access_type=offline&redirect_uri=http://server.ru/callback/&client_id=……………………………………
[8] Источник: http://habrahabr.ru/post/240447/
Нажмите здесь для печати.