---
# System prepended metadata

title: API-App票券功能
tags: [FET-PU]

---

## 取得用戶票券列表
#### 此 api 需在 request header 帶入 jwt
POST http://20.222.229.77/pu/ticket/recipients

``` json
Request:
{
  "page": 0,
  "size": 5,  
  "source": "PU",
  "userAccount": "jay"
}

Response:
{
  
  "code": 200,
  "data": [
    {
      # 票券夾ID
      "ticketRecipientId": "504228471577247745",
      # 票券名稱
      "ticketItemName": "點數券",
      # 票券到期日
      "ticketItemValidToDate": "2024/12/31",
      # 票券勾選類型(可複選、不可複選)
      "ticketItemSelectionType": "可複選",
      # 票券金額
      "itemAmount": 5
    },
    {
      "ticketRecipientId": "504228471577247746",
      "ticketItemName": "點數券",
      "ticketItemValidToDate": "2024/12/31",
      "ticketItemSelectionType": "可複選",
      "itemAmount": 5
    },
    {
      "ticketRecipientId": "504228471577247747",
      "ticketItemName": "點數券",
      "ticketItemValidToDate": "2024/12/31",
      "ticketItemSelectionType": "可複選",
      "itemAmount": 5
    },
    {
      "ticketRecipientId": "504228471577247748",
      "ticketItemName": "點數券",
      "ticketItemValidToDate": "2024/12/31",
      "ticketItemSelectionType": "可複選",
      "itemAmount": 5
    },
    {
      "ticketRecipientId": "504228471577247749",
      "ticketItemName": "點數券",
      "ticketItemValidToDate": "2024/12/31",
      "ticketItemSelectionType": "可複選",
      "itemAmount": 5
    }
  ]
}
```

## 取得票券兌換的QRCode
#### 此 api 需在 request header 帶入 jwt
POST http://20.222.229.77/pu/ticket/generateQRCode

```jsonld!
Request:
{
 # 票券夾 Ids 
 "ticketRecipientIds": [
    504228471577247745,
    504228471577247746
  ]
}

Response:
QRCode 圖檔

```
#### 程式範例
``` javascript
import React, { useState } from 'react';

const QRCodeGenerator = () => {
  const [ticketRecipientIds, setTicketRecipientIds] = useState([]);
  const [qrCode, setQrCode] = useState(null);

  const handleGenerateQRCode = async () => {
    try {
      // 構建請求對象
      const requestBody = {
        ticketRecipientIds: ticketRecipientIds,
      };

      const response = await fetch('http://20.222.229.77/pu/ticket/generateQRCode', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${token}`  
        },
        body: JSON.stringify(requestBody), // 將請求對象轉換為 JSON 格式
      });

      if (!response.ok) {
        throw new Error('Error generating QR Code');
      }

      // 將二進位數據轉換為可顯示的 Blob 格式
      const blob = await response.blob();
      const qrCodeUrl = URL.createObjectURL(blob);
      setQrCode(qrCodeUrl);
    } catch (error) {
      console.error('Error generating QR Code:', error);
    }
  };

  return (
    <div>
      <h2>QR Code Generator</h2>
      <input
        type="text"
        value={ticketRecipientIds.join(',')}
        onChange={(e) => setTicketRecipientIds(e.target.value.split(','))}
        placeholder="Enter ticket recipient IDs separated by commas"
      />
      <button onClick={handleGenerateQRCode}>Generate QR Code</button>

      {qrCode && (
        <div>
          <h3>Generated QR Code:</h3>
          <img src={qrCode} alt="Generated QR Code" />
        </div>
      )}
    </div>
  );
};

export default QRCodeGenerator;

```

## QRCode 解碼並回傳商品資訊
#### 此 api 需在 request header 帶入 jwt
POST http://20.222.229.77/pu/ticket/decodeQRCode

#### 前端程式範例
```shell!
npm install react-webcam
```
```jsx!
import React, { useRef, useState } from 'react';
import Webcam from 'react-webcam';

const QRCodeUploader = () => {
  const webcamRef = useRef(null);
  const [image, setImage] = useState(null);
  const [data, setData] = useState(null);

  const capture = () => {
    const imageSrc = webcamRef.current.getScreenshot();
    setImage(imageSrc);
  };

  const handleUpload = async () => {
    if (image) {
      try {
        // 將 base64 圖片轉為 blob 格式
        const blob = await (await fetch(image)).blob();

        // 將圖片上傳到後端
        const formData = new FormData();
        formData.append('file', blob, 'qrcode.png');

        const response = await fetch('http://20.222.229.77/pu/ticket/decodeQRCode', {
          method: 'POST',
          headers: {
            'Authorization': 'Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJqYXkiLCJwaG9uZU51bWJlciI6IjA5MTIzNDU2NzgiLCJleHAiOjE3MzAwODMwMzMsImFjY291bnQiOiJqYXkifQ.D-eBzBKTc4okAHc26U2l6ftLT_M24ky_4h2-QUPO5V2j_gFgLYXJ5umpUKjFFRxvF3Wh7ozonhBIdrE8ZRY0Xw'
          },
          body: formData,
        });

        if (response.ok) {
            const result = await response.json();
            setData(result.data);
          } else {
            console.error('Error decoding QR Code:', response.statusText);
          }
      } catch (error) {
        console.error('Error uploading QR Code:', error);
      }
    }
  };

  return (
    <div>
      <h2>QR Code Uploader</h2>
      <Webcam
        audio={false}
        ref={webcamRef}
        screenshotFormat="image/png"
        width={100}
        height={100}
      />
      <button onClick={capture}>Capture QR Code</button>
      {image && (
        <>
          <img src={image} alt="Captured QR Code" />
          <button onClick={handleUpload}>Upload QR Code</button>
        </>
      )}

    {data && (
        <div>
          <h3>Scan Result:</h3>
          <pre>{JSON.stringify(data, null, 2)}</pre>
        </div>
      )}
    </div>
  );
};

export default QRCodeUploader;


```
#### Response 說明
```jsonld!
{
    "code": 200,
    "data": [
        {
            # 票券夾ID, 後續兌換 api 會使用
            "ticketRecipientId": "504228471577247745",
            # 商家名稱 
            "storeName": "jayhung",
            # 票券編號
            "ticketSerialId": 504211739416461314,
            # 品項名稱
            "ticketItemName": "點數券",
            # 品項金額
            "itemAmount": 5.00,
            # 票券效期(起)
            "ticketItemFromToDate": "2024/10/23",
            # 票券效期(迄)
            "ticketItemValidToDate": "2024/12/31",
            # 票券狀態
            "ticketSerialStatus": "已發行可使用"
        },
        {
            "ticketRecipientId": "504228471577247746",
            "storeName": "jayhung",
            "ticketSerialId": 504211739416461315,
            "ticketItemName": "點數券",
            "itemAmount": 5.00,
            "ticketItemFromToDate": "2024/10/23",
            "ticketItemValidToDate": "2024/12/31",
            "ticketSerialStatus": "可兌換(已歸戶到用戶票券夾)"
        }
    ]
}
```

## 用戶票券兌換
#### 此 api 需在 request header 帶入 jwt
POST http://20.222.229.77/pu/ticket/redeem

```json
Request：
{
  	
    # 客戶票券夾 id
    "ticketRecipientIds": [
        "504228471577247745",
        "504228471577247746"
    ],
    # 兌換商家 userId(後台登入者) 
    "redeemedStoreUserId": "496224360160296960"
}

Response：
{
  "code": 200,
  "data": "票券兌換成功!"
}
```

## 取得用戶票券兌換紀錄
#### 此 api 需在 request header 帶入 jwt
POST http://20.222.229.77/pu/ticket/used
```jsonld
Request:
{
  "page": 0,
  "size": 10,
  "source": "PU",
  "userAccount": "jay"
}

Response:
{
  "code": 200,
  "data": [
    {
      "ticketRecipientId": "504228471577247745",
      "ticketItemName": "點數券",
      "ticketItemStatus": "已兌換",
      "ticketItemValidToDate": "2024/12/31",
      "ticketItemSelectionType": null,
      "itemAmount": 5
    },
    {
      "ticketRecipientId": "504228471577247746",
      "ticketItemName": "點數券",
      "ticketItemStatus": "已兌換",
      "ticketItemValidToDate": "2024/12/31",
      "ticketItemSelectionType": null,
      "itemAmount": 5
    }
  ]
```

## 取得用戶票券 Detail
#### 此 api 需在 request header 帶入 jwt

#### 在 api url 最後面直接帶入 recipientId 
GET /pu/ticket/detail/{recipientId}

```jsonld
# 票券已兌換
response:
{
  "code": 200,
  "data": {
    "ticketRecipientId": "504228471577247745",
    # 票券名稱
    "ticketItemName": "點數券",
    # 票券狀態
    "ticketItemStatus": "已兌換",
    # 票券到期日
    "ticketItemValidToDate": "2024/12/31",
    # 票券勾選類型(可複選、不可複選)
    "ticketItemSelectionType": "可複選",
    # 票券金額
    "itemAmount": 5,
    # 消費時間
    "redeemStoreName": "jayhung",
    # 消費地點
    "redeemTime": "2024/10/25"
  }
}

# 票券已轉贈
response:
{
  "code": 200,
  "data": {
    "ticketRecipientId": "504228471577247747",
    # 票券名稱
    "ticketItemName": "點數券",
    # 票券狀態
    "ticketItemStatus": "已轉贈",
    # 票券到期日
    "ticketItemValidToDate": "2024/12/31",
    # 票券勾選類型(可複選、不可複選)
    "ticketItemSelectionType": "可複選",
    # 票券金額
    "itemAmount": 5,
    # 票券轉贈對像名稱
    "transToAccountName": "mavisliang",
    # 票券轉贈時間
    "transToTime": "2024/10/28 08:17:04"
  }
} 

```

## 模糊搜尋使用者帳號-by UserAccount or UserName
#### 此 api 需在 request header 帶入 jwt
POST http://20.222.229.77/pu/system/searchUserByNameOrAccount
```jsonld
Request:
{
  "condition": "m"
}

Response:
{
  "code": 200,
  "data": {
    "records": [
      {
        "userId": "499596945581408260",
        "userAccount": "mavis",
        "userName": "mavisliang"
      }
    ]
  }
}
```

## 用戶票券轉贈
#### 此 api 需在 request header 帶入 jwt
POST http://20.222.229.77/pu/ticket/transfer

```json
Request：
{
  	
    # 客戶票券夾 id
    "ticketRecipientIds": [
        "505977150537465856"
    ],
    # 票券受贈者 
    "transToUserAccount": "jay"
}

Response：
{
  "code": 200,
  "data": [
    {
      "ticketRecipientId": "505977150537465856",
      # 票券名稱
      "ticketItemName": "點數券",
      # 票券到期日
      "ticketItemValidToDate": "2024/12/31",
      # 票券金額
      "itemAmount": 5,
      # 票券贈送對像姓名
      "transToAccountName": "jayhung",
      # 票券轉贈時間  
      "transToTime": "2024/10/28 13:35:48",
      # 票券勾選類型(可複選、不可複選)
      "ticketItemSelectionType": "可複選",
        
    }
  ]
}
```
