此包提供了使用CyberSource安全接受托管签出的实用程序。

django-cybersource-hosted-checkout的Python项目详细描述


Django CyberSource托管结账

此包提供了使用CyberSource安全接受托管签出的实用程序。

CyberSource安全验收托管签出是一个往返过程:您在服务器上开始付款,然后转到CyberSource。在事务结束时,CyberSource将返回到您配置的URL处的服务器。

我们假设您对产品和配置文件有工作知识;您可以read the CyberSource manual here

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

如果你不想让你的眼睛流血与可怕的pdf上面,这里有一个tl;博士。

创建您的网络源配置文件

在网络源测试和实时环境中都必须这样做。从测试开始。过程是一样的。

  • 在这里登录:https://businesscenter.cybersource.com/ebc/login/
  • Tools & Settings下,单击Profiles,然后单击Create New Profile
  • 填写表单并单击Save。然后单击刚才创建的配置文件名以进一步编辑它。
  • 将此屏幕上的Profile ID复制到django设置中作为CYBERSOURCE_PROFILE_ID。您将注意到有八个部分可以修改。我只负责这里的规定区域。
    • 支付设置:至少输入一个Card Type,其中至少有一个Currency与之关联。
    • 安全:单击Create New Key。将Access KeySecret Key值分别复制为CYBERSOURCE_ACCESS_KEYCYBERSOURCE_SECRET_KEY的django设置。
    • 客户响应页面:对于Transaction Response Page,选择Hosted by you,然后输入稍后将在django中创建的路由,例如https://www.mysite.com/orders/payment-response/
  • 完成所有字段后,请确保Activate配置文件!

安装Django CyberSource托管签出

首先,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='[您的网络源配置文件ID]
  • CYBERSOURCE_ACCESS_KEY='[您的网络源访问密钥]'
  • CYBERSOURCE_SECRET_KEY='[您的网络源密钥]'

代码和配置

型号.py

在本例中,我们将向Django网站的用户收取19.95美元的课程费用。

首先,在django项目中的应用程序中创建一个继承自AbstractCyberSourceTransaction的模型;抽象模型存储唯一标识符、事务uuid、在django中创建事务的时间戳以及从cybersource完成事务的另一个时间戳。可以添加要跟踪和存储的任何其他字段。在这个例子中,我们添加了usercourse,这样我们就可以在付款后完成交易。然后是makemigrationsmigrate

fromdjango.dbimportmodelsfromcybersource_hosted_checkout.modelsimportAbstractCyberSourceTransactionclassCyberSourceTransaction(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)

视图.py

在这里,我们利用django FormView,在form_valid()中,我们调用函数并呈现模板,模板将自动为CyberSource准备数据并将其发布到服务器。fields字典包含执行事务所需的特定于网络源的字段。您可以在手册中看到完整的列表;下面的示例是一次性购买19.95美元的课程。

importdatetimefromuuidimportuuid4fromdjango.confimportsettingsfromdjango.contribimportmessagesfromdjango.contrib.messages.viewsimportSuccessMessageMixinfromdjango.viewsimportViewfromdjango.views.genericimportFormViewfrombracesimportLoginRequiredMixin,CsrfExemptMixinfrommy_app.modelsimportCyberSourceTransactionclassAddCourseView(LoginRequiredMixin,SuccessMessageMixin,FormView):template_name='my_app/transaction.html'form_class=TransactionFormsuccess_url=reverse_lazy('home')success_message="Your transaction has been completed."defform_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 CyberSourcetransaction_uuid=uuid4().hextransaction=CyberSourceTransaction()transaction.transaction_uuid=transaction_uuidtransaction.user=request.usertransaction.course=coursetransaction.save()# Fields to pass to CyberSource - see manual for a full listfields={}fields['profile_id']=settings.CYBERSOURCE_PROFILE_IDfields['access_key']=settings.CYBERSOURCE_ACCESS_KEYfields['amount']='19.95'fields['transaction_uuid']=transaction_uuidfields['bill_to_forename']=request.user.first_namefields['bill_to_surname']=request.user.last_namefields['bill_to_email']=request.user.emailfields['locale']='en-us'fields['currency']='usd'fields['transaction_type']='sale'fields['reference_number']=transaction.idcontext=super().get_context_data(**kwargs)context=sign_fields_to_context(fields,context)# Render a page which POSTs to CyberSource via JavaScript.returnrender(request,'cybersource_hosted_checkout/post_to_cybersource.html',context=context,)classCyberSourceResponseView(CsrfExemptMixin,View):"""    Recevies a POST from CyberSource and redirects to home.    """defpost(self,request):ifrequest.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.',)returnredirect(reverse_lazy('home'))

AddCourseView类将显示您的购买表单,当表单有效时,将必要的字段传递给cybersource以显示其签出页面。

CyberSourceResponseView是从CyberSource成功签出后运行的视图的类。成功完成购买后,用户将被引导回您在CyberSource配置文件中放置的路由(在示例中,https://www.mysite.com/orders/payment-response/),在这里我们将交易标记为通过更新时间戳return_from_cybersource来完成,以标记事务已完成。

url.py

我们需要将我们的观点插入到与网络资源匹配的路径中。

fromdjango.urlsimportpathfrommyapp.viewsimportMyHomeView,AddCourseView,CyberSourceResponseViewurlpatterns=[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

初始版本、测试和文档改进。

贡献者

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
java为扫描器的输入生成字符序列   hibernate中的java实体合并   如何使变量在Java文件中成为全局变量   java JVM崩溃“异常访问冲突”   向MediaMetadataRetriever中的setDataSource()发送Uri时发生java IllegalArgumentException   java没有节约协议?   用户界面java gui帮助actionlistener   java索引越界异常,即使大小小于索引?   在C++中使用java的困惑   在普通java编码中插入图像   JDBC上的java缓存数据   在Java中,在字符串的特定位置替换子字符串   java在运行elasticsearch集群时遇到Perm Gen空间问题   java Soap故障跟踪   java拆分器。固定长度(int)。拆分(字符串)   java获取jar内部包的路径