# 优惠券、奖励与推荐

兑换、领取和发放优惠券，生成推荐码并兑换奖励。

更新于 2026-11-06

[网页版本](https://www.longplayai.com/zh-hans/docs/guides/offers)

<a id="redeem"></a>

## 兑换券码

用户输入券码后在浏览器调用 `redeemCoupon`。不可用时返回 `reason`，如 `outside_window`、`limit_reached`、`sold_out`。

**redeem.ts**

```ts
import { createLongplay } from "@tinkerlandai/longplay-sdk";

const longplay = createLongplay({
  baseUrl: "https://api.longplayai.com",
  scope: { projectId: "<APP_UUID>", environment: "sandbox" },
});

type UUID = ReturnType<typeof crypto.randomUUID>;

export async function redeem(customerToken: string, code: string, requestId: UUID) {
  longplay.identify(customerToken);
  const { offer, reason } = await longplay.redeemCoupon(code, requestId);
  if (!offer) return { ok: false as const, reason };
  const offers = await longplay.listOffers();
  return { ok: true as const, offers };
}
```

<a id="grant"></a>

## 从后端发券

**grant.ts**

```ts
import { createLongplayServer } from "@tinkerlandai/longplay-sdk/server";

const longplay = createLongplayServer({
  baseUrl: process.env.LONGPLAY_API_URL!,
  apiKey: process.env.LONGPLAY_SERVER_KEY!,
  scope: { projectId: process.env.LONGPLAY_PROJECT_ID!, environment: "sandbox" },
});

export async function grantWelcomeCoupon(customerId: string, requestId: string) {
  const { offer, reason } = await longplay.grantOffer({
    customerId,
    couponId: process.env.LONGPLAY_WELCOME_COUPON_ID!,
    requestId,
  });
  return offer ?? reason;
}
```

需要 `offers:grant` 权限。用户自助领取使用浏览器的 `claimCoupon(couponId, requestId)`。

<a id="apply"></a>

## 在购买中使用优惠

- 新购买：把领取到的 `offerId` 传给 `previewAttach`。
- 已有订阅：调用 `setBillingCoupons`。
- 在你自己的结账中用券：后端调用 `recordMerchantEvent` 上报 `coupon.redeemed`。

<a id="referrals"></a>

## 推荐码与奖励

浏览器调用 `createReferralCode({ programId, requestId })` 生成推荐码；被推荐的用户调用 `redeemReward({ code, requestId })` 兑换奖励。

<a id="operations"></a>

## 相关接口

- **优惠券、奖励与推荐 (8)**:  [redeemCoupon](https://www.longplayai.com/zh-hans/docs/api/redeem-coupon.md); [listOffers](https://www.longplayai.com/zh-hans/docs/api/list-offers.md); [grantOffer](https://www.longplayai.com/zh-hans/docs/api/grant-offer.md); [grantModelBenefit](https://www.longplayai.com/zh-hans/docs/api/grant-model-benefit.md); [readModelBenefit](https://www.longplayai.com/zh-hans/docs/api/read-model-benefit.md); [redeemReward](https://www.longplayai.com/zh-hans/docs/api/redeem-reward.md); [createReferralCode](https://www.longplayai.com/zh-hans/docs/api/create-referral-code.md); [claimRewardProduct](https://www.longplayai.com/zh-hans/docs/api/claim-reward-product.md)

- [路径、凭据与权限见全部接口](https://www.longplayai.com/zh-hans/docs/api/operations.md#offers)
