<?php
declare (strict_types = 1);

namespace asc\line;

use think\facade\Db;
use GuzzleHttp\Client;

class LinePay
{
    private $channelId;
    private $channelSecret;

    public function __construct($channelId, $channelSecret)
    {
        $this->channelId = $channelId;
        $this->channelSecret = $channelSecret;
    }

    public function request($data){
        $uri = '/v3/payments/request';
        $Nonce = date('c') . uniqid('-');

        $authMacText = $this->channelSecret . $uri . json_encode($data) . $Nonce;
        $Authorization = base64_encode(hash_hmac('sha256', $authMacText, $this->channelSecret, true));

        $headers = [
            'Content-Type' => 'application/json',
            'X-LINE-ChannelId' => $this->channelId,
            'X-LINE-Authorization-Nonce' => $Nonce,
            'X-LINE-Authorization' => $Authorization
        ];

        $client = new Client([
            'headers' => $headers
        ]);

        $response = $client->post('https://sandbox-api-pay.line.me'.$uri, ['body' => json_encode($data)]);

        return json_decode($response->getBody()->getContents(), true);    	

    }

    public function confirm($transation_id, $data){
        $uri = '/v3/payments/'.$transation_id.'/confirm';
        $Nonce = date('c') . uniqid('-');

        $authMacText = $this->channelSecret . $uri . json_encode($data) . $Nonce;
        $Authorization = base64_encode(hash_hmac('sha256', $authMacText, $this->channelSecret, true));

        $headers = [
            'Content-Type' => 'application/json',
            'X-LINE-ChannelId' => $this->channelId,
            'X-LINE-Authorization-Nonce' => $Nonce,
            'X-LINE-Authorization' => $Authorization
        ];

        $client = new Client([
            'headers' => $headers
        ]);

        $response = $client->post('https://sandbox-api-pay.line.me'.$uri, ['body' => json_encode($data)]);

        return json_decode($response->getBody()->getContents(), true);    	

    }

}
