# 決済URL 作成

`POST /v1/sessions`

- operationId: `createPaymentSession`
- tags: リダイレクト型決済

M's PayBridgeが提供するリダイレクト型決済ページを発行し、その決済ページへのURLをレスポンスします。


## コードサンプル

### cURL

```bash
curl \
    -X POST \
    -H "Authorization: Bearer <Secret API Key>" \
    -H "Content-Type: application/json" \
    -d '{
    "success_url": "https://your-service.example.com/success",
    "cancel_url": "https://your-service.example.com/cancel",
    "transaction": {
        "pay_type": ["Card", "Konbini", "Paypay"],
        "amount": "1000"
    },
    "card": {
        "job_code": "CAPTURE",
        "tds_type": "2",
        "tds2_type": "2"
    },
    "konbini": {
        "payment_term_day": 2,
        "konbini_reception_mail_send_flag": "0"
    },
    "paypay": {
        "job_code": "CAPTURE"
    }
}' \
"https://api.test.fincode.jp/v1/sessions"
```

### Node.js

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

const API_KEY = "<Secret API Key>";

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

    try {
        // リクエストの送信
        const paymentSession = await fincode.paymentSessions.create({
            success_url: "https://your-service.example.com/success",
            cancel_url: "https://your-service.example.com/cancel",
            shop_service_name: "My Store",
            transaction: {
                pay_type: ["Card"],
                amount: "1000",
            },
            card: {
                job_code: "CAPTURE",
                tds_type: "2",
                tds2_type: "2",
                td_tenant_name: "My Store",
            },
        });
    } catch (e) {
        // エラーの処理
    }
})();
```

### Go

```go
package main

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

func main() {

	apiKey := "<Secret API Key>"

	body := CreatingPaymentSessionRequest{
		SuccessURL: stringPointer("https://your-service.example.com/success"),
		CancelURL:  stringPointer("https://your-service.example.com/cancel"),
		Transaction: Transaction{
			PayType: []string{"Card", "Konbini", "Paypay"},
			Amount:  "1234",
		},
		Card: &CardPaymentSession{
			JobCode:  "CAPTURE",
			TdsType:  stringPointer("2"),
			Tds2Type: stringPointer("2"),
		},
		Konbini: &KonbiniPaymentSession{
			PaymentTermDay:               2,
			KonbiniReceptionMailSendFlag: "0",
		},
		PayPay: &PayPayPaymentSession{
			JobCode: "CAPTURE",
		},
	}

	marshalledBody, _ := json.Marshal(body)

	// リクエストの作成
	req, _ := http.NewRequest(
		"POST",
		"https://api.test.fincode.jp/v1/sessions",
		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 CreatingPaymentSessionRequest struct {
	SuccessURL         *string                `json:"success_url,omitempty"`
	CancelURL          *string                `json:"cancel_url,omitempty"`
	Expire             *string                `json:"expire,omitempty"`
	ShopServiceName    *string                `json:"shop_service_name,omitempty"`
	ReceiverMail       *string                `json:"receiver_mail,omitempty"`
	MailCustomerName   *string                `json:"mail_customer_name,omitempty"`
	GuildeMailSendFlag *string                `json:"guilde_mail_send_flag,omitempty"`
	ThanksMailSendFlag *string                `json:"thanks_mail_send_flag,omitempty"`
	ShopMailTemplateID *string                `json:"shop_mail_template_id,omitempty"`
	Transaction        Transaction            `json:"transaction"`
	Card               *CardPaymentSession    `json:"card,omitempty"`
	Konbini            *KonbiniPaymentSession `json:"konbini,omitempty"`
	PayPay             *PayPayPaymentSession  `json:"paypay,omitempty"`
}
type Transaction struct {
	PayType      []string `json:"pay_type"`
	OrderID      *string  `json:"order_id,omitempty"`
	Amount       string   `json:"amount"`
	Tax          *string  `json:"tax,omitempty"`
	ClientField1 *string  `json:"client_field_1,omitempty"`
	ClientField2 *string  `json:"client_field_2,omitempty"`
	ClientField3 *string  `json:"client_field_3,omitempty"`
}

type CardPaymentSession struct {
	JobCode      string  `json:"job_code,omitempty"`
	TdsType      *string `json:"tds_type,omitempty"`
	Tds2Type     *string `json:"tds2_type,omitempty"`
	TdTenantName *string `json:"td_tenant_name,omitempty"`
}

type KonbiniPaymentSession struct {
	PaymentTermDay               int    `json:"payment_term_day,omitempty"`
	KonbiniReceptionMailSendFlag string `json:"konbini_reception_mail_send_flag,omitempty"`
}

type PayPayPaymentSession struct {
	JobCode          string  `json:"job_code,omitempty"`
	OrderDescrpition *string `json:"order_description,omitempty"`
}

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

### PHP

```php
<?php

$apiKey = '<Secret API Key>';

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

$data = json_encode([
    "success_url" => "https://your-service.example.com/success",
    "cancel_url" => "https://your-service.example.com/cancel",
    "transaction" => [
        "pay_type" => ["Card", "Konbini", "Paypay"],
        "amount" => "1000",
    ],
    "card" => [
        "job_code" => "CAPTURE",
        "tds_type" => "2",
        "tds2_type" => "2",
    ],
    "konbini" => [
        "payment_term_day" => 2,
        "konbini_reception_mail_send_flag" => "0"
    ],
    "paypay" => [
        "job_code" => "CAPTURE",
    ]
]);

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

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

data = {
    "success_url": "https://your-service.example.com/success",
    "cancel_url": "https://your-service.example.com/cancel",
    "transaction": {
        "pay_type": ["Card", "Konbini", "Paypay"],
        "amount": "1000"
    },
    "card": {
        "job_code": "CAPTURE",
        "tds_type": "2",
        "tds2_type": "2"
    },
    "konbini": {
        "payment_term_day": 3,
        "konbini_reception_mail_send_flag": "0"
    },
    "paypay": {
        "job_code": "CAPTURE"
    }
}

# 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/sessions"
    uri = URI.parse(BASE_URL + endpoint)

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

    data = {
        success_url: "https://your-service.example.com/success",
        cancel_url: "https://your-service.example.com/cancel",
        transaction: {
            pay_type: ["Card", "Konbini", "Paypay"],
            amount: "1000"
        },
        card: {
            job_code: "CAPTURE",
            tds_type: "2",
            tds2_type: "2"
        },
        konbini: {
            payment_term_day: 2,
            konbini_reception_mail_send_flag: "0"
        },
        paypay: {
            job_code: "CAPTURE"
        }
    }

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

## パラメータ

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

## リクエストボディ

Content-Type: `application/json`

| パラメータ | 型 | 必須 | 説明 |
| --- | --- | --- | --- |
| `transaction` | object | ✓ | 決済共通項目 |
| `card` | object |  | カード決済パラメータ |
| `konbini` | object |  | コンビニ決済パラメータ |
| `paypay` | object |  | PayPayパラメータ |
| `virtualaccount` | object |  | 銀行振込（バーチャル口座）パラメータ |
| `success_url` | success_url |  |  |
| `cancel_url` | cancel_url |  |  |
| `expire` | PaymentSession_properties-expire |  | リダイレクト型決済URL 有効期限 |
| `shop_service_name` | shop_service_name |  |  |
| `guide_mail_send_flag` | guide_mail_send_flag |  | 決済メール 送信フラグ |
| `receiver_mail` | receiver_mail |  |  |
| `mail_customer_name` | mail_customer_name |  |  |
| `thanks_mail_send_flag` | thanks_mail_send_flag |  |  |
| `shop_mail_template_id` | shop_mail_template_id |  |  |

## レスポンス

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

| パラメータ | 型 | 必須 | 説明 |
| --- | --- | --- | --- |
| `id` | string |  | リダイレクト型決済URL ID |
| `link_url` | string |  | リダイレクト型決済URL |
| `success_url` | string |  | 成功時リダイレクトURL |
| `cancel_url` | string |  | キャンセル時リダイレクトURL |
| `status` | PaymentSessionStatus |  |  |
| `expire` | string |  | リダイレクト型決済URL 有効期限 |
| `shop_service_name` | string |  | ショップ／サービス名 |
| `guide_mail_send_flag` | enum(0 | 1) |  | 決済メール 送信フラグ |
| `receiver_mail` | string |  | 決済メール 送信先メールアドレス |
| `mail_customer_name` | string |  | 購入メール 購入者の名前 |
| `thanks_mail_send_flag` | enum(0 | 1) |  | 完了メール 送信フラグ |
| `shop_mail_template_id` | string |  | メールテンプレートID |
| `transaction` | object |  | 決済共通項目 |
| `card` | PaymentSession.Card |  | カード決済に関する情報 |
| `konbini` | PaymentSession.Konbini |  | コンビニ決済に関する情報 |
| `paypay` | PaymentSession.PayPay |  | PayPayに関する情報 |
| `virtualaccount` | PaymentSession.VirtualAccount |  | 銀行振込（バーチャル口座）に関する情報 |
| `bill_id` | string |  | 請求ID |
| `created` | created |  |  |
| `updated` | updated |  |  |

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

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

