An Unofficial Alipay API for Python

Related tags

E-commerce alipay
Overview

An Unofficial Alipay API for Python

Overview

An Unofficial Alipay API for Python, It Contain these API:

  • Generate direct payment url
  • Generate partner trade payment url
  • Generate standard mixed payment url
  • Generate batch trans pay url
  • Generate send goods confirm url
  • Generate forex trade url
  • Generate QR code url
  • Verify notify
  • Single Trade Query
  • Generate Refund With Pwd URL

official document: https://b.alipay.com/order/techService.htm

Install

pip install alipay

Usage

Initialization

>>> from alipay import Alipay
>>> alipay = Alipay(pid='your_alipay_pid', key='your_alipay_key', seller_email='your_seller_mail')

Or you can use seller_id instead of seller_email:

>>> alipay = Alipay(pid='your_alipay_pid', key='your_alipay_key', seller_id='your_seller_id')

Generate direct payment url

生成即时到账支付链接

Introduction: https://b.alipay.com/order/productDetail.htm?productId=2012111200373124

>>> alipay.create_direct_pay_by_user_url(out_trade_no='your_order_id', subject='your_order_subject', total_fee='100.0', return_url='your_order
_return_url', notify_url='your_order_notify_url')
'https://mapi.alipay.com/gateway.do?seller_email=.....'

Generate partner trade payment url

生成担保交易支付链接

Introduction: https://b.alipay.com/order/productDetail.htm?productId=2012111200373121

>>> params = {
... 'out_trade_no': 'your_order_id',
... 'subject': 'your_order_subject',
... 'logistics_type': 'DIRECT',
... 'logistics_fee': '0',
... 'logistics_payment': 'SELLER_PAY',
... 'price': '10.00',
... 'quantity': '12',
... 'return_url': 'your_order_return_url',
... 'notify_url': 'your_order_notify_url'
... }
>>> alipay.create_partner_trade_by_buyer_url(**params)
'https://mapi.alipay.com/gateway.do?seller_email=.....'

Generate standard mixed payment url

生成标准双接口支付链接

Introduction: https://b.alipay.com/order/productDetail.htm?productId=2012111300373136

>>> alipay.trade_create_by_buyer_url(**params)
'https://mapi.alipay.com/gateway.do?seller_email=.....'

Generate batch trans pay url

生成批量付款链接

Introduction: https://b.alipay.com/order/productDetail.htm?productId=2012111200373121

>>> params = {
... 'batch_list': (), #批量付款用户列表
... 'account_name': 'seller_account_name', #卖家支付宝名称
... 'batch_no': 'batch_id', #转账流水号,须唯一
... 'notify_url': 'your_batch_notify_url' #异步通知地址
... }
>>> alipay.create_batch_trans_notify_url(**params)
'https://mapi.alipay.com/gateway.do?seller_email=xxx&detail_data=....'

Note: batch_list 为批量付款用户列表,具体格式如下例子:(如涉及中文请使用unicode字符)

>>> batch_list = ({'account': '[email protected]', #支付宝账号
...                'name': u'测试', #支付宝用户姓名
...                'fee': '100', #转账金额
...                'note': 'test'},
...               {'account': '[email protected]', #支付宝账号
...                'name': u'测试', #支付宝用户姓名
...                'fee': '100', #转账金额
...                'note': 'test'}) #转账原因

Generate send goods confirm url

生成确认发货链接

Introduction: https://cshall.alipay.com/support/help_detail.htm?help_id=491097

>>> params = {
... 'trade_no': 'your_alipay_trade_id',
... 'logistics_name': 'your_logicstic_name',
... 'transport_type': 'EXPRESS',
... 'invocie_no': 'your_invocie_no'
... }
>>> alipay.send_goods_confirm_by_platform(**params)
'https://mapi.alipay.com/gateway.do?sign=.....&trade_no=...'

Generate forex trade url

  • Create website payment for foreigners (With QR code)
  • Create mobile payment for foreigners

Introduction: http://global.alipay.com/ospay/home.htm

>>> params = {
... 'out_trade_no': 'your_order_id',
... 'subject': 'your_order_subject',
... 'logistics_type': 'DIRECT',
... 'logistics_fee': '0',
... 'logistics_payment': 'SELLER_PAY',
... 'price': '10.00',
... 'quantity': '12',
... 'return_url': 'your_order_return_url',
... 'notify_url': 'your_order_notify_url'
... }
>>> # Create website payment for foreigners
>>> alipay.create_forex_trade_url(**params)
'https://mapi.alipay.com/gateway.do?service=create_forex_trade......'
>>> # Create mobile payment for foreigners
>>> alipay.create_forex_trade_wap_url(**params)
'https://mapi.alipay.com/gateway.do?service=create_forex_trade_wap......'

Generate QR code url

生成创建 QR 码链接

Introduction: https://b.alipay.com/order/productDetail.htm?productId=2012120700377303

>>> alipay.add_alipay_qrcode_url(**params)
'https://mapi.alipay.com/gateway.do?seller_id=.......'

Note: 如果你的 biz_data 中有 Unicode 字符,在 dumps 的时候需要把 ensure_ascii 设置为 False,即 json.dumps(d, ensure_ascii=False) 否则会遇到错误

Verify notify

verify notify from alipay server, example in Pyramid Application

def alipy_notify(request):
    alipay = request.registry['alipay']
    if alipay.verify_notify(**request.params):
        # this is a valid notify, code business logic here
    else:
        # this is a invalid notify

Single Trade Query

单笔交易查询

文档:http://wenku.baidu.com/link?url=WLjyz-H6AlfDLIU7kR4LcVNQgxSTMxX61fW0tDCE8yZbqXflCd0CVFsZaIKbRFDvVLaFlq0Q3wcJ935A7Kw-mRSs0iA4wQu8cLaCe5B8FIq

import re
xml = alipay.single_trade_query(out_trade_no="10000005")
res = re.findall('<trade_status>(\S+)</trade_status>', xml) # use RE to find trade_status, xml parsing is more useful, in fact.
status = None if not res else res[0]
print status # will print out TRADE_SUCCESS when trade is success

Generate Refund With Pwd URL

生成即时到账有密退款链接

Introduction: https://doc.open.alipay.com/docs/doc.htm?spm=a219a.7629140.0.0.XRddqH&treeId=62&articleId=104744&docType=1

>>> params = {
... 'batch_list': (), #批量退款数据集
... 'batch_no': 'batch_id', #退款批次号,须唯一
... 'notify_url': 'your_batch_notify_url' #异步通知地址
... }
>>> alipay.refund_fastpay_by_platform_pwd(**params)
'https://mapi.alipay.com/gateway.do?seller_email=xxx&detail_data=....'

Note: batch_list 为批量退款数据集,具体格式如下例子:(如涉及中文请使用unicode字符)

>>> batch_list = ({'trade_no': 'xxxxxxxx', #原付款支付宝交易号
...                'fee': '100', #退款总金额
...                'note': 'test'}, #退款原因
...               {'trade_no': 'xxxxxxxx', #原付款支付宝交易号
...                'fee': '100', #退款总金额
...                'note': 'test'}) #退款原因

Example in Pyramid Application

Include alipay either by setting your includes in your .ini, or by calling config.include('alipay').

pyramid.includes = alipay

now in your View

def some_view(request):
    alipay = request.registry['alipay']
    url = alipay.create_direct_pay_by_user_url(...)

Reference

Comments
  • django 的notify_url应该这样写吧?

    django 的notify_url应该这样写吧?

    def alipy_notify(request):
        if alipay.verify_notify(**request.POST):
            # this is a valid notify, code business logic here
        else:
            # this is a invalid notify
    
    opened by pc10201 3
  • 您的readme文档,关于wap支付这部分代码写的不对的吧?

    您的readme文档,关于wap支付这部分代码写的不对的吧?

    alipay_wap = Alipay(pid='your_alipay_pid', key='your_alipay_key', seller_id='your_seller_id')

    是否应该为

    alipay_wap = WapAlipay(pid='your_alipay_pid', key='your_alipay_key', seller_id='your_seller_id')

    opened by benliu723 2
  • 通过pip安装0.2.4错误

    通过pip安装0.2.4错误

    sudo pip install alipay==0.2.4
    Downloading/unpacking alipay==0.2.4
      Downloading alipay-0.2.4.tar.gz
      Running setup.py (path:/tmp/pip_build_root/alipay/setup.py) egg_info for package alipay
        Traceback (most recent call last):
          File "<string>", line 17, in <module>
          File "/tmp/pip_build_root/alipay/setup.py", line 7, in <module>
            CHANGES = open(os.path.join(here, 'CHANGES.rst')).read()
        IOError: [Errno 2] No such file or directory: '/tmp/pip_build_root/alipay/CHANGES.rst'
        Complete output from command python setup.py egg_info:
        Traceback (most recent call last):
    
      File "<string>", line 17, in <module>
    
      File "/tmp/pip_build_root/alipay/setup.py", line 7, in <module>
    
        CHANGES = open(os.path.join(here, 'CHANGES.rst')).read()
    
    IOError: [Errno 2] No such file or directory: '/tmp/pip_build_root/alipay/CHANGES.rst'
    
    ----------------------------------------
    Cleaning up...
    

    对pip而言仅仅更新版本号不行吗?

    opened by zxkane 2
  • verify_notify验证失败

    verify_notify验证失败

    alipay.verify_notify(**request.args) failed

    对比过示例的pyramid的 request.params

    pyramid的request.params是 NestedMultiDict([(u'a', u'111'), (u'b', u'cccc')])

    flask的 MultiDict([('a', u'111'), ('b', u'cccc')])

    看起来区别好像是 key 一个为 unicode,另一个不是 values 两者都是unicode

    您上次让我检查 values 是不是utf-8 编码,那示例应该是能够成功的吧,示例的pyramid也是unicode的

    opened by JoshYuJump 1
  • Seller id support

    Seller id support

    1. Add support to use seller_id instead of seller_email (when initialization)
    2. Polish some style problems (whitespace, indent, etc.)
    3. Update README and unit tests correspondingly.
    opened by Hexcles 1
  • 支付宝异步回调收不到信息有人发生过吗?

    支付宝异步回调收不到信息有人发生过吗?

    def notify_url_handler(request):
        if request.method=='POST':
            if alipay.verify_notify(**request.POST.dict()):
                a=Personblling.objects.create(user_id=1,billingmoney=2,billingstatus=True,trade_no=12)
                return HttpResponse("success")
            else:
                return HttpResponse("failed")
        else:
            return HttpResponse("failed")
    

    直接访问连接有用,但是支付后a那条操作无法执行

    opened by kangsgo 0
  • FIX SEVERE FAULT IN `check_notify_remotely`!

    FIX SEVERE FAULT IN `check_notify_remotely`!

    Two strings are not safe to compare using 'is'. Sometimes it will give the 'right' result, if the cpython "internalize" the string literals. Otherwise, two same strings might have different IDs.

    http://stackoverflow.com/questions/1504717/why-does-comparing-strings-in-python-using-either-or-is-sometimes-produce

    opened by Hexcles 0
  • 手机支付的问题

    手机支付的问题

    https://doc.open.alipay.com/doc2/detail.htm?treeId=203&articleId=105463&docType=1 文档介绍 wap 下生成的是 m.alipay.com 开头的 url 这里生成的是 mapi.alipay.com/gateway.do 开头的 不能唤起 支付宝 App ,需要手动拼接成 m.alipay.com 的 url 吗?

    opened by wuyazi 0
  • sign_type问题

    sign_type问题

    我看的文档https://doc.open.alipay.com/docs/api.htm?spm=a219a.7395905.0.0.wItNMR&docType=4&apiId=862 sign_type 都是RSA 为什么你的封装签名中用的是MD5 文档中说只支持RSA和RSA2呀 难道我看的是假文档?

    opened by wsqy 3
Owner
Eric Lo
Eric Lo
Python money class with optional CLDR-backed locale-aware formatting and an extensible currency exchange solution.

Python Money Money class with optional CLDR-backed locale-aware formatting and an extensible currency exchange solution. This is version 1.4.0-dev. De

Carlos Palol 214 Dec 22, 2022
A modular, high performance, headless e-commerce platform built with Python, GraphQL, Django, and React.

Saleor Commerce Customer-centric e-commerce on a modern stack A headless, GraphQL-first e-commerce platform delivering ultra-fast, dynamic, personaliz

Mirumee Labs 17.7k Dec 31, 2022
A web application to search for input products across several supermarkets' e-commerce to return price, detail of products running on Python.

Price Checker A web application to search for input products across several supermarkets' e-commerce to return price, detail of products. Requirements

null 3 Jun 28, 2022
Portfolio and E-commerce site built on Python-Django and Stripe checkout

StripeMe Introduction Stripe Me is an e-commerce and portfolio website offering communication services, including web-development, graphic design and

null 3 Jul 5, 2022
Storefront - An E-commerce StoreFront Application Built With Python

An E-commerce StoreFront Application A very robust storefront project. This is a

Fachii Felix Zasha 1 Apr 4, 2022
Currency Conversion in Python

CurrencyConversion connect to an API to do currency conversions, save as json text or screen output exchangeratesAPI.py -h Exchange Rates via 'api.cur

soup-works 1 Jan 29, 2022
Unofficial Open Corporates CLI: OpenCorporates is a website that shares data on corporations under the copyleft Open Database License. This is an unofficial open corporates python command line tool.

Unofficial Open Corporates CLI OpenCorporates is a website that shares data on corporations under the copyleft Open Database License. This is an unoff

Richard Mwewa 30 Sep 8, 2022
An API wrapper for Henrik's Unofficial VALORANT API

ValorantAPI.py An API wrapper for Henrik's Unofficial VALORANT API Warning!! This project is still in beta and only contains barely anything yet. If y

Jakkaphat Chalermphanaphan 0 Feb 4, 2022
This package accesses nitrotype's official api along with its unofficial user api

NitrotypePy This package accesses nitrotype's official api along with its unofficial user api. Currently still in development. Install To install, run

The Moon That Rises 2 Sep 4, 2022
The unofficial Amazon search CLI & Python API

amzSear The unofficial Amazon Product CLI & API. Easily search the amazon product directory from the command line without the need for an Amazon API k

Asher Silvers 95 Nov 11, 2022
🔍 Google Search unofficial API for Python with no external dependencies

Python Google Search API Unofficial Google Search API for Python. It uses web scraping in the background and is compatible with both Python 2 and 3. W

Avi Aryan 204 Dec 28, 2022
Unofficial GoPro API Library for Python - connect to GoPro via WiFi.

GoPro API for Python Unofficial GoPro API Library for Python - connect to GoPro cameras via WiFi. Compatibility: HERO3 HERO3+ HERO4 (including HERO Se

Konrad Iturbe 1.3k Jan 1, 2023
Unofficial Python wrapper for official Hacker News API

haxor Unofficial Python wrapper for official Hacker News API. Installation pip install haxor Usage Import and initialization: from hackernews import H

null 147 Sep 18, 2022
Unofficial Medium Python Flask API and SDK

PyMedium - Unofficial Medium API PyMedium is an unofficial Medium API written in python flask. It provides developers to access to user, post list and

Engine Bai 157 Nov 11, 2022
(unofficial) Googletrans: Free and Unlimited Google translate API for Python. Translates totally free of charge.

Googletrans Googletrans is a free and unlimited python library that implemented Google Translate API. This uses the Google Translate Ajax API to make

Suhun Han 3.2k Jan 4, 2023
Unofficial Python API client for Notion.so

notion-py Unofficial Python 3 client for Notion.so API v3. Object-oriented interface (mapping database tables to Python classes/attributes) Automatic

Jamie Alexandre 3.9k Jan 3, 2023
An Unofficial TikTok API Wrapper In Python

This is an unofficial api wrapper for TikTok.com in python. With this api you are able to call most trending and fetch specific user information as well as much more.

David Teather 2.9k Jan 8, 2023
Unofficial YooMoney API python library

API Yoomoney - unofficial python library This is an unofficial YooMoney API python library. Summary Introduction Features Installation Quick start Acc

Aleksey Korshuk 136 Dec 30, 2022
Unofficial python api for MicroBT Whatsminer ASICs

whatsminer-api Unofficial python api for MicroBT Whatsminer ASICs Code adapted from a python file found in the Whatsminer Telegram group that is credi

Satoshi Anonymoto 16 Dec 23, 2022
An unofficial python API for trading on the DeGiro platform, with the ability to get real time data and historical data.

DegiroAPI An unofficial API for the trading platform Degiro written in Python with the ability to get real time data and historical data for products.

Jorrick Sleijster 5 Dec 16, 2022