iT邦幫忙

2024 iThome 鐵人賽

DAY 29
0
Modern Web

從零開始教你做AspNet7.0購物網站系列 第 29

Day-29綠界全方位金流串接(4)正式串接

  • 分享至 

  • xImage
  •  

正式串接

前期準備工作已經完成,接下來就把金流串接上我們的購物網站上去~

前端表單
Shoping/Index.cshtml

<form action="/Shoping/Checkout" method="post">

    <div class="row mb-3">
        <label for="colFormLabel" class="col-sm-2 col-form-label">寄送地址:</label>
        <div class="col-sm-10">
            <input type="text" class="form-control" id="adress" name="adress" placeholder="請輸入地址">
        </div>
    </div>
    <div class="row mb-3">
        <label for="colFormLabel" class="col-sm-2 col-form-label">聯絡電話:</label>
        <div class="col-sm-10">
            <input type="text" class="form-control" id="phone" name="phone" placeholder="請輸入聯絡電話">
        </div>
    </div>
    <div class="row mb-3">
        <label for="colFormLabel" class="col-sm-2 col-form-label">寄送姓名:</label>
        <div class="col-sm-10">
            <input type="text" class="form-control" id="name" name="name" placeholder="請輸入姓名">
        </div>
    </div>
    <input type="number" id="all_number" name="all_number" class="d-none" value=@ViewBag.all_number>
    <p>總價:@ViewBag.all_number</p>

    <div class="d-grid gap-2 col-6 mx-auto">
        <button class="btn btn-outline-primary" type="submit">結帳</button>
    </div>
</form>

控制器執行串接
ShopingController.cs

[HttpPost]
public async Task<IActionResult> Checkout()
{
    // 獲取當前時間
    DateTime currentTime = DateTime.Now;

    // 將時間轉換為數字格式(例如 Unix 時間戳)
    long numericTime = ((DateTimeOffset)currentTime).ToUnixTimeSeconds();

    //內部產生訂單
    var order = new Order
    {
        order_number ="0000"+ Request.Cookies["UserVerify"] + Request.Form["all_number"]+ numericTime,
        adress = Request.Form["adress"],
        phone = Request.Form["phone"],
        price = int.Parse(Request.Form["all_number"]),
        user_id = int.Parse(Request.Cookies["UserVerify"]),
        manufacturer_id = 0,
        payment = false
    };

    _db.Order.Add(order);
    _db.SaveChanges();


    //訂單下的詳細物件
    var shop = _db.Shop.Where(u => u.user_id == int.Parse(Request.Cookies["UserVerify"])).ToList();
    foreach (var item in shop)
    {
        var product = _db.Product.Find(item.product_id);
        int product_number = product.price * item.number;
        var items = new Item
        {
            order_id = order.order_number,
            product_id = item.product_id,
            product_name = product.name,
            price = product_number,
            user_id = int.Parse(Request.Cookies["UserVerify"]),
            manufacturer_id = product.manufacturer_id
        };

        _db.Item.Add(items);
        _db.SaveChanges();
    }


    //訂單記錄完成之後刪除購物車
    var Shoping = _db.Shop.Where(u => u.user_id == int.Parse(Request.Cookies["UserVerify"])).ToList();
    _db.Shop.RemoveRange(Shoping); // 或者使用 _db.RemoveRange(Shoping);
    _db.SaveChanges();

    //連接綠界金流
    var appSettings = Configuration.GetSection("ECPay");

    string ItemName = "shopping";
    DateTime now = DateTime.Now;
    string formattedDateTime = now.ToString("yyyy/MM/dd HH:mm:ss");
    string MerchantTradeNo = order.order_number;
    string TradeDesc = "shopping";
    
    int TotalAmount = order.price;

    string input = "HashKey="+ appSettings["HashKey"] + "&ChoosePayment=Credit&EncryptType=1&ItemName=" + ItemName +"&MerchantID="+ appSettings["MerchantID"] + "&MerchantTradeDate="+ formattedDateTime + "&MerchantTradeNo="+ MerchantTradeNo + "&PaymentType=aio&ReturnURL="+ appSettings["ReturnURL"]+ "&TotalAmount="+ TotalAmount+ "&TradeDesc=" + TradeDesc + "&HashIV=" + appSettings["HashIV"];

    //Console.WriteLine(input);

    input = Encryption.CheckMacValue(input);
    // 创建要发送的 JSON 对象
    var jsonData = new
    {
        CheckMacValue = input,
        ChoosePayment = "Credit",
        EncryptType = 1,
        MerchantID = appSettings["MerchantID"],
        MerchantTradeDate = formattedDateTime,
        MerchantTradeNo = MerchantTradeNo,
        PaymentType = "aio",
        TotalAmount = TotalAmount,
        TradeDesc = TradeDesc,
        ItemName = ItemName,
        ReturnURL = appSettings["ReturnURL"]

    };
    // 将 JSON 对象转换为 application/x-www-form-urlencoded 格式的字符串
    var formData = new FormUrlEncodedContent(new Dictionary<string, string>
        {
            { "CheckMacValue", input },
            { "ChoosePayment", jsonData.ChoosePayment },
            { "EncryptType", jsonData.EncryptType.ToString() },
            { "MerchantID", jsonData.MerchantID },
            { "MerchantTradeDate", jsonData.MerchantTradeDate },
            { "MerchantTradeNo", jsonData.MerchantTradeNo },
            { "PaymentType", jsonData.PaymentType },
            { "TotalAmount", jsonData.TotalAmount.ToString() },
            { "TradeDesc", jsonData.TradeDesc },
            { "ItemName", jsonData.ItemName },
            { "ReturnURL", jsonData.ReturnURL }
        });

    // 发送 POST 请求
    var response = await _httpClient.PostAsync(appSettings["PostUrl"], formData);


    //return Content(await formData.ReadAsStringAsync(), "application/x-www-form-urlencoded");

    // 处理响应
    if (response.IsSuccessStatusCode)
    {
        // 处理成功的情况
        var htmlContent = await response.Content.ReadAsStringAsync();
        return View("Checkout", htmlContent);
        //return Content(htmlContent, "text/html");

    }
    else
    {
        // 处理失败的情况
        return RedirectToAction("Index", "Home");
    }

}

這裡在把資料送給綠界金流之前,會先在網站的資料庫為這筆訂單建檔,之後才會發給綠界金流

成功之後綠界會發一個網頁讓使用者填自己的信用卡資料結帳
https://ithelp.ithome.com.tw/upload/images/20240915/20122704nQdsA6dsmy.jpg

這樣子串接就完成啦~


上一篇
Day-28 綠界全方位金流串接(3)數據加密
下一篇
Day-30 完結撒花~!
系列文
從零開始教你做AspNet7.0購物網站30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言