main.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import dotenv
  2. import uuid
  3. import os
  4. import logging
  5. from fastapi import FastAPI
  6. from fastapi.templating import Jinja2Templates
  7. from pydantic import BaseModel
  8. from dotenv import load_dotenv
  9. from os.path import join, dirname
  10. from linepay import LinePayApi
  11. # dotenv
  12. dotenv_path = join(dirname(__file__),'./env/.env')
  13. load_dotenv(dotenv_path)
  14. # logger (TBD)
  15. # template
  16. templates = Jinja2Templates(directory="templates")
  17. # Line Pay Config
  18. LINE_PAY_CHANNEL_ID = os.environ.get("LINE_PAY_CHANNEL_ID")
  19. LINE_PAY_CHANNEL_SECRET = os.environ.get("LINE_PAY_CHANNEL_SECRET")
  20. LINE_PAY_REQEST_BASE_URL = "https://{}".format(
  21. os.environ.get("HOST_NAME")
  22. )
  23. line = LinePayApi(LINE_PAY_CHANNEL_ID, LINE_PAY_CHANNEL_SECRET, is_sandbox=True)
  24. # Fastapi
  25. app = FastAPI()
  26. @app.get('/')
  27. def hellow():
  28. return {"Hello" : "World"}
  29. ## Request
  30. @app.get('/request')
  31. async def pay_request():
  32. order_id = str(uuid.uuid4())
  33. amount = 1200
  34. currency = "TWD"
  35. request_options ={
  36. "amount" : amount,
  37. "currency" : currency,
  38. "orderId" : order_id,
  39. "packages" : [
  40. {
  41. "id" : "早鳥方案",
  42. "amount" : 1200,
  43. "products" :[
  44. {
  45. # "id" : "Id_早鳥方案",
  46. "name" : "早鳥方案",
  47. "quantity" : 1,
  48. "price" : 1200,
  49. # "imageUrl" : ""
  50. }
  51. ]
  52. }
  53. ],
  54. "redirectUrls" : {
  55. "confirmUrl" : LINE_PAY_REQEST_BASE_URL + "/confirm",
  56. "cancelUrl" : LINE_PAY_REQEST_BASE_URL + "/cancel"
  57. }
  58. }
  59. response = line.request(request_options)
  60. transaction_id = int(response.get("info",{}).get("transactionId",0))
  61. check_result = line.check_payment_status(transaction_id)
  62. response["transaction_id"] = transaction_id
  63. response["paymentStatusCheckReturnCode"] = check_result.get("returnCode", None)
  64. response["paymentStatusCheckReturnMessage"] = check_result.get("returnMessage", None)
  65. return templates.TemplateResponse("request.html", response=response)
  66. ## Confirm
  67. ## Capture
  68. ## Refund
  69. ## Payment Details API
  70. ## Pay Preapproved API