Files
2026-08-20 18:39:37 +07:00

134 lines
3.6 KiB
PHP

<?php
// require_once 'PaymentMethodMapper.php';
// require_once 'GatewayFactory.php';
class PaymentService
{
private $pdo;
public function __construct($pdo)
{
$this->pdo = $pdo;
}
public function createPayment($data)
{
if (empty($data['invoices'])) {
return [
"success" => false,
"message" => "Invoice kosong"
];
}
$customerId = $data['customer_id'];
$method = $data['method'] ?? null;
$gatewayType= $data['gateway_type'];
$code = ($gatewayType == 'winpay') ? 'W' : 'D';
$trxId = 'TRX-' . $code . time() . rand(1000,9999);
$amount = $this->getAmountFromInvoice($data['invoices']);
if ($amount <= 0) {
return [
"success" => false,
"message" => "Nominal tidak valid"
];
}
// Hanya untuk kebutuhan winpay aja yang gak ada payment link nya
if($method){
try {
$mapped = PaymentMethodMapper::map($method);
} catch (Exception $e) {
return [
"success" => false,
"message" => $e->getMessage()
];
}
}
$gateway = GatewayFactory::make($gatewayType, $this->pdo);
if (!$gateway) {
return [
"success" => false,
"message" => "Gateway tidak ditemukan"
];
}
/**
* =========================
* HIT GATEWAY
* =========================
*/
$result = $gateway->charge([
'transaction_id' => $trxId,
'amount' => $amount,
'customer' => $data['customer'],
'invoice_id' => $data['invoices'],
'invoice_detail' => $data['invoice_detail'],
'type' => $mapped['type'],
'channel' => $mapped['channel'],
'endpoint' => $mapped['endpoint'],
'raw_method' => $method
]);
/**
* =========================
* HANDLE ERROR DARI GATEWAY
* =========================
*/
if (($result['status'] ?? '') === 'FAILED') {
return [
"success" => false,
"message" => $result['message'] ?? 'Payment gagal'
];
}
/**
* =========================
* SUCCESS
* =========================
*/
return [
"success" => true,
"transaction_id" => $result['transaction_id'],
"amount" => $amount,
"data" => $result
];
}
/**
* =====================================================
* AMBIL NOMINAL DARI 1 TAGIHAN
* =====================================================
*/
private function getAmountFromInvoice($invoiceIds)
{
if (empty($invoiceIds)) {
return 0;
}
// ambil 1 invoice saja
$invoiceId = is_array($invoiceIds) ? $invoiceIds[0] : $invoiceIds;
$stmt = $this->pdo->prepare("
SELECT verifikasi_tagihan
FROM tagihan
WHERE id = :id
LIMIT 1
");
$stmt->execute([
':id' => $invoiceId
]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
return isset($row['verifikasi_tagihan']) ? (float)$row['verifikasi_tagihan'] : 0;
}
}