Skip to content

Instantly share code, notes, and snippets.

@Fed0t
Created November 21, 2018 11:16
Show Gist options
  • Save Fed0t/589e2e79dc35193ada1f71b4e0a3d194 to your computer and use it in GitHub Desktop.
Save Fed0t/589e2e79dc35193ada1f71b4e0a3d194 to your computer and use it in GitHub Desktop.
GoogleInAppBillingController php example
<?php
namespace App\Http\Controllers;
use App\AdminActivityLog;
use App\Exceptions\ValidationException;
use App\GooglePayment;
use App\GooglePaymentRenew;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;
use Google_Client;
use Google_Auth_AssertionCredentials;
use Google_Service_AndroidPublisher;
use Google_Auth_Exception;
use Carbon\Carbon;
class GoogleInAppBillingController extends Controller {
//pubsub notifications trigger this functions
public function renewSubscriptionPubSub($payload)
{
$subscription = $this->verifySubscription(
$payload['subscriptionNotification']['subscriptionId'],
$payload['subscriptionNotification']['purchaseToken']
);
$developerPayload = $this->parseDeveloperPayload($subscription->developerPayload);
if ($this->validateResponse($subscription))
{
$expireSubscription = $subscription['expiryTimeMillis'] / 1000;
$subscription->user_id = $developerPayload->id;
$this->storeSubscriptionAfterValidation($subscription);
$subsController = new SubscriptionController();
$subsController->makeUserPremium($developerPayload->id, $expireSubscription, $subscription['orderId']);
// $channel = 'channel.chat.' . $receiver;
// event(new ChatMessageEvent($channel, json_encode($notifyReceiver)));
$this->activityAlert($expireSubscription, $developerPayload->username, 'prelungit');
}
}
public function makeRequest(Request $request)
{
$receiptRequest = $request->all();
$authUser = $request->user();
if ($receiptRequest)
{
$subscriptionId = $receiptRequest['productId'];
$purchaseToken = $receiptRequest['purchaseToken'];
$orderId = $receiptRequest['orderId'];
$paymentId = $this->storeReceiptBeforeValidation($authUser->id, $receiptRequest);
$subscription = $this->verifySubscription($subscriptionId, $purchaseToken);
if ($this->validateResponse($subscription))
{
$developerPayload = $this->parseDeveloperPayload($subscription->developerPayload);
$updatePayment = GooglePayment::find($paymentId);
$updatePayment->status = 'premium';
$updatePayment->save();
$expireSubscription = $subscription['expiryTimeMillis'] / 1000;
$subsController = new SubscriptionController();
$subsController->makeUserPremium($authUser->id, $expireSubscription, $orderId);
$this->activityAlert($expireSubscription, $developerPayload->username);
return json_encode($subscription, true);
}
}
return false;
}
public function verifySubscription($subscriptionId, $purchaseToken)
{
// set the package name and subscription id
$packageName = Config::get('google.application_id');
try
{
$client = new Google_Client();
$client->setApplicationName(Config::get('google.application_name'));
$client->setAuthConfig(Config::get('google.service_account_json'));
$client->setSubject(Config::get('google.service_account_email'));
$client->setScopes(['https://www.googleapis.com/auth/androidpublisher']);
$service = new Google_Service_AndroidPublisher($client);
$subscription = $service->purchases_subscriptions->get($packageName, $subscriptionId, $purchaseToken);
return $subscription;
} catch (Google_Auth_Exception $e)
{
throw new Exception('Error validating transaction', 500);
}
}
public function storeSubscriptionAfterValidation($subscription)
{
$payment = GooglePaymentRenew::insert($subscription->toArray());
return $payment->id;
}
public function storeReceiptBeforeValidation($userId, $receipt)
{
if (isset($receipt['purchaseToken']))
{
$receiptData = json_decode($receipt['receiptData'], true);
$payment = new GooglePayment();
$payment->user_id = $userId;
$payment->autoRenewing = ($receiptData['autoRenewing']) ? 1 : 0;
$payment->purchaseState = $receipt['purchaseState'];
$payment->purchaseTime = $receipt['purchaseTime'];
$payment->purchaseTime = $receipt['purchaseTime'];
$payment->orderId = $receipt['orderId'];
$payment->productId = $receipt['productId'];
$payment->receiptSignature = $receipt['receiptSignature'];
$payment->developerPayload = $receipt['developerPayload'];
$payment->receiptData = $receipt['receiptData'];
$payment->status = 'pending';
$payment->save();
return $payment->id;
} else
{
throw new ValidationException('No receipt data found', 250);
}
}
public function validateResponse($subscription)
{
if (is_null($subscription))
{
return false;
} elseif (isset($subscription['error']['code']))
{
return false;
} elseif (!isset($subscription['expiryTimeMillis']))
{
return false;
}
$seconds = $subscription['expiryTimeMillis'] / 1000;
$date = date("d-m-Y H:i:s", $seconds);
$datetime = new Carbon($date);
if (Carbon::now()->gt($datetime))
{
return false;
}
return true;
}
public function parseDeveloperPayload($payload)
{
preg_match_all("/\{[^\}]*\}/", $payload, $matches);
$developerPayload = json_decode($matches[0][0]);
return $developerPayload;
}
public function activityAlert($expireTime, $username, $type = 'facut')
{
$now = Carbon::now();
$end = Carbon::createFromTimestamp($expireTime);
$length = $end->diffInDays($now);
$log = new AdminActivityLog();
$log->date = time();
$log->username = $username;
$log->description = 'Payment success (Google Play Store)';
$log->save();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment