Djangoroidの奮闘記

python,django,angularJS1~三十路過ぎたプログラマーの奮闘記

Django e-commerce part72 Braintree & Customer ID

Braintree の設定方法

Braintree sandboxに登録

2016年10月現在では、braintreeは日本に対応していないため、とりあえずsandboxで試してみる。

Braintreeをinstall

pip install braintree
pip freeze > requirements.txt

settings/local.py にBratintreeのアカウントなどを設定

BRAINTREE_PUBLIC = "*****************"
BRAINTREE_PRIVATE = "*****************"
BRAINTREE_MERCHANT = "*****************"
BRAINTREE_ENVIROMENT = "Sandbox"

ポイント

  • IDは、"" 文字列として数字を渡す。
  • また、Braintreeの環境は、Sandboxとして設定する。
  • 公式ドキュメントは、この辺りを参照

Set Up Your Server | Python - Braintree Developer Documentation

orders/models.py にbraintreeのフィールドをセットする。

class UserCheckout(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, blank=True) #optional
    email = models.EmailField(unique=True) #--> required
    braintree_id = models.CharField(max_length=120, null=True, blank=True)
  • braintree_id をcharfieldで設定する。

post_save signalsに対応する、def update_braintree_idを作成する。

def update_braintree_id(sender, instance, *args, **kwargs):
    if not instance.braintree_id:
        pass

post_save.connect(update_braintree_id, sender=UserCheckout)
  • UserCheckoutがsaveされた後に、update_braintree_idをアップデートする。

orders/models.py に、braintreeをimportする

Setting -> Users and Roles -> User List -> APIKeys -> PrivateKeyのViewをクリック -> 対応言語をPython に変更 -> braintreeの設定に必要なコードが表示されるので、それをコピペ。import braintreeを忘れない。

import braintree

    braintree.Configuration.configure(
        braintree.Environment.Sandbox,
        '***********',
        '************',
        '***********************************'
    )

# 以下は、settingsからimportするパターン。本番では以下を利用する。
    # braintree.Configuration.configure(braintree.Environment.Sandbox,
    #     merchant_id=settings.BRAINTREE_MERCHANT,
    #     public_key=settings.BRAINTREE_PUBLIC,
    #     private_key=settings.BRAINTREE_PRIVATE)

BraintreeのCustomerを作成する。

Create Customerの公式ドキュメントはこちら。 Customer.create() | Python - Braintree Developer Documentation

def update_braintree_id(sender, instance, *args, **kwargs):
    if not instance.braintree_id:
     result = braintree.Customer.create({
    "first_name": "Jen",
    "last_name": "Smith",
    "company": "Braintree",
    "email": "jen@example.com",
    "phone": "312.555.1234",
    "fax": "614.555.5678",
    "website": "www.example.com"
})
pass

とりあえず、そのままコピペしてみる。それを以下のように修正する。

def update_braintree_id(sender, instance, *args, **kwargs):
    if not instance.braintree_id:
        result = braintree.Customer.create({
            "email": instance.email,
        })
        if result.is_success:
            print (result)

ポイント

  • braintreeのCustomer.createメソッドで、UserCheckoutのemailを利用して、それをkeyvalueにして、braintreeのCustomerをcreateする。
  • テストで、resultの表示も行なっている。

adminサイトで、UserCheckoutを保存して、post_saveのあとの、updata_braintree_idが機能しているか確認する。

adminサイトから、手動でUserCheckoutを保存してみる。successすると、以下のようにターミナルに表示される。

<SuccessfulResult {customer: <Customer {first_name: None, last_name: None, id: '*******'} at *************>} at *********>

orders/models.py に追記する。

def update_braintree_id(sender, instance, *args, **kwargs):
    if not instance.braintree_id:
        result = braintree.Customer.create({
            "email": instance.email,
        })
        if result.is_success:
            instance.braintree_id = result.customer.id
            instance.save()

post_save.connect(update_braintree_id, sender=UserCheckout)