LINE株式会社は、2023年10月1日にLINEヤフー株式会社になりました。LINEヤフー株式会社の新しいブログはこちらです。 LINEヤフー Tech Blog

Blog


Python版LINE Pay API SDK(v3対応)がリリースされたので使い方をご紹介します。

LINE Pay SDK Python

こんにちは。LINEでテクニカルエバンジェリストとしてLINEのAPIを利用したデベロッパーのビジネスの成功をお手伝いさせていただいている立花です。

先日リリースされたLINE Pay API v3のPython版SDKをAPI Expert加川澄廣さんが公開して下さいましたので、使い方をご紹介いたします。

v3における変更点

v3における変更点は以下です。

  • 認証の仕組みの変更
  • White IP登録が不要に
  • 決済対象商品がよりフレキシブルに設定可能に
  • Checkout(決済完了時に配送先も入力可能に)

詳しくは以下をご参照下さい。

Python版SDKのご紹介

リポジトリ

リポジトリは以下となります。

https://github.com/sumihiro3/line-pay-sdk-python

動作環境

Python >= 3.6

インストール

PyPIに登録済みのため、pipでインストール可能です。

$ pip install line-pay

各APIの使い方

サンプルプロジェクト

LINE Pay SDK Python

どなたでもお手元で動作を確認できるよう、kintoneと連携したLINE Pay APIの機能を体験できるアプリケーションを作成し、githubに公開してあります。使い方はREADMEに記載してありますのでよろしければダウンロードしてご利用下さい。

https://github.com/stachibana/line-pay-v3-python-sdk-sample

なおLINE Pay APIは現在は個人事業主の方でも審査に通過すれば本番運用も可能です。詳しくは以下の記事をご参照下さい。

LINE Pay API を使って個人開発のBot に決済機能をつける

Request API

決済のリクエストを行います。options.payment.captureの値にFalseを指定することでオーソリと売上確定を分離させることが可能です。分離した場合は売上をCapture APIを利用して確定させる必要があります。

order_id = str(uuid.uuid4())
amount = 1
currency = "JPY"
request_options = {
    "amount": amount,
    "currency": currency,
    "orderId": order_id,
    "packages": [
        {
            "id": "package-999",
            "amount": 1,
            "name": "Sample package",
            "products": [
                    {
                        "id": "product-001",
                        "name": "Sample product",
                        "imageUrl": "https://placehold.jp/99ccff/003366/150x150.png?text=Sample%20product",
                                    "quantity": 1,
                                    "price": 1
                    }
            ]
        }
    ],
    "options": {
        "payment": {
            "capture": True|False
        }
    },
    "redirectUrls": {
        "confirmUrl": request.host_url.replace('http', 'https') + "confirm",
        "cancelUrl": request.host_url.replace('http', 'https') + "cancel"
    }
}
response = api.request(request_options)

Confirm API

Request APIが発行した決済用リンクへ遷移したユーザーが承認を行った後、加盟店側で決済を完了させるためのAPIです。

transaction_id = int(request.args.get('transactionId'))

response = api.confirm(
    transaction_id,
    amount,
    currency
)

Capture API

オーソリ状態の決済データを確定させるAPIです。

response = api.capture(transaction_id, amount, currency)

Void API

オーソリ状態の決済データを無効化させるAPIです。

response = api.void(transaction_id)

Refund API

確定した売上を返金するAPIです。返金は全額、もしくは金額での指定が可能です。

# 全額
response = api.refund(transaction_id)
# 金額指定
response = api.refund(transaction_id, 50.0)

Payment Details API

取引履歴を紹介できるAPIです。

details = api.payment_details(transaction_id)

Pay Preapproved API

自動決済(予め取得したユーザーの同意を前提に、次回以降ユーザーの同意無しで決済できる機能)を行うAPIです。自動決済に必要なRegKeyははRequest API実行時のパラメータoptions.payment.payTypePREAPPROVEDを指定することで取得可能です。

RegKey取得

# Request
order_id = str(uuid.uuid4())
amount = 1
currency = "JPY"
request_options = {
    "amount": amount,
    "currency": currency,
    "orderId": order_id,
    "packages": [
        {
            "id": "package-999",
            "amount": 1,
            "name": "Sample package",
            "products": [
                    {
                        "id": "product-001",
                        "name": "Sample product",
                        "imageUrl": "https://placehold.jp/99ccff/003366/150x150.png?text=Sample%20product",
                                    "quantity": 1,
                                    "price": 1
                    }
            ]
        }
    ],
    "options": {
        "payment": {
            "capture": True,
            "payType": "PREAPPROVED"
        }
    },
    "redirectUrls": {
        "confirmUrl": request.host_url.replace('http', 'https') + "confirm",
        "cancelUrl": request.host_url.replace('http', 'https') + "cancel"
    }
}
response = api.request(request_options)
# Confirm
response = api.confirm(
    transaction_id,
    amount,
    currency
)
if 'regKey' in response['info']:
    reg_key = response['info']['regKey']
# Pay preapproved
order_id = str(uuid.uuid4())
amount = 1.0
currency = "JPY"
product_name = "定期購入アイテム"

response = api.pay_preapproved(reg_key, product_name, amount, currency, order_id, True)

Checkout

ユーザーが希望する発送先住所を元に発送方法を提案し、送料と同時に決済を行うことができるAPIです。options.shippingの値の指定と、住所を受け取り発送方法を返却するInquiry ShippingMethods APIの実装が必要です。

※ 本APIはSandbox環境では利用できません。

# Request
order_id = str(uuid.uuid4())
amount = 1
currency = "JPY"
request_options = {
    "amount": amount,
    "currency": currency,
    "orderId": order_id,
    "packages": [
        {
            "id": "package-999",
            "amount": 1,
            "name": "Sample package",
            "products": [
                    {
                        "id": "product-001",
                        "name": "Sample product",
                        "imageUrl": "https://placehold.jp/99ccff/003366/150x150.png?text=Sample%20product",
                                    "quantity": 1,
                                    "price": 1
                    }
            ]
        }
    ],
    "options": {
        "payment": {
            "capture": True
        },
        "shipping": {
            "type": "SHIPPING",
            "feeInquiryUrl": request.host_url.replace('http', 'https') + "v1/shippings/methods/get/"
        }
    },
    "redirectUrls": {
        "confirmUrl": request.host_url.replace('http', 'https') + "confirm",
        "cancelUrl": request.host_url.replace('http', 'https') + "cancel"
    }
}
response = api.request(request_options)
# Inquiry ShippingMethods API
@app.route('/v1/shippings/methods/get/', methods=["POST"])
def inquiryShippingMethods():
    result = {
        "returnCode": "0000",
        "returnMessage": "Example",
        "info": {
            "shippingMethods": [
                {
                    "id": "hoge",
                    "name": "hogehoge express",
                    "amount": "1000",
                    "toDeliveryYmd": datetime.datetime.now().strftime("%Y%m%d")
                }
            ]
        }
    }
    return jsonify(result)

まとめ

SDKのおかげでシンプルに記述が可能になります。加川さん、ありがとうございます。また、他にもSDK作られている方がいらっしゃいましたら、是非教えて下さいね。