# 決済手段 登録

`POST /v1/customers/{customer_id}/payment_methods`

- operationId: `createCustomerPaymentMethod`
- tags: 決済手段

`customer_id`で指定した顧客に対し、決済手段を登録します。


## コードサンプル

### cURL

```bash
curl \
    -X POST \
    -H "Authorization:Bearer <Secret API Key>" \
    -H "Content-Type: application/json" \
    -d '{
    "pay_type": "Directdebit",
    "default_flag": "1",
    "return_url": "https://your-service.example.com/return",
    "directdebit":  {
        "application_type": "ONLINE",
        "bank_code": "0310",
        "branch_code": "000",
        "account_type": "1",
        "account_number": "0999999",
        "account_name_kana": "ナマエカナ"
    }
}' \
'https://api.test.fincode.jp/v1/customers/{customer_id}/payment_methods'
```

### Go

```go
package main

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

func main() {

	apiKey := "<Secret API Key>"

	customerID := "<Customer ID>"

	body := CreatingPaymentMethodRequest{
		PayType:     "Directdebit",
		DefaultFlag: "1",
		ReturnURL:   "https://your-service.example.com/return",
		Directdebit: Directdebit{
			ApplicationType: "ONLINE",
			BankCode:        "0310",
			BranchCode:      stringPointer("000"),
			AccountType:     stringPointer("1"),
			AccountNumber:   stringPointer("0999999"),
			AccountNameKana: "ナマエカナ",
		},
	}

	marshalledBody, _ := json.Marshal(body)

	url := fmt.Sprintf("https://api.test.fincode.jp/v1/customers/%s/payment_methods", customerID)

	// リクエストの作成
	req, _ := http.NewRequest(
		"POST",
		url,
		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 CreatingPaymentMethodRequest struct {
	PayType     string      `json:"pay_type"`
	DefaultFlag string      `json:"default_flag"`
	Directdebit Directdebit `json:"directdebit"`
	ReturnURL   string      `json:"return_url"`
}

type Directdebit struct {
	ApplicationType  string            `json:"application_type"`
	BankCode         string            `json:"bank_code"`
	BranchCode       *string           `json:"branch_code,omitempty"`
	AccountType      *string           `json:"account_type,omitempty"`
	AccountNumber    *string           `json:"account_number,omitempty"`
	AccountName      *string           `json:"account_name,omitempty"`
	AccountNameKana  string            `json:"account_name_kana"`
	PaperApplication *PaperApplication `json:"paper_application,omitempty"`
}

type PaperApplication struct {
	PostalAccountNumber1 *string `json:"postal_account_number_1,omitempty"`
	PostalAccountNumber2 *string `json:"postal_account_number_2,omitempty"`
	RequestFormId        string  `json:"request_form_id"`
}

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

### Node.js

```javascript
import fetch from "node-fetch";

const BASE_URL = "https://api.test.fincode.jp";

const API_KEY = "<Secret API Key>";

(async () => {
    const customerId = "<Customer ID>";

    const endpoint = `${BASE_URL}/v1/customers/${customerId}/payment_methods`;

    const response = await fetch(endpoint, {
        method: "POST",
        headers: {
            Authorization: `Bearer ${API_KEY}`,
            "Content-Type": "application/json",
        },
        body: JSON.stringify({
            pay_type: "Directdebit",
            default_flag: "1",
            return_url: "https://your-service.example.com/return",
            directdebit: {
                application_type: "ONLINE",
                bank_code: "0310",
                branch_code: "000",
                account_type: "1",
                account_number: "0999999",
                account_name_kana: "ナマエカナ",
            },
        }),
    });
    const paymentMethods = await response.json();
})();
```

### PHP

```php
<?php

$apiKey = '<Secret API Key>';

$customerId = '<Customer ID>';

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

$data = json_encode([
    "pay_type" => "Directdebit",
    "default_flag" => "1",
    "return_url" => "https://your-service.example.com/return",
    "directdebit" => [
        "application_type" => "ONLINE",
        "bank_code" => "0310",
        "branch_code" => "000",
        "account_type" => "1",
        "account_number" => "0999999",
        "account_name_kana" => "ナマエカナ"
    ]
]);

$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>'

customer_id = '<Customer ID>'

url = f'https://api.test.fincode.jp/v1/customers/{customer_id}/payment_methods'

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

data = {
    "pay_type": "Directdebit",
    "default_flag": "1",
    "return_url": "https://your-service.example.com/return",
    "directdebit": {
        "application_type": "ONLINE",
        "bank_code": "0310",
        "branch_code": "000",
        "account_type": "1",
        "account_number": "0999999",
        "account_name_kana": "ナマエカナ"
    }
}

# 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
    customer_id = '<Customer ID>'
    endpoint = "/v1/customers/#{customer_id}/payment_methods"
    
    uri = URI.parse(BASE_URL + endpoint)

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

    data = {
        pay_type: "Directdebit",
        default_flag: "1",
        return_url: "https://your-service.example.com/return",
        directdebit: {
            application_type: "ONLINE",
            bank_code: "9999",
            branch_code: "000",
            account_type: "1",
            account_number: "0999999",
            account_name_kana: "ナマエカナ"
        }   
    }

    # リクエストの作成
    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
```

## パラメータ

| 名前 | 位置 | 必須 | 型 | 説明 |
| --- | --- | --- | --- | --- |
| `customer_id` | path | ✓ | CustomerId_schema | 顧客ID |
| `Tenant-Shop-Id` | header |  | schema | <span class="smallText color--red-400">※ 顧客情報を共有しないプラットフォームのメインショップのみ指定可</span> |

## リクエストボディ

Content-Type: `application/json`

| パラメータ | 型 | 必須 | 説明 |
| --- | --- | --- | --- |
| `pay_type` | PaymentMethodPayType | ✓ |  |
| `default_flag` | properties-default_flag | ✓ |  |
| `return_url` | return_url |  |  |
| `return_url_on_failure` | return_url_on_failure |  |  |
| `client_field_1` | client_field_1 |  | 加盟店自由項目 1 |
| `client_field_2` | client_field_2 |  | 加盟店自由項目 2 |
| `client_field_3` | client_field_3 |  | 加盟店自由項目 3 |
| `card` | object |  | <span class="smallText">※ `pay_type = "Card"`（この決済手段登録がカード情報登録である）のとき必須</span> |
| `directdebit` | object |  | <span class="smallText">※ `pay_type = "Directdebit"`（この決済手段登録が口座振替用の口座情報登録である）のとき必須</span> |

## レスポンス

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

| パラメータ | 型 | 必須 | 説明 |
| --- | --- | --- | --- |
| `id` | PaymentMethod_properties-id |  |  |
| `pay_type` | enum(Card | Directdebit | Virtualaccount) |  | - `Card` |
| `customer_id` | properties-customer_id |  |  |
| `status` | status |  |  |
| `redirect_url` | redirect_url |  |  |
| `redirect_url_accessed_flag` | redirect_url_accessed_flag |  |  |
| `return_url` | return_url |  |  |
| `return_url_on_failure` | return_url_on_failure |  |  |
| `default_flag` | properties-default_flag |  |  |
| `client_field_1` | client_field_1 |  |  |
| `client_field_2` | client_field_2 |  |  |
| `client_field_3` | client_field_3 |  |  |
| `delete_flag` | properties-delete_flag |  |  |
| `process_date` | properties-process_date |  |  |
| `created` | properties-created |  |  |
| `updated` | properties-updated |  |  |
| `card` | card |  |  |
| `directdebit` | directdebit |  |  |
| `virtualaccount` | virtualaccount |  |  |

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

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

