# サブスクリプション 登録

`POST /v1/subscriptions`

- operationId: `createSubscription`
- tags: サブスクリプション

`customer_id`で指定した顧客に対して`plan_id`で指定したプランを適用したサブスクリプション情報を登録します。


## コードサンプル

### cURL

```bash
curl \
    -X POST \
    -H "Authorization:Bearer <Secret API Key>" \
    -H "Content-Type: application/json" \
    -d '{
    "pay_type": "Card",
    "plan_id": "<Plan ID>",
    "customer_id": "<Customer ID>",
    "card_id": "<Card ID>",
    "start_date": "2025/05/05",
    "stop_date": "2025/06/05"
}' \
'https://api.test.fincode.jp/v1/subscriptions'
```

### Node.js

```javascript
import { createFincode } from "@fincode/node";

const API_KEY = "<Secret API Key>";

(async () => {
    const fincode = createFincode({ apiKey: API_KEY, isLiveMode: false });

    const planId = "<Plan ID>";

    const customerId = "<Customer ID>";
    const cardId = "<Card ID>";

    try {
        // リクエストの送信
        const subscription = await fincode.subscriptions.create({
            pay_type: "Card",
            plan_id: planId,
            customer_id: customerId,
            card_id: cardId,
            start_date: "2022/05/16",
        });
    } catch (e) {
        // エラーの処理
    }
})();
```

### Go

```go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
)

func main() {

	apiKey := "<Secret API Key>"

	body := CreatingSubscriptionRequest{
		PayType:       "Card",
		PlanID:        "<Plan ID>",
		CustomerID:    "<Customer ID>",
		CardID:        stringPointer("<Card ID>"),
		StartDate:     stringPointer("2024/11/01"),
		InitialAmount: stringPointer("5000"),
	}

	marshalledBody, _ := json.Marshal(body)

	// リクエストの作成
	req, _ := http.NewRequest("POST", "https://api.test.fincode.jp/v1/subscriptions", bytes.NewBuffer(marshalledBody))
	req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", apiKey))
	req.Header.Set("Content-Type", "application/json")

	// リクエストの送信
	client := &http.Client{}
	res, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer res.Body.Close()

}

type CreatingSubscriptionRequest struct {
	ID            *string `json:"id,omitempty"`
	PayType       string  `json:"pay_type"`
	PlanID        string  `json:"plan_id"`
	CustomerID    string  `json:"customer_id"`
	CardID        *string `json:"card_id,omitempty"`
	StartDate     *string `json:"start_date,omitempty"`
	StopDate      *string `json:"stop_date,omitempty"`
	EndMonthFlag  *string `json:"end_month_flag,omitempty"`
	SendURL       *string `json:"send_url,omitempty"`
	ClientField1  *string `json:"client_field_1,omitempty"`
	ClientField2  *string `json:"client_field_2,omitempty"`
	ClientField3  *string `json:"client_field_3,omitempty"`
	InitialAmount *string `json:"initial_amount,omitempty"`
	InitialTax    *string `json:"initial_tax,omitempty"`
}

func stringPointer(s string) *string {
	return &s
}
```

### PHP

```php
<?php

$apiKey = '<Secret API Key>';

$baseUrl = "https://api.test.fincode.jp";
$endpoint = "/v1/subscriptions";
$headers = [
    "Authorization: Bearer " . $apiKey,
    "Content-Type: application/json"
];

$data = json_encode([
    "pay_type" => "Card",
    "plan_id" => "<Plan ID>",
    "customer_id" => "<Customer ID>",
    "card_id" => "<Card ID>",
    "start_date" => "2022/05/16",
]);

$session = curl_init();
curl_setopt($session, CURLOPT_URL, $baseUrl . $endpoint);
curl_setopt($session, CURLOPT_HTTPHEADER, $headers);
curl_setopt($session, CURLOPT_POST, true);
curl_setopt($session, CURLOPT_POSTFIELDS, $data);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
// curl_setopt($session, CURLOPT_SSL_VERIFYPEER, );
// curl_setopt($session, CURLOPT_SSL_VERIFYHOST, );

$response = curl_exec($session);

if ($response === false) {
    # エラー処理
    echo "cURL Error: " . curl_error($session);
} else {
    # APIからのデータを処理
    var_dump($response);
}

curl_close($session);
```

### Python 3

```python
import requests

api_key = '<Secret API Key>'

url = f'https://api.test.fincode.jp/v1/subscriptions'

# ヘッダーを設定
headers = {
    'Authorization': f'Bearer {api_key}',
    'Content-Type': 'application/json'
}

data = {
    "pay_type": "Card",
    "plan_id": "<Plan ID>",
    "customer_id": "<Customer ID>",
    "card_id": "<Card ID>",
    "start_date": "2022/05/16"
}

# HTTP POSTリクエストの送信
try:
    response = requests.post(url, headers=headers, json=data)

    # レスポンスの処理
    if response.status_code == 200:
        # 成功した場合の処理
        print(f"Success: {response.json()}")
    else:
        # エラーの処理
        print(f"Error: {response.json()}")
except requests.RequestException as e:
    # 通信エラーの処理
    print(f"Request error: {e}")
```

