> For the complete documentation index, see [llms.txt](https://bothub.gitbook.io/project/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://bothub.gitbook.io/project/advanced-tool/api/sheng-cheng-you-hui-quan-de-jie-kou-de-xie-fa.md).

# 生成优惠券的接口的写法

## 接口效果

商户可以公开⼀一个接⼝口，供Bothub调⽤用以设置⽤用户的优惠券码。具体步骤如下：

1. 判断请求的⽤用户id之前是否已经领取过优惠券。如果领取过，则接⼝口返回，不不需要任何操作
2. 如果没有领取过，则⽣生成⼀一个新的优惠券码，且调⽤用Bothub的接⼝口设置该券码。之后在bot⾥既可以进行模板变量方式进行引用。（例如，通过代码实例设置的优惠码以{{coupon\_code}}进行访问）
3. 此处的判断条件仅为示例。商户可以根据自己需要的业务逻辑进行改写和扩充，以实现类似优惠券总量控制，每人限领X张，一定时间内不能重复领取等效果。

## 代码示例

```php
use Http;
public function generateCouponCode(Request $request, $user_id)
    {
        // Check whether this user id has got a coupon before.
        // If yes, return with no actions.
        // If not, generate a new coupon code and set it as the
        // param of the user
        $headers = [
            'APIKEY' => "*API KEY of your bot*"
        ];
        // Call Bothub API to set coupon code as
        Http::post('https://api.bothub.ai/api',[
            'recipient' => [
                'id' => $user_id,
            ],
            'settings' => [
                'params' => [
                    [
                        'key' => 'coupon_code',
                        'value' => 1,
                    ]
                ]
            ],
            'request' => [
                'method' => 'set_params',
                'id' => '*unique request id*',
                'meta' => '',
            ]
        ], 5, $headers);
        return response()->json();
    }
```
