# 請求 更新

`PUT /v1/billings/{id}`

- operationId: `updateBillings`
- tags: 請求管理

指定したIDを持つ請求情報を更新します。\
請求 発行APIを呼び出すまで請求は行われません。発行後は 回収困難フラグ、および 加盟店自由項目 のみが更新可能です。


## コードサンプル

### cURL

```bash
#!/bin/bash

# 変数設定
API_KEY="<Secret API Key>"
BILLING_ID="<Billing ID>"

curl \
    -X PUT \
    -H "Authorization: Bearer $API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "bill_type":"01",
      "is_uncollectible": false,
      "customer_id": "CUST001",
      "customer_honorific": "様",
      "customer_overwrite": {
        "name": "株式会社テスト",
        "email": "test@example.com",
        "addr_country": "392",
        "addr_state": "13",
        "addr_city": "新宿区",
        "addr_line_1": "1-1-1",
        "addr_line_2": "テストビル",
        "addr_line_3": "",
        "addr_post_code": "1600022"
      },
      "issuer_overwrite": {
        "addr_state": "13",
        "addr_city": "新宿区",
        "addr_line_1": "1-1-1",
        "addr_line_2": "テストビル",
        "addr_line_3": "",
        "addr_post_code": "1600022",
        "email": "issuer@example.com",
        "phone_number": "0312345678"
      },
      "invoice": {
        "invoice_number": "INV123456",
        "bill_mail_send_flag": "0",
        "receipt_mail_send_flag": "0",
        "underpayment_mail_send_flag": "0",
        "lines": [
          {
            "date": "2023/10/01",
            "name": "商品A",
            "unit_price": 1000,
            "quantity": 2,
            "tax_rate": 10
          }
        ]
      },
      "pay_types": [
        "Virtualaccount",
        "Card"
      ]
    }' \
    "https://api.test.fincode.jp/v1/billings/$BILLING_ID"
```

### Node.js

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

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

(async () => {
    const billingID = "<Billing ID>"; // ここにBilling IDを設定

    const endpoint = `${BASE_URL}/v1/billings/${billingID}`;

    const response = await fetch(endpoint, {
        method: "PUT",
        headers: {
            Authorization: `Bearer ${API_KEY}`,
            "Content-Type": "application/json",
        },
        body: JSON.stringify({
            bill_type: "01",
            is_uncollectible: false,
            customer_id: "CUST001",
            customer_honorific: "様",
            customer_overwrite: {
                name: "株式会社テスト",
                email: "test@example.com",
                addr_country: "JPN", // 3文字の国コード
                addr_state: "13",
                addr_city: "新宿区",
                addr_line_1: "1-1-1",
                addr_line_2: "テストビル",
                addr_line_3: "",
                addr_post_code: "1600022"
            },
            issuer_overwrite: {
                addr_state: "13",
                addr_city: "新宿区",
                addr_line_1: "1-1-1",
                addr_line_2: "テストビル",
                addr_line_3: "",
                addr_post_code: "1600022",
                email: "issuer@example.com",
                phone_number: "0312345678"
            },
            invoice: {
                invoice_number: "INV123456",
                bill_mail_send_flag: "0",
                receipt_mail_send_flag: "0",
                underpayment_mail_send_flag: "0",
                lines: [
                    {
                        date: "2023/10/01",
                        name: "商品A",
                        unit_price: 1000,
                        quantity: 2,
                        tax_rate: 10
                    }
                ]
            },
            pay_types: [
                "Virtualaccount",
                "Card"
            ]
        }),
    });

    if (response.ok) {
        const billingData = await response.json();
        console.log("Billing Updated:", billingData);
    } else {
        console.error("Error updating billing:", await response.text());
    }
})();
```

### Go

```go
package main

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

func main() {
	// APIキーと請求IDを指定
	apiKey := "<Secret API Key>"
	billingID := "<Billing ID>"

	// リクエストボディの作成
	body := UpdateBillingRequest{
		BillType:        "01",
		IsUncollectible: false,
		Invoice: Invoice{
			BillMailSendFlag:         "0",
			ReceiptMailSendFlag:      "0",
			UnderpaymentMailSendFlag: "0",
			InvoiceNumber:            "INV123456",
			Lines: []Line{
				{
					Date:      "2023/10/01",
					Name:      "商品A",
					UnitPrice: 1000,
					Quantity:  2,
					TaxRate:   10,
				},
			},
		},
		CustomerID:        "CUST001",
		CustomerHonorific: "様",
		CustomerOverwrite: CustomerOverwrite{
			Name:        "株式会社テスト",
			Email:       "test@example.com",
			AddrCountry: "392",
			AddrState:   "13",
			AddrCity:    "新宿区",
			AddrLine1:   "1-1-1",
			AddrLine2:   "テストビル",
			AddrLine3:   "",
			AddrPostCode: "1600022",
		},
		IssuerOverwrite: IssuerOverwrite{
			AddrCountry: "JP",
			AddrState:   "13",
			AddrCity:    "新宿区",
			AddrLine1:   "1-1-1",
			AddrLine2:   "テストビル",
			AddrLine3:   "",
			AddrPostCode: "1600022",
			Email:       "issuer@example.com",
			PhoneNumber: "0312345678",
		},
		PayTypes: []string{"Virtualaccount", "Card"},
	}

	// JSONにエンコード
	marshalledBody, err := json.Marshal(body)
	if err != nil {
		log.Fatalf("エンコードエラー: %v", err)
	}

	// URLの設定
	url := fmt.Sprintf("https://api.test.fincode.jp/v1/billings/%s", billingID)

	// HTTPリクエストの作成
	req, err := http.NewRequest("PUT", url, bytes.NewBuffer(marshalledBody))
	if err != nil {
		log.Fatalf("リクエストの作成エラー: %v", err)
	}

	// ヘッダーの設定
	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.Fatalf("リクエストエラー: %v", err)
	}
	defer res.Body.Close()

	// レスポンスのステータスコードの表示
	fmt.Println("Status:", res.Status)
}

type UpdateBillingRequest struct {
	BillType		 string            `json:"bill_type,omitempty"`
	IsUncollectible   bool              `json:"is_uncollectible,omitempty"`
	CustomerID        string            `json:"customer_id,omitempty"`
	CustomerHonorific string            `json:"customer_honorific,omitempty"`
	CustomerOverwrite CustomerOverwrite `json:"customer_overwrite,omitempty"`
	IssuerOverwrite   IssuerOverwrite   `json:"issuer_overwrite,omitempty"`
	Invoice           Invoice           `json:"invoice,omitempty"`
	LinkType          LinkType          `json:"link_type,omitempty"`
	PayTypes          []string          `json:"pay_types,omitempty"`
}

type CustomerOverwrite struct {
	Name        string `json:"name"`
	Email       string `json:"email"`
	AddrCountry string `json:"addr_country"`
	AddrState   string `json:"addr_state"`
	AddrCity    string `json:"addr_city"`
	AddrLine1   string `json:"addr_line_1"`
	AddrLine2   string `json:"addr_line_2"`
	AddrLine3   string `json:"addr_line_3,omitempty"`
	AddrPostCode string `json:"addr_post_code"`
}

type IssuerOverwrite struct {
	AddrCountry string `json:"addr_country"`
	AddrState   string `json:"addr_state"`
	AddrCity    string `json:"addr_city"`
	AddrLine1   string `json:"addr_line_1"`
	AddrLine2   string `json:"addr_line_2"`
	AddrLine3   string `json:"addr_line_3,omitempty"`
	AddrPostCode string `json:"addr_post_code"`
	Email       string `json:"email"`
	PhoneNumber string `json:"phone_number"`
}

type Invoice struct {
	InvoiceNumber            string `json:"invoice_number,omitempty"`
	Lines                    []Line `json:"lines,omitempty"`
	BillMailSendFlag         string `json:"bill_mail_send_flag,omitempty"`
	ReceiptMailSendFlag      string `json:"receipt_mail_send_flag,omitempty"`
	UnderpaymentMailSendFlag string `json:"underpayment_mail_send_flag,omitempty"`
}	

type Line struct {
	Date      string  `json:"date,omitempty"`
	Name      string  `json:"name,omitempty"`
	UnitPrice float64 `json:"unit_price,omitempty"`
	Quantity  float64 `json:"quantity,omitempty"`
	TaxRate   float64 `json:"tax_rate,omitempty"`
}

type LinkType struct {
	SuccessUrl string `json:"type,omitempty"`
	CancelUrl string `json:"type,omitempty"`
	Expire string `json:"type,omitempty"`
	ReceiverMail string `json:"type,omitempty"`
	MailCustomerName string `json:"type,omitempty"`
	Transactions []Transaction `json:"transactions,omitempty"`
}

type Transaction struct {
	Amount       float64 `json:"amount,omitempty"`
	Tax 		float64 `json:"tax,omitempty"`
}
```

### PHP

```php
<?php

$apiKey = '<Secret API Key>';
$billingId = '<Billing ID>';  // ここにBilling IDを設定

$baseUrl = "https://api.test.fincode.jp";
$endpoint = "/v1/billings/{$billingId}";

$headers = [
    "Authorization: Bearer " . $apiKey,
    "Content-Type: application/json"
];

$data = json_encode([
    "bill_type" => "01",
    "is_uncollectible" => false,
    "customer_id" => "CUST001",
    "customer_honorific" => "様",
    "customer_overwrite" => [
        "name" => "株式会社テスト",
        "email" => "test@example.com",
        "addr_country" => "392",
        "addr_state" => "13",
        "addr_city" => "新宿区",
        "addr_line_1" => "1-1-1",
        "addr_line_2" => "テストビル",
        "addr_line_3" => "",
        "addr_post_code" => "1600022"
    ],
    "issuer_overwrite" => [
        "addr_state" => "13",
        "addr_city" => "新宿区",
        "addr_line_1" => "1-1-1",
        "addr_line_2" => "テストビル",
        "addr_line_3" => "",
        "addr_post_code" => "1600022",
        "email" => "issuer@example.com",
        "phone_number" => "0312345678"
    ],
    "invoice" => [
        "invoice_number" => "INV123456",
        "bill_mail_send_flag" => "0",
        "receipt_mail_send_flag" => "0",
        "underpayment_mail_send_flag" => "0",
        "lines" => [
            [
                "date" => "2023/10/01",
                "name" => "商品A",
                "unit_price" => 1000,
                "quantity" => 2,
                "tax_rate" => 10
            ]
        ]
    ],
    "pay_types" => [
        "Virtualaccount",
        "Card"
    ]
]);

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

$response = curl_exec($session);

if ($response === false) {
    // エラー処理
    echo "cURL Error: " . curl_error($session);
} else {
    // APIからのデータを処理
    $httpCode = curl_getinfo($session, CURLINFO_HTTP_CODE);
    echo "HTTP Status Code: " . $httpCode . "\n";
    
    if ($httpCode === 200) {
        $responseData = json_decode($response, true);
        echo "Invoice Updated Successfully:\n";
        var_dump($responseData);
    } else {
        echo "Error Response:\n";
        var_dump($response);
    }
}

curl_close($session);

?>
```

### Python 3

```python
import requests

api_key = '<Secret API Key>'
billing_id = '<Billing ID>'  # ここにBilling IDを設定
url = f'https://api.test.fincode.jp/v1/billings/{billing_id}'

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

data = {
    "bill_type": "01",
    "is_uncollectible": "0",
    "customer_id": "CUST001",
    "customer_honorific": "様",
    "customer_overwrite": {
        "name": "株式会社テスト",
        "email": "test@example.com",
        "addr_country": "JPN", 
        "addr_state": "13",
        "addr_city": "新宿区",
        "addr_line_1": "1-1-1",
        "addr_line_2": "テストビル",
        "addr_line_3": "",
        "addr_post_code": "1600022"
    },
    "issuer_overwrite": {
        "addr_state": "13",
        "addr_city": "新宿区",
        "addr_line_1": "1-1-1",
        "addr_line_2": "テストビル",
        "addr_line_3": "",
        "addr_post_code": "1600022",
        "email": "issuer@example.com",
        "phone_number": "0312345678"
    },
    "invoice": {
        "invoice_number": "INV123456",
        "bill_mail_send_flag": "0",
        "receipt_mail_send_flag": "0",
        "underpayment_mail_send_flag": "0",
        "lines": [
            {
                "date": "2023/10/01",
                "name": "商品A",
                "unit_price": 1000,
                "quantity": 2,
                "tax_rate": 10
            }
        ]
    },
    "pay_types": [
        "Virtualaccount",
        "Card"
    ]
}

# HTTP PUTリクエストの送信
try:
    response = requests.put(url, headers=headers, json=data)
    
    # レスポンスの処理
    print(f"HTTP Status Code: {response.status_code}")
    
    if response.status_code == 200:
        # 成功した場合の処理
        print("Invoice Updated Successfully:")
        print(response.json())
    else:
        # エラーの処理
        print("Error Response:")
        try:
            print(response.json())
        except ValueError:
            # JSONでない場合はテキストを表示
            print(response.text)
            
except requests.RequestException as e:
    # 通信エラーの処理
    print(f"Request error: {e}")
except Exception as e:
    # その他のエラーの処理
    print(f"Unexpected 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
    billing_id = '<Billing ID>'  # ここにBilling IDを設定
    endpoint = "/v1/billings/#{billing_id}"

    uri = URI.parse(BASE_URL + endpoint)

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

    data = {
        bill_type:"01",
        is_uncollectible: false,
        customer_id: "CUST001",
        customer_honorific: "様",
        customer_overwrite: {
            name: "株式会社テスト",
            email: "test@example.com",
            addr_country: "392",
            addr_state: "13",
            addr_city: "新宿区",
            addr_line_1: "1-1-1",
            addr_line_2: "テストビル",
            addr_line_3: "",
            addr_post_code: "1600022"
        },
        issuer_overwrite: {
            addr_state: "13",
            addr_city: "新宿区",
            addr_line_1: "1-1-1",
            addr_line_2: "テストビル",
            addr_line_3: "",
            addr_post_code: "1600022",
            email: "issuer@example.com",
            phone_number: "0312345678"
        },
        invoice: {
            invoice_number: "INV123456",
            bill_mail_send_flag: "0",
            receipt_mail_send_flag: "0",
            underpayment_mail_send_flag: "0",
            lines: [
                {
                    date: "2023/10/01",
                    name: "商品A",
                    unit_price: 1000,
                    quantity: 2,
                    tax_rate: 10
                }
            ]
        },
        pay_types: [
            "Virtualaccount",
            "Card"
        ]
    }

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

    request.body = data.to_json

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

        puts "HTTP Status Code: #{response.code}"

        case response
        when Net::HTTPSuccess
            puts 'Invoice Updated Successfully:'
            begin
                response_data = JSON.parse(response.body)
                puts JSON.pretty_generate(response_data)
            rescue JSON::ParserError
                puts response.body
            end
        else
            puts 'Error Response:'
            begin
                error_data = JSON.parse(response.body)
                puts JSON.pretty_generate(error_data)
            rescue JSON::ParserError
                puts response.body
            end
        end

    rescue StandardError => e
        puts "Request error: #{e.message}"
    end
end

main
```

## パラメータ

| 名前 | 位置 | 必須 | 型 | 説明 |
| --- | --- | --- | --- | --- |
| `Tenant-Shop-Id` | header |  | schema | <span class="smallText color--red-400">※ プラットフォームのメインショップのみ指定可</span> |
| `id` | path | ✓ | string | 請求ID |

## リクエストボディ

Content-Type: `application/json`

| パラメータ | 型 | 必須 | 説明 |
| --- | --- | --- | --- |
| `is_uncollectible` | boolean |  | 回収困難フラグ |
| `bill_type` | bill_type |  |  |
| `customer_id` | Billing_properties-customer_id |  |  |
| `customer_honorific` | customer_honorific |  |  |
| `customer_overwrite` | customer_overwrite |  |  |
| `issuer_overwrite` | issuer_overwrite |  |  |
| `is_tax_included` | is_tax_included |  |  |
| `due_date` | due_date |  |  |
| `memo` | memo |  |  |
| `client_field_1` | Billing_properties-client_field_1 |  |  |
| `client_field_2` | Billing_properties-client_field_2 |  |  |
| `client_field_3` | Billing_properties-client_field_3 |  |  |
| `pay_types` | array<enum(Card | Konbini | Paypay | Virtualaccount | Directdebit | Payeeaccount)> |  | ショップで利用可能な決済種別のリスト |
| `input_type` | input_type |  |  |
| `invoice` | object |  | インボイス情報 |
| `link_type` | object |  | リダイレクト型決済情報 |
| `draft` | object |  | 下書き情報 |

## レスポンス

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

| パラメータ | 型 | 必須 | 説明 |
| --- | --- | --- | --- |
| `id` | string |  | 請求ID |
| `bill_type` | string |  | 請求方式 |
| `status` | string |  | 請求のステータス |
| `customer_id` | string |  | 顧客（請求先）ID |
| `customer_honorific` | string |  | 顧客（請求先）敬称 |
| `customer` | object |  | 顧客（請求先）情報 |
| `customer_overwrite` | object |  | 上書き顧客（請求先）情報 |
| `issuer` | object |  | 発行元事業者情報 |
| `issuer_overwrite` | object |  | 上書き発行元事業者情報 |
| `issue_date` | string |  | 発行年月日 形式： `yyyy/MM/dd` |
| `is_tax_included` | boolean |  | 内税表記有無 |
| `due_date` | string |  | 支払期日 形式： `yyyy/MM/dd` |
| `memo` | string |  | 備考 |
| `client_field_1` | string |  | 加盟店自由項目1 |
| `client_field_2` | string |  | 加盟店自由項目2 |
| `client_field_3` | string |  | 加盟店自由項目3 |
| `is_uncollectible` | boolean |  | 回収不能フラグ |
| `is_paid_externally` | boolean |  | M's PayBridge外支払フラグ |
| `transaction_date` | string |  | 支払完了日 形式： `yyyy/MM/dd` |
| `total_amount` | string |  | 合計金額 |
| `billing_total_amount` | string |  | 合計請求金額 |
| `pay_types` | array<string> |  | 利用可能な決済種別リスト |
| `input_type` | enum(amount) |  | 取引金額の入力方式 |
| `used_pay_type` | string |  | 利用された決済種別 |
| `invoice` | object |  | インボイスに関する情報 |
| `link_type` | object |  | リダイレクト型決済に関する情報 |
| `draft` | object |  | 下書き情報 |
| `billing_file_import_entry_id` | string |  | 請求インポートファイル読み込みエントリーID |
| `trade_client_field_1` | string |  | 決済情報自由項目 1 |
| `trade_client_field_2` | string |  | 決済情報自由項目 2 |
| `trade_client_field_3` | string |  | 決済情報自由項目 3 |
| `created` | string |  | 作成日時 形式： `yyyy/MM/dd HH:mm:ss.SSS` |
| `updated` | string |  | 更新日時 形式： `yyyy/MM/dd HH:mm:ss.SSS` |

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

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

