Untitled

 avatar
unknown
plain_text
2 years ago
6.5 kB
6
Indexable
<?php

class Am_Paysystem_Xendit extends Am_Paysystem_Abstract
{
    const PLUGIN_STATUS = self::STATUS_DEV;
    const PLUGIN_REVISION = '@@VERSION@@';

    protected $defaultTitle = "Xendit";
    protected $defaultDescription = "Supports Credit Cards, eWallets, etc.";

    const
        API_URL = 'https://api.xendit.co/v2/',
        RECURRING_URL = 'https://api.xendit.co/recurring_payments',
        RECURRING_ID = 'xendit-recurring-id';

    public function getSupportedCurrencies()
    {
        return ['IDR', 'PHP'];
    }

    public function  _initSetupForm(Am_Form_Setup $form)
    {
        $form->addText('api_key',['class' => 'am-el-wide'])
            ->setLabel("API Key")
            ->addRule('required');
        $form->addText('token',['class' => 'am-el-wide'])
            ->setLabel("Verification Token")
            ->addRule('required');
    }

    function isConfigured()
    {
        return strlen($this->getConfig('api_key')) && strlen($this->getConfig('token'));
    }

    public function getRecurringType()
    {
        return self::REPORTS_REBILL;
    }

    function _process($invoice, $request, $result)
    {
        $req = new Am_HttpRequest(self::API_URL . 'invoices', Am_HttpRequest::METHOD_POST);
        $req->setAuth($this->getConfig('api_key'));
        $req->addPostParameter([
            'external_id' => $invoice->public_id,
            'amount' => $invoice->first_total,
            'description' => $invoice->getLineDescription(),
            'customer[given_names]' => $invoice->getName(),
            'customer[email]' => $invoice->getEmail(),
            'customer[mobile_number]' => $invoice->getPhone(),
            'success_redirect_url' => $this->getReturnUrl(),
            'failure_redirect_url' => $this->getCancelUrl(),
            'currency' => $invoice->currency,
        ]);
        $res = $req->send();

        $l = $this->getDi()->invoiceLogRecord;
        $l->paysys_id = $this->getId();
        $l->title = 'createinvoice';
        $l->setInvoice($invoice);
        $l->add($req);
        $l->add($res);
        $vars = json_decode($res->getBody(), true);
        if(($res->getStatus() == 200) && (!empty($vars['invoice_url'])))
        {
            $a = new Am_Paysystem_Action_Redirect($vars['invoice_url']);
            $result->setAction($a);
        }
        else
        {
            throw new Am_Exception_InputError(___("Payment failed"));
        }
    }

    function getReadme()
    {
        $url = $this->getPluginUrl('ipn');
        return <<<CUT
Set URL in Callback Settings in Xendit Dashboard to:
{$url}
CUT;
    }

    function createTransaction($request, $response, array $invokeArgs)
    {
        return new Am_Paysystem_Xendit_Transaction($this, $request, $response, $invokeArgs);
    }

}

class Am_Paysystem_Xendit_Transaction extends Am_Paysystem_Transaction_Incoming
{

    function __construct($plugin, $request, $response, $invokeArgs)
    {
        parent::__construct($plugin, $request, $response, $invokeArgs);
        $this->vars = json_decode($request->getRawBody(), true);
    }

    public function validateSource()
    {
        return $this->request->getHeader('x-callback-token') == $this->plugin->getConfig('token');
    }

    public function validateTerms()
    {
        return true;
    }

    public function validateStatus()
    {
        return $this->vars['status'] == 'PAID';
    }

    function getUniqId()
    {
        return $this->vars['id'];
    }

    function processValidated()
    {
        if(($this->invoice->status == Invoice::PENDING) && ($this->invoice->rebill_times))
        {
            $result = new Am_Paysystem_Result();
            $req = new Am_HttpRequest(Am_Paysystem_Xendit::RECURRING_URL, Am_HttpRequest::METHOD_POST);
            $req->setAuth($this->plugin->getConfig('api_key'));
            $req->addPostParameter([
                'external_id' => $this->invoice->public_id,
                'payer_email' => $this->invoice->getEmail(),
                'description' => $this->invoice->getLineDescription(),
                'amount' => $this->invoice->second_total,
                'interval' => $this->getInterval($this->invoice),
                'interval_count' => $this->getIntervalCount($this->invoice),
                'total_recurrence' => $this->invoice->rebill_times,
                'start_date' => $this->getStartDate($this->invoice),
                'should_send_email' => 'true',
                'currency' => $this->invoice->currency
            ]);
            $tr = new Am_Paysystem_Xendit_Transaction_Recurring($this->plugin, $this->invoice, $req, true);
            $tr->run($result);
        }
        parent::processValidated();
    }

    function findInvoiceId()
    {
        return $this->vars['external_id'];
    }

    function getInterval(Invoice $invoice)
    {
        $p = new Am_Period($invoice->second_period);
        switch ($p->getUnit())
        {
            case 'd':
                return 'DAY';
            case 'm':
                return 'MONTH';
            case 'y':
                return 'MONTH';
        }
    }
    function getIntervalCount(Invoice $invoice)
    {
        $p = new Am_Period($invoice->second_period);
        $c = $p->getCount();
        switch ($p->getUnit())
        {
            case 'd':
                return $c;
            case 'm':
                return $c;
            case 'y':
                return $c * 12;
        }
    }

    function getStartDate(Invoice $invoice)
    {
        $p = new Am_Period($invoice->first_period);
        return $p->addTo(Am_Di::getInstance()->sqlDate);
    }
}

class Am_Paysystem_Xendit_Transaction_Recurring extends Am_Paysystem_Transaction_CreditCard
{

    function __construct(Am_Paysystem_Abstract $plugin, Invoice $invoice, $request, $doFirst)
    {
        parent::__construct($plugin, $invoice, $request, $doFirst);
    }

    public function parseResponse()
    {
        $this->vars = json_decode($this->response->getBody(), true);
    }

    function getUniqId()
    {
    }

    function processValidated()
    {
        if($this->vars['status'] == 'ACTIVE')
            $this->invoice->data()->set(Am_Paysystem_Xendit::RECURRING_ID, $this->vars['id'])->update();
    }
}
Editor is loading...
Leave a Comment