跳转到主要内容

此软件包提供使用CyberSource安全接受托管结账的实用工具。

项目描述

Django CyberSource Hosted Checkout

此软件包提供使用CyberSource安全接受托管结账的实用工具。

CyberSource安全接受托管结账是一个往返过程:你开始在服务器上启动支付,然后传递给CyberSource。交易结束时,CyberSource将返回你配置的URL的你的服务器。

我们假设您对产品和配置文件有实际了解;您可以在这里阅读CyberSource手册

它所做的繁重工作包括正确创建signed_date_timefields_to_signsignature字段,并自动将它们包含在POST中,以及您需要传递的任何字段。

如果您不想看上面那个糟糕的PDF文件而让眼睛疼痛,这里有一个TL;DR。

创建您的CyberSource配置文件

您需要在CyberSource测试和实时环境中都这样做。从测试开始。过程是相同的。

  • 在此处登录:https://businesscenter.cybersource.com/ebc/login/
  • 工具与设置下,单击配置文件,然后单击创建新配置文件
  • 填写表格并单击保存。然后单击您刚刚创建的配置文件名称以进一步编辑。
  • 将此屏幕上的 配置文件 ID 复制到您的 Django 设置中,作为 CYBERSOURCE_PROFILE_ID。您会注意到有八个部分可以进行修改。这里我只介绍必须覆盖的区域。
    • 支付设置:至少输入一种 卡片类型,并关联至少一种 货币
    • 安全:点击 创建新密钥。将 访问密钥密钥 值分别复制到您的 Django 设置中的 CYBERSOURCE_ACCESS_KEYCYBERSOURCE_SECRET_KEY
    • 客户响应页面:对于 交易响应页面,选择 由您托管,并输入您稍后在 Django 中创建的路由,例如 https://www.mysite.com/orders/payment-response/
  • 完成所有字段后,务必 激活 配置文件!

安装 Django CyberSource Hosted Checkout

首先,运行 pip install django-cybersource-hosted-checkout,并将 'cybersource_hosted_checkout' 添加到您的 INSTALLED_APPS 列表。

如果您打算使用下面的示例来入门,您还需要运行 pip install django-braces

设置

这些设置必须在 Django 的设置中存在。

  • CYBERSOURCE_URL
    • 对于 CyberSource 的测试环境:https://testsecureacceptance.cybersource.com/pay
    • 对于 CyberSource 的生产环境:https://secureacceptance.cybersource.com/pay
  • CYBERSOURCE_PROFILE_ID = '[您的 CyberSource 配置文件 ID]'
  • CYBERSOURCE_ACCESS_KEY = '[您的 CyberSource 访问密钥]'
  • CYBERSOURCE_SECRET_KEY = '[您的 CyberSource 密钥]'

代码和配置

models.py

在这个例子中,我们将向我们的 Django 网站的用户收取 19.95 美元,以购买课程。

首先,在 Django 项目的某个应用程序中创建一个继承自 AbstractCyberSourceTransaction 的模型;抽象模型存储一个唯一标识符、一个交易 UUID、一个在 Django 中创建交易的时间戳以及从 CyberSource 完成交易的时间戳。您可以添加任何您想跟踪和存储的附加字段。在这个例子中,我们添加了 usercourse,以便在支付后完成交易。然后运行 makemigrationsmigrate

from django.db import models
from cybersource_hosted_checkout.models import AbstractCyberSourceTransaction

class CyberSourceTransaction(AbstractCyberSourceTransaction):
    """
    Stores credit card transaction receipts made with CyberSource.
    """
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    course = models.ForeignKey(Course, on_delete=models.PROTECT)

views.py

在这里,我们利用 Django 的 FormView,并在 form_valid() 中调用函数并渲染模板,该模板将自动准备数据用于 CyberSource 并将其 POST 到他们的服务器。fields 字典包含执行交易所需的 CyberSource 特定字段。您可以在手册中查看完整列表;下面的示例是一次性以 19.95 美元购买课程。

import datetime
from uuid import uuid4
from django.conf import settings
from django.contrib import messages
from django.contrib.messages.views import SuccessMessageMixin
from django.views import View
from django.views.generic import FormView
from braces import LoginRequiredMixin, CsrfExemptMixin
from my_app.models import CyberSourceTransaction

class AddCourseView(LoginRequiredMixin, SuccessMessageMixin, FormView):
    template_name = 'my_app/transaction.html'
    form_class = TransactionForm
    success_url = reverse_lazy('home')
    success_message = "Your transaction has been completed."

    def form_valid(self, form, request, **kwargs):
        # Get the proverbial `course` from the database based on something in the form.
        course = Course.objects.get(course_code=form.cleaned_data['course_code'])

        # Create a transaction in the database before we pass to CyberSource;
        # we will update this with a timestamp on return from CyberSource
        transaction_uuid = uuid4().hex
        transaction = CyberSourceTransaction()
        transaction.transaction_uuid = transaction_uuid
        transaction.user = request.user
        transaction.course = course
        transaction.save()

        # Fields to pass to CyberSource - see manual for a full list
        fields = {}
        fields['profile_id'] = settings.CYBERSOURCE_PROFILE_ID
        fields['access_key'] = settings.CYBERSOURCE_ACCESS_KEY
        fields['amount'] = '19.95'
        fields['transaction_uuid'] = transaction_uuid
        fields['bill_to_forename'] = request.user.first_name
        fields['bill_to_surname'] = request.user.last_name
        fields['bill_to_email'] = request.user.email
        fields['locale'] = 'en-us'
        fields['currency'] = 'usd'
        fields['transaction_type'] = 'sale'
        fields['reference_number'] = transaction.id

        context = super().get_context_data(**kwargs)
        context = sign_fields_to_context(fields, context)

        # Render a page which POSTs to CyberSource via JavaScript.
        return render(
            request,
            'cybersource_hosted_checkout/post_to_cybersource.html',
            context=context,
        )

class CyberSourceResponseView(CsrfExemptMixin, View):
    """
    Recevies a POST from CyberSource and redirects to home.
    """

    def post(self, request):
        if request.POST.get('decision').upper() == 'ACCEPT':
            # Success! Add the course by getting the transaction we started.
            # Check both reference number and UUID since we're not requiring
            # a login.
            transaction = CyberSourceTransaction.objects.get(
                id=request.POST.get('req_reference_number'),
                uuid=request.POST.get('req_transaction_uuid'),
            )
            transaction.return_from_cybersource = datetime.datetime.now()
            # Here is where you'll put your code in place of this dummy function.
            add_course_for_user(transaction.course, transaction.user, request)
            messages.success(
                request,
                'Your payment was successful and the course has been added. Happy trading!',
            )
            transaction.save()
        else:
            # Uh oh, unsuccessful payment.
            messages.error(
                request,
                'Sorry, your payment was not successful.',
            )

        return redirect(reverse_lazy('home'))

AddCourseView 类将显示您的购买表单,当它有效时,将必要的字段传递给 CyberSource 以显示他们的结账页面。

CyberSourceResponseView 是在 CyberSource 成功结账后运行的视图的类。在成功完成购买后,用户将被重定向回您在 CyberSource 配置文件中指定的路由(例如,https://www.mysite.com/orders/payment-response/),我们通过更新 return_from_cybersource 的时间戳来标记交易已完成。

urls.py

我们需要将我们的视图插入与 CyberSource 匹配的路由。

from django.urls import path
from myapp.views import MyHomeView, AddCourseView, CyberSourceResponseView

urlpatterns = [
    path('', MyHomeView.as_view(), name='home'),
    path('orders/buy-course/', AddCourseView.as_view(), name='add-course'),
    path('orders/payment-response/', CyberSourceResponseView.as_view(), name='add-course-cybersource-response'),
]

运行测试

git clone git@github.com:wharton/django-cybersource-hosted-checkout.git
mkvirtualenv test-cybersource
cd django-cybersource-hosted-checkout/testproject
pip install -r requirements.txt
coverage run --source='..' manage.py test cybersource_hosted_checkout
coverage report

发布说明

0.0.1 - 0.0.6

初始发布,测试和文档改进。

贡献者

项目详情


下载文件

下载适合您平台文件的文件。如果您不确定选择哪个,请了解更多关于 安装包 的信息。

源分布

django-cybersource-hosted-checkout-0.0.6.tar.gz (6.9 kB 查看哈希值)

上传时间 源代码

构建分发版

由以下机构支持