# 托管支付

### 1. 配置您的 MoneyCollect 账户

首先，请确保您已在 MoneyCollect 后台上设置了账户。如果您尚未完成，请先按照[“快速开始”](/docs/guidelines_zh/zai-xian-zhi-fu/kuai-su-kai-shi.md)中的所有步骤操作，然后再继续。

### 2. 部署服务端

MoneyCollect 使用 [Session](https://apireference.moneycollect.com/docs/api-v1/ac48ebdba6798-create-a-session) 对象来表达您的支付操作，追踪整个过程中的支付生命周期和状态变化。

**创建结帐按钮**

在您的网站上添加一个 `Checkout` 按钮，该按钮调用服务器api，以创建结账会话。

```html
<html>
  <body>
    <button id="submit"><span id="button-text">结帐</span></button>
  </body>
  <script>
    // 关于订单的信息
    // 用于在服务器上计算订单总额
    var orderData = {
        items: [{ id: "photo-subscription" }],
        currency: "usd"
    };
    document.querySelector("#submit").addEventListener("click", function(evt) {
        evt.preventDefault();
        // 发起支付
        fetch("/create-checkout", {
            method: "POST",
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify(orderData)
        }).then(function(result) {
            return result.json();
        }).then(function(data) {
            // 重定向到支付页面
            window.location.href = data.url;
        });
    });
  </script>
</html>
```

在服务器端添加接口以创建 [Checkout Session](https://apireference.moneycollect.com/docs/api-v1/ac48ebdba6798-create-a-session)。结算会话控制您的客户在托管支付页面上看到的内容。您可以使用以下选项进行配置：

* <mark style="color:blue;">`amountTotal`</mark> 客户需要支付的总金额。
* <mark style="color:blue;">`currency`</mark> 客户需要支付的货币。
* <mark style="color:blue;">`lineItems`</mark> 客户正在购买的商品列表。它可以在托管支付页面上为客户显示。显示的项目包括<mark style="color:purple;">`products'name`</mark>（产品名称）、<mark style="color:purple;">`images`</mark>（图片）和<mark style="color:purple;">`quantity`</mark>（数量）。
* 通过设置<mark style="color:blue;">`orderNo`</mark>，您可以将您的订单编号与结账会话关联起来。将来，您可以通过关联的<mark style="color:blue;">`orderNo`</mark>在 MoneyCollect 后台中找到相应的付款信息。
* 如果没有提供账单地址信息<mark style="color:blue;">`billingDetails`</mark>，则将在结账页面上从客户处收集该信息。

您还需要设置以下 URL，并确保它们可以被公开访问，这样 MoneyCollect 才能将您的客户重定向到这些页面。

* <mark style="color:blue;">`returnUrl`</mark> 您网站上的一个成功或订单确认页面，用于客户完成付款后重定向他们。
* <mark style="color:blue;">`cancelUrl`</mark> 如果客户在结帐期间取消付款，请通过 URL 将其重定向回您的网站。
* <mark style="color:blue;">`notifyUrl`</mark> 完成付款后，支付结果也会发送到此 URL。

> 如果结帐会话未在创建后 24 小时内支付，将自动被取消。
>
> 创建结算会话并成功响应后，请将您的客户重定向到响应中返回的结算页面的 `url`。

此外，您还可以根据具体需求灵活采取其他支付方式。

```java
post("/create-checkout", (request, response) -> {

    // 使用您的私钥
    MoneyCollect.apiKey = "test_pr_NWZsa******";

    // 配置首选支付方式
    List<String> paymentMethodTypes = new ArrayList<>();
    paymentMethodTypes.add("card");
    paymentMethodTypes.add("kakao_pay");
    
    SessionCreateParams params = SessionCreateParams.builder()
        .setReturnUrl("http://localhost:6060/success.html")
        .setCancelUrl("http://localhost:6060/cancel.html")
        .setNotifyUrl("http://localhost:6060/success.html")
        .setPaymentMethodTypes(paymentMethodTypes)
        .setAmountTotal(19 * 100L)
        .setCurrency("USD")
        .setOrderNo("C"+System.currentTimeMillis())
        .setWebsite("https://www.mc.com").build();
    Session session = Session.create(params);
    return JSONObject.toJSONString(new CreateCheckoutResponse(session.getUrl()));
});
```

可以通过启动 Web 服务器（例如 localhost:4242）来测试接口。

**测试**

1. 点击您的<mark style="color:purple;">`结帐`</mark>按钮。
2. 使用测试卡信息填写支付详细信息：
   * 输入 4242 4242 4242 4242 作为<mark style="color:purple;">`卡号`</mark>。
   * 输入任何未来日期作为<mark style="color:purple;">`卡片有效期`</mark>。
   * 输入任何三位数字作为<mark style="color:purple;">`CVC`</mark>。
   * 输入<mark style="color:purple;">`客户的电子邮件`</mark>。
   * 输入<mark style="color:purple;">`客户的名字和姓氏`</mark>。
   * 输入<mark style="color:purple;">`账单详情`</mark>。
3. 单击<mark style="color:purple;">`支付`</mark>。
4. 您将被重定向到您的返回页面。

接下来，您可以在 MoneyCollect 后台中找到新的订单，并检查支付订单详情。

### 3. 创建确认页面

创建一个名为 `<mark style="color:blue;">returnUrl</mark>` 的页面，并在Checkout会话中提供，用于在您的顾客完成支付后，显示订单确认页面或订单详细信息。顾客完成支付后，将被重定向到该页面。

```html
<html>
<head>
  <title>Thanks for your order!</title>
</head>
<body>
  <section>
    <p>
      We appreciate your business! If you have any questions, please email
    </p>
    <p>
      <a href="index.html">Restart demo</a>
    <p>
  </section>
</body>
</html>
```

如果您的客户在支付中取消，则创建结算会话中提供的 `cancelUrl` 页面，他们将被重定向到此页面。

```html
<html>
<head>
  <title>Checkout canceled</title>
</head>
<body>
  <section>
    <p>Forgot to add something to your cart? Shop around then come back to pay!</p>
  </section>
  <p>
    <a href="index.html">Restart demo</a>
  <p>
</body>
</html>
```

### 4. 其他测试资源

您可以使用几个测试卡来确保您的集成已准备好投入生产。

您与任何的 <mark style="color:purple;">`CVC`</mark> 、 <mark style="color:purple;">`postal code`</mark> 和 <mark style="color:purple;">`future expiration date`</mark> 一起使用。

<table><thead><tr><th width="282.73825503355704">卡号</th><th width="150">品牌</th><th>描述</th></tr></thead><tbody><tr><td>4242 4242 4242 4242</td><td>Visa</td><td><mark style="color:green;">成功</mark>并立即处理支付。</td></tr><tr><td>3566 0020 2036 0505</td><td>JCB</td><td><mark style="color:green;">成功</mark>并立即处理支付。</td></tr><tr><td>6011 1111 1111 1117</td><td>Discover</td><td><mark style="color:green;">成功</mark>并立即处理支付。</td></tr><tr><td>3782 8224 6310 0052</td><td>American Express</td><td><mark style="color:green;">成功</mark>并立即处理支付。</td></tr><tr><td>5555 5555 5555 4444</td><td>Mastercard</td><td><mark style="color:green;">成功</mark>并立即处理支付。</td></tr><tr><td>4000 0000 0000 0077</td><td>Visa</td><td>始终失败，拒绝代码为<mark style="color:red;"><code>declined</code></mark></td></tr><tr><td>4000002500003155</td><td>Visa</td><td>此卡在所有交易中都需要3D身份验证</td></tr></tbody></table>

### 5. 付款后

有关管理 WebHooks、处理退款和处理付款后的响应的详细指导，请参阅以下文档。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.moneycollect.com/docs/guidelines_zh/zai-xian-zhi-fu/zai-xian-zhi-fu/tuo-guan-zhi-fu.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