### Ruby

```ruby
require 'net/http'
require 'uri'
require 'json'


API_KEY = '<Secret API Key>'
BASE_URL = 'https://api.test.fincode.jp'

def main
    endpoint = "/v1/subscriptions"
    uri = URI.parse(BASE_URL + endpoint)

    http = Net::HTTP.new(uri.host, uri.port)
    http.use_ssl = true

    data = {
        pay_type: "Card",
        plan_id: "<Plan ID>",
        customer_id: "<Customer ID>",
        card_id: "<Card ID>",
        start_date: "2025/05/05",
        stop_date: "2025/06/05"
    }

    # リクエストの作成
    request = Net::HTTP::Post.new(uri.request_uri)
    request['Authorization'] = "Bearer #{API_KEY}"
    request['Content-Type'] = 'application/json'

    request.body = data.to_json

    # リクエストの送信
    response = http.request(request)

    case response
    when Net::HTTPSuccess
        puts 'SUCCESS'
    else
        puts 'ERROR'
    end

    # レスポンスの表示
    puts response.body
end

main
```

## リクエストボディ

Content-Type: `application/json`

| パラメータ | 型 | 必須 | 説明 |
| --- | --- | --- | --- |
| `id` | Subscription_properties-id |  |  |
| `pay_type` | SubscriptionPayType | ✓ |  |
| `plan_id` | Plan_properties-id | ✓ |  |
| `customer_id` | id | ✓ |  |
| `card_id` | properties-id |  | カードID |
| `payment_method_id` | PaymentMethod_properties-id |  | 決済手段ID |
| `start_date` | start_date | ✓ | 課金開始日 |
| `stop_date` | stop_date |  | 課金停止日 |
| `end_month_flag` | end_month_flag |  |  |
| `initial_amount` | initial_amount |  |  |
| `initial_tax` | initial_tax |  |  |
| `remarks` | remarks |  | （`pay_type = Directdebit`の場合のみ利用可能）ご利用明細表示内容 |
| `client_field_1` | client_field_n |  | 加盟店自由項目 1 |
| `client_field_2` | client_field_n |  | 加盟店自由項目 2 |
| `client_field_3` | client_field_n |  | 加盟店自由項目 3 |
| `send_url` | send_url |  |  |

## レスポンス

### 200 リクエストに成功

| パラメータ | 型 | 必須 | 説明 |
| --- | --- | --- | --- |
| `id` | string |  | サブスクリプションID |
| `shop_id` | Shop_properties-id |  |  |
| `pay_type` | SubscriptionPayType |  |  |
| `plan_id` | Plan_properties-id |  |  |
| `plan_name` | plan_name |  |  |
| `customer_id` | id |  | 顧客ID |
| `card_id` | properties-id |  | カードID |
| `payment_method_id` | PaymentMethod_properties-id |  | 決済手段ID |
| `amount` | properties-amount |  |  |
| `tax` | properties-tax |  |  |
| `total_amount` | total_amount |  |  |
| `initial_amount` | integer |  | 初回利用金額 |
| `initial_tax` | integer |  | 初回税送料 |
| `initial_total_amount` | integer |  | 初回合計金額 |
| `status` | SubscriptionStatus |  |  |
| `start_date` | string |  | 課金開始日 |
| `next_charge_date` | string |  | 次回課金日 |
| `stop_date` | string |  | 課金停止日 |
| `end_month_flag` | enum(0 | 1) |  | 月末課金フラグ |
| `send_url` | string |  | ※ 閉塞機能 |
| `subscription_retry_mode` | enum(enabled | disabled) |  | リトライ対象設定 |
| `is_retry_scheduled` | boolean |  | リトライ予定フラグ |
| `error_code` | error_code |  | このサブスクリプションにおいて発生したエラーのうち、一番最新のエラーのエラーコードです。 |
| `client_field_1` | client_field_n |  | 加盟店自由項目 1 |
| `client_field_2` | client_field_n |  | 加盟店自由項目 2 |
| `client_field_3` | client_field_n |  | 加盟店自由項目 3 |
| `remarks` | remarks |  | ご利用明細表示内容 |
| `settlement_route` | DirectDebitSettlementRoute |  | 振替サービス |
| `created` | created |  |  |
| `updated` | updated |  |  |

### 400 不正なリクエスト

| パラメータ | 型 | 必須 | 説明 |
| --- | --- | --- | --- |
| `errors` | array<FincodeAPIError> |  |  |

