---
# System prepended metadata

title: 匯率交換系統

---

# 匯率交換系統
![匯率轉換器 - Opera 2024-01-10 21-45-06](https://hackmd.io/_uploads/ByI0YQhda.gif)
# Code
## HTML -> index.html
```htmlmixed!
<!DOCTYPE html>
<html lang="zh-TW">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>匯率轉換器</title>
    <link rel="stylesheet" href="./style.css">
</head>
<body>
    <div class="exchange-rate-calculator">
        <h1>Exchange Rate Calculator</h1>
        <center><div class="tenor-gif-embed" data-postid="14968812126018030690" data-share-method="host" data-aspect-ratio="1" data-width="60%"><a href="https://tenor.com/view/toothless-dance-cas-van-de-pol-casvandepol-toothless-dance-gif-14968812126018030690">Toothless Dance GIF</a>from <a href="https://tenor.com/search/toothless-gifs">Toothless GIFs</a></div> <script type="text/javascript" async src="https://tenor.com/embed.js"></script></center>
        <form id="currency-form">
            <div class="padd">
                <div class="form-group">
                    <label for="currency-one">Currency</label>
                    <select id="currency-one">
                        <option value="TWD">TWD</option>
                        <option value="USD">USD</option>
                        <option value="JPY">JPY</option>
                        <option value="EUR">EUR</option>
                        <!-- 這裡可以新增更多幣種 -->
                    </select>
                    <input type="number" id="amount-one" placeholder="Enter amount">
                </div>
            </div>
            <div class="inner">
                <button type="button" id="swap-button">SWAP</button>
            </div>

            <div class="form-group">
                <label for="currency-two">Currency</label>
                <select id="currency-two">
                    <option value="TWD">TWD</option>
                    <option value="USD">USD</option>
                    <option value="JPY">JPY</option>
                    <option value="EUR">EUR</option>
                    <!-- 這裡可以新增更多幣種 -->
                </select>
                <input type="number" id="amount-two" placeholder="Result" disabled>
            </div>
        </form>
        <div class="rate-display" id="rate"></div>
    </div>
    <script src="./script.js"></script>
</body>
</html>

```
## CSS -> style.css
```css!
*{
    box-sizing: border-box;
    position: relative;
}

body {
    font-family: '微軟正黑體';
    background-color: #9b9b9b;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    margin: 0;
}

.exchange-rate-calculator {
    background-color: #ffffff;
    padding: 20px;
    width: 300px;
    border-radius: 5px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

h1 {
    color: #333;
    text-align: center;
    margin-bottom: 10px;
    margin-top: 0px;
}

.form-group {
    margin-bottom: 15px;
}

.form-group label {
    display: block;
    margin-bottom: 5px;
}

.form-group input,
.form-group select {
    width: 100%;
    padding: 10px;
    border: 1px solid #cccccc;
    border-radius: 4px;
}

.padd{
    margin-bottom: 60px;
}

.inner{
    position: absolute;
    width: 100%;
    left: 50%;
    top: 50%;
    transform: translate(-50%,-50%);
    /* margin-top: 100px; */
}

#swap-button {
    display: inline-block;
    width: 100%;
    padding: 10px;
    margin: 20px 0;
    font-weight: 800;
    background-color: #39e586;
    color: #ffffff;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    border-bottom: 0px solid #279e5c;
    /* transition: all 0.3; */
    transition: all 0.3s;
}

#swap-button:hover {
    border-bottom: 8px solid #279e5c;
    transform: translate(0,-8px);
}

#swap-button:active{
    transform: translate(0,0);
    border-bottom: 0px solid #279e5c;
    background-color: #279e5c;
    transition: all 0.05s;
}

.rate-display {
    margin-top: 20px;
    text-align: center;
    padding: 10px;
    background-color: #f8f9fa;
    border: 1px solid #dddddd;
    border-radius: 4px;
}

```
## JavaScript -> script.js
```javascript!
// 取得前端元素
var amountOne = document.getElementById("amount-one");
var currencyOne = document.getElementById("currency-one");
var amountTwo = document.getElementById("amount-two");
var currencyTwo = document.getElementById("currency-two");
var swapButton = document.getElementById("swap-button");
var rateDisplay = document.getElementById("rate");

// 輸入金額就直接轉換
amountOne.addEventListener("input", convertCurrency);
currencyOne.addEventListener("change", convertCurrency);
currencyTwo.addEventListener("change", convertCurrency);

// 初始化匯率and結果
convertCurrency();

// swap按鈕
swapButton.addEventListener("click", function () {
    var tempCurrency = currencyOne.value;
    currencyOne.value = currencyTwo.value;
    currencyTwo.value = tempCurrency;
    convertCurrency();
});

// 匯率轉換
function convertCurrency() {
    var fromCurrency = currencyOne.value;
    var toCurrency = currencyTwo.value;

    // 用PHP取得匯率data
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
            var result = JSON.parse(xhr.responseText);
            if (result.success) {
                var rate = result.exchange_rate;
                rateDisplay.innerHTML = `1 ${fromCurrency} = ${rate} ${toCurrency}`;

                var inputAmount = parseFloat(amountOne.value);
                if (!isNaN(inputAmount)) {
                    var convertedAmount = inputAmount * rate;
                    amountTwo.value = convertedAmount.toFixed(2);
                } else {
                    amountTwo.value = "";
                }
            } else {
                console.log(result.error);
            }
        }
    };
    xhr.open("GET", "apikey.php?sourceCurrency=" + fromCurrency + "&targetCurrency=" + toCurrency, true);
    xhr.send();
}

```

## PHP -> apikey.php
```php!
<?php
// 從前端獲取幣種
$sourceCurrency = $_GET['sourceCurrency'];
$targetCurrency = $_GET['targetCurrency'];

// 這裡用的是fixer API
$apiKey = 'a80a4d4df91b1c791956d455ca7cfdfa';
$requestUrl = 'http://data.fixer.io/api/latest?access_key=' . $apiKey;

$ch = curl_init($requestUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);

if (curl_errno($ch)) {
    echo json_encode(array("success" => false, "error" => '错误: ' . curl_error($ch)));
} else {
    $data = json_decode($response, true);

    // 從API獲取匯率
    $exchange_rate = $data['rates'][$targetCurrency] / $data['rates'][$sourceCurrency];

    // 將匯率儲存進database
    $mysqli = new mysqli("localhost", "root", "", "exchange_rates");

    if ($mysqli->connect_error) {
        die("連接失敗: " . $mysqli->connect_error);
    }

    // 檢查database是否已經有該匯率了
    $checkSql = "SELECT * FROM exchange_rate_data WHERE source_currency='$sourceCurrency' AND target_currency='$targetCurrency'";
    $checkResult = $mysqli->query($checkSql);

    if ($checkResult->num_rows === 0) {
        // 沒有就INSERT
        $sql = "INSERT INTO exchange_rate_data (source_currency, target_currency, exchange_rate) VALUES ('$sourceCurrency', '$targetCurrency', $exchange_rate)";

        if ($mysqli->query($sql) === TRUE) {
            echo json_encode(array("success" => true, "exchange_rate" => $exchange_rate));
        } else {
            echo json_encode(array("success" => false, "error" => "Error: " . $sql . "<br>" . $mysqli->error));
        }
    } else {
        // 如果有就直接return
        $row = $checkResult->fetch_assoc();
        echo json_encode(array("success" => true, "exchange_rate" => $row['exchange_rate']));
    }
    $mysqli->close();
}
curl_close($ch);
?>

```
## Database Setting
![image](https://hackmd.io/_uploads/SJp127hdp.png)


