82 lines
2.6 KiB
PHP
82 lines
2.6 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use App\Models\Product;
|
|
use Illuminate\Support\Facades\Http;
|
|
|
|
class CafeService
|
|
{
|
|
public function __construct(private $cafeConfig)
|
|
{
|
|
}
|
|
|
|
private function getToken()
|
|
{
|
|
if ($this->cafeConfig->token_refreshed_at > now()->subMinute(50)) {
|
|
return $this->cafeConfig->access_token;
|
|
}
|
|
$response = Http::asForm()->post('https://pardakht.cafebazaar.ir/devapi/v2/auth/token/', [
|
|
'grant_type' => 'refresh_token',
|
|
'client_id' => $this->cafeConfig->client_id,
|
|
'client_secret' => $this->cafeConfig->client_secret,
|
|
'refresh_token' => $this->cafeConfig->refresh_token,
|
|
]);
|
|
$response = json_decode($response, true);
|
|
if (isset($response['access_token'])) {
|
|
$this->cafeConfig->access_token = $response['access_token'];
|
|
$this->cafeConfig->token_refreshed_at = now();
|
|
$this->cafeConfig->save();
|
|
}
|
|
|
|
return $response['access_token'] ?? null;
|
|
}
|
|
|
|
private function sendRequest($url, $method, $params = [])
|
|
{
|
|
$response = Http::connectTimeout(2)->timeout(5)->retry(3, 500, throw: false)->send($method, $url, [
|
|
'headers' => [
|
|
'Authorization' => $this->getToken()
|
|
],
|
|
'form_params' => $params
|
|
]);
|
|
|
|
return json_decode($response, true);
|
|
}
|
|
|
|
public function checkPurchase($product, $token)
|
|
{
|
|
$response = $this->sendRequest("https://pardakht.cafebazaar.ir/devapi/v2/api/validate/{$product->packageName->name}/inapp/{$product->uuid}/purchases/$token/", 'GET');
|
|
// if ($response['consumptionState']) {
|
|
// return [
|
|
// 'status' => false,
|
|
// 'message' => 'already consumed',
|
|
// ];
|
|
// }
|
|
|
|
if ($response['purchaseState']) {
|
|
return [
|
|
'status' => false,
|
|
'message' => 'refunded',
|
|
];
|
|
}
|
|
|
|
return [
|
|
'status' => true
|
|
];
|
|
}
|
|
|
|
public function consumePurchase($product, $token)
|
|
{
|
|
if ($product->type == Product::TYPES['permanent']) {
|
|
$response = $this->sendRequest("https://pardakht.cafebazaar.ir/devapi/v2/api/consume/{$product->packageName->name}/purchases/", 'POST', ['token' => $token]);
|
|
}
|
|
}
|
|
|
|
public function checkSubscription($product, $token)
|
|
{
|
|
$response = $this->sendRequest("https://pardakht.cafebazaar.ir/devapi/v2/api/applications/{$product->packageName->name}/active-subscriptions/$token/", 'GET');
|
|
return $response['subscriptions'] ?? false;
|
|
}
|
|
}
|