87 lines
2.9 KiB
PHP
87 lines
2.9 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers;
|
|
|
|
use App\Models\BraintreePayment;
|
|
use App\Models\BraintreePaymentRefund;
|
|
use App\Models\BraintreePaymentStatus;
|
|
use App\Models\OrdersStatusHistory;
|
|
use Braintree\Exception\InvalidSignature;
|
|
use Braintree\Gateway;
|
|
use Illuminate\Contracts\Routing\ResponseFactory;
|
|
use Illuminate\Http\JsonResponse;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Http\Response;
|
|
use Illuminate\Support\Facades\Http;
|
|
use Illuminate\Support\Facades\Log;
|
|
|
|
class WebhookController extends Controller
|
|
{
|
|
protected Gateway $gateway;
|
|
public function __construct(Gateway $gateway)
|
|
{
|
|
$this->gateway = $gateway;
|
|
}
|
|
|
|
public function testWebhook(Request $request): JsonResponse
|
|
{
|
|
try {
|
|
$sampleNotification = $this->gateway->webhookTesting()->sampleNotification(
|
|
$request->input('webhook_kind'),
|
|
$request->input('transaction_id'),
|
|
);
|
|
|
|
// Simulate receiving the webhook directly
|
|
$webhookRequest = new Request([
|
|
'bt_signature' => $sampleNotification['bt_signature'],
|
|
'bt_payload' => $sampleNotification['bt_payload'],
|
|
]);
|
|
|
|
// Call your actual webhook handler
|
|
return $this->handle($webhookRequest);
|
|
|
|
} catch (\Exception $e) {
|
|
return response()->json(['error' => $e->getMessage()], 500);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* @throws InvalidSignature
|
|
*/
|
|
public function handle(Request $request): JsonResponse
|
|
{
|
|
$webhookNotification = $this->gateway->webhookNotification()->parse(
|
|
$request->input('bt_signature'),
|
|
$request->input('bt_payload')
|
|
);
|
|
Log::channel('braintree')->info('Webhook ', ['kind' => $webhookNotification->kind]);
|
|
Log::channel('braintree')->info('Webhook ', ['timestamp' => $webhookNotification->timestamp]);
|
|
Log::channel('braintree')->info('Webhook ', ['transaction' => $webhookNotification->transaction ?? null]);
|
|
Log::channel('braintree')->info('', []);
|
|
|
|
|
|
try {
|
|
$webhookTrans = $webhookNotification->subject['transaction'];
|
|
|
|
if ($refund = BraintreePaymentRefund::where('refund_id', $webhookTrans['id'])->first()) {
|
|
$origTrans = BraintreePayment::where('transaction_id', $refund->transaction_id)->first();
|
|
$is_refund = true;
|
|
} else {
|
|
$origTrans = BraintreePayment::where('transaction_id', $webhookTrans['id'])->first();
|
|
$is_refund = false;
|
|
}
|
|
|
|
BraintreePaymentStatus::create([
|
|
'transaction_id' => $origTrans->transaction_id,
|
|
'status_name' => ($is_refund ? "refund_" : "") . $webhookNotification->kind,
|
|
]);
|
|
|
|
return response()->json('', 200);
|
|
}
|
|
catch (\Exception $e) {
|
|
return response()->json(['error' => $e->getMessage()], 500);
|
|
}
|
|
}
|
|
|
|
}
|