• Stars
    star
    268
  • Rank 153,144 (Top 4 %)
  • Language
    Python
  • License
    Apache License 2.0
  • Created over 6 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

支付宝开放平台 Alipay SDK for Python

alipay-sdk-python

The official Alipay SDK for Python.

访问蚂蚁金服开放平台的官方SDK。

Links

Issues

不管您在使用SDK的过程中遇到任何问题,欢迎前往 支付宝开放社区 发帖与支付宝工作人员和其他开发者一起交流。

注:为了提高开发者问题的响应时效,github本身的issue功能已关闭,支付宝开放社区中发帖的问题,通常会在2小时内响应。

Example

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import traceback

from alipay.aop.api.AlipayClientConfig import AlipayClientConfig
from alipay.aop.api.DefaultAlipayClient import DefaultAlipayClient
from alipay.aop.api.FileItem import FileItem
from alipay.aop.api.domain.AlipayTradeAppPayModel import AlipayTradeAppPayModel
from alipay.aop.api.domain.AlipayTradePagePayModel import AlipayTradePagePayModel
from alipay.aop.api.domain.AlipayTradePayModel import AlipayTradePayModel
from alipay.aop.api.domain.GoodsDetail import GoodsDetail
from alipay.aop.api.domain.SettleDetailInfo import SettleDetailInfo
from alipay.aop.api.domain.SettleInfo import SettleInfo
from alipay.aop.api.domain.SubMerchant import SubMerchant
from alipay.aop.api.request.AlipayOfflineMaterialImageUploadRequest import AlipayOfflineMaterialImageUploadRequest
from alipay.aop.api.request.AlipayTradeAppPayRequest import AlipayTradeAppPayRequest
from alipay.aop.api.request.AlipayTradePagePayRequest import AlipayTradePagePayRequest
from alipay.aop.api.request.AlipayTradePayRequest import AlipayTradePayRequest
from alipay.aop.api.response.AlipayOfflineMaterialImageUploadResponse import AlipayOfflineMaterialImageUploadResponse
from alipay.aop.api.response.AlipayTradePayResponse import AlipayTradePayResponse

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s %(levelname)s %(message)s',
    filemode='a',)
logger = logging.getLogger('')


if __name__ == '__main__':
    """
    设置配置,包括支付宝网关地址、app_id、应用私钥、支付宝公钥等,其他配置值可以查看AlipayClientConfig的定义。
    """
    alipay_client_config = AlipayClientConfig()
    alipay_client_config.server_url = 'https://openapi.alipay.com/gateway.do'
    alipay_client_config.app_id = '[your app_id]'
    alipay_client_config.app_private_key = '[your app private key]'
    alipay_client_config.alipay_public_key = '[alipay public key]'

    """
    得到客户端对象。
    注意,一个alipay_client_config对象对应一个DefaultAlipayClient,定义DefaultAlipayClient对象后,alipay_client_config不得修改,如果想使用不同的配置,请定义不同的DefaultAlipayClient。
    logger参数用于打印日志,不传则不打印,建议传递。
    """
    client = DefaultAlipayClient(alipay_client_config=alipay_client_config, logger=logger)

    """
    系统接口示例:alipay.trade.pay
    """
    # 对照接口文档,构造请求对象
    model = AlipayTradePayModel()
    model.auth_code = "282877775259787048"
    model.body = "Iphone6 16G"
    goods_list = list()
    goods1 = GoodsDetail()
    goods1.goods_id = "apple-01"
    goods1.goods_name = "ipad"
    goods1.price = 10
    goods1.quantity = 1
    goods_list.append(goods1)
    model.goods_detail = goods_list
    model.operator_id = "yx_001"
    model.out_trade_no = "20180510AB014"
    model.product_code = "FACE_TO_FACE_PAYMENT"
    model.scene = "bar_code"
    model.store_id = ""
    model.subject = "huabeitest"
    model.timeout_express = "90m"
    model.total_amount = 1
    request = AlipayTradePayRequest(biz_model=model)
    # 如果有auth_token、app_auth_token等其他公共参数,放在udf_params中
    # udf_params = dict()
    # from alipay.aop.api.constant.ParamConstants import *
    # udf_params[P_APP_AUTH_TOKEN] = "xxxxxxx"
    # request.udf_params = udf_params
    # 执行请求,执行过程中如果发生异常,会抛出,请打印异常栈
    response_content = None
    try:
        response_content = client.execute(request)
    except Exception as e:
        print(traceback.format_exc())
    if not response_content:
        print("failed execute")
    else:
        response = AlipayTradePayResponse()
        # 解析响应结果
        response.parse_response_content(response_content)
        print(response.body)
        if response.is_success():
            # 如果业务成功,则通过respnse属性获取需要的值
            print("get response trade_no:" + response.trade_no)
        else:
            # 如果业务失败,则从错误码中可以得知错误情况,具体错误码信息可以查看接口文档
            print(response.code + "," + response.msg + "," + response.sub_code + "," + response.sub_msg)


    """
    带文件的系统接口示例:alipay.offline.material.image.upload
    """
    # 如果没有找到对应Model类,则直接使用Request类,属性在Request类中
    request = AlipayOfflineMaterialImageUploadRequest()
    request.image_name = "我的店"
    request.image_type = "jpg"
    # 设置文件参数
    f = open("/Users/foo/Downloads/IMG.jpg", "rb")
    request.image_content = FileItem(file_name="IMG.jpg", file_content=f.read())
    f.close()
    response_content = None
    try:
        response_content = client.execute(request)
    except Exception as e:
        print(traceback.format_exc())
    if not response_content:
        print("failed execute")
    else:
        response = AlipayOfflineMaterialImageUploadResponse()
        response.parse_response_content(response_content)
        if response.is_success():
            print("get response image_url:" + response.image_url)
        else:
            print(response.code + "," + response.msg + "," + response.sub_code + "," + response.sub_msg)


    """
    页面接口示例:alipay.trade.page.pay
    """
    # 对照接口文档,构造请求对象
    model = AlipayTradePagePayModel()
    model.out_trade_no = "pay201805020000226"
    model.total_amount = 50
    model.subject = "测试"
    model.body = "支付宝测试"
    model.product_code = "FAST_INSTANT_TRADE_PAY"
    settle_detail_info = SettleDetailInfo()
    settle_detail_info.amount = 50
    settle_detail_info.trans_in_type = "userId"
    settle_detail_info.trans_in = "2088302300165604"
    settle_detail_infos = list()
    settle_detail_infos.append(settle_detail_info)
    settle_info = SettleInfo()
    settle_info.settle_detail_infos = settle_detail_infos
    model.settle_info = settle_info
    sub_merchant = SubMerchant()
    sub_merchant.merchant_id = "2088301300153242"
    model.sub_merchant = sub_merchant
    request = AlipayTradePagePayRequest(biz_model=model)
    # 得到构造的请求,如果http_method是GET,则是一个带完成请求参数的url,如果http_method是POST,则是一段HTML表单片段
    response = client.page_execute(request, http_method="GET")
    print("alipay.trade.page.pay response:" + response)


    """
    构造唤起支付宝客户端支付时传递的请求串示例:alipay.trade.app.pay
    """
    model = AlipayTradeAppPayModel()
    model.timeout_express = "90m"
    model.total_amount = "9.00"
    model.seller_id = "2088301194649043"
    model.product_code = "QUICK_MSECURITY_PAY"
    model.body = "Iphone6 16G"
    model.subject = "iphone"
    model.out_trade_no = "201800000001201"
    request = AlipayTradeAppPayRequest(biz_model=model)
    response = client.sdk_execute(request)
    print("alipay.trade.app.pay response:" + response)

More Repositories

1

SoloPi

SoloPi 自动化测试工具
Java
5,736
star
2

alipay-easysdk

Alipay Easy SDK for multi-language(java、c#、php、ts etc.) allows you to enjoy a minimalist programming experience and quickly access the various high-frequency capabilities of the Alipay Open Platform.
Java
1,099
star
3

agentUniverse

agentUniverse is a LLM multi-agent framework that allows developers to easily build multi-agent applications.
Python
799
star
4

alipay-sdk-java-all

支付宝开放平台 Alipay SDK for Java
Java
521
star
5

alipay-sdk-nodejs-all

支付宝开放平台 Alipay SDK for Node.js
TypeScript
408
star
6

mPaaS

mPaaS Demo 合集,mPaaS 是源自于支付宝的移动开发平台。The collection of demos for mPaaS components. mPaaS is the Mobile Development Platform which oriented from Alipay.
C
323
star
7

ant-application-security-testing-benchmark

xAST评价体系,让安全工具不再“黑盒”. The xAST evaluation benchmark makes security tools no longer a "black box".
Java
301
star
8

PainlessInferenceAcceleration

Python
283
star
9

Owfuzz

Owfuzz: a WiFi protocol fuzzing tool
C
216
star
10

alipay-sdk-net-all

支付宝开放平台 Alipay SDK for .NET
C#
200
star
11

cvpr2020-plant-pathology

Python
170
star
12

antcloud-node-stack

蚂蚁金融科技官方 Node 技术栈脚本
JavaScript
159
star
13

financial_evaluation_dataset

Python
154
star
14

rdf-file

Rdf-File是一个处理结构化文本文件的工具组件
Java
149
star
15

alipay-sdk-php-all

支付宝开放平台 Alipay SDK for PHP
PHP
146
star
16

SOFAStack

SOFAStack™ (Scalable Open Financial Architecture Stack) is a collection of cloud native middleware components, which are designed to build distributed systems with high performance and reliability, and have been fully validated by mission-critical financial business scenarios.
139
star
17

Ant-Multi-Modal-Framework

Research Code for Multimodal-Cognition Team in Ant Group
Python
117
star
18

vsag

vsag is a vector indexing library used for similarity search.
C++
115
star
19

Pyraformer

Python
100
star
20

container-observability-service

Simplify Kubernetes applications operation with one-stop observability services, including resource delivery SLO,root cause diagnoses and container lifecycle tracing and more.
Go
88
star
21

ios-malicious-bithunter

iOS Malicious Bit Hunter is a malicious plug-in detection engine for iOS applications. It can analyze the head of the macho file of the injected dylib dynamic library based on runtime. If you are interested in other programs of the author, please visit https://github.com/SecurityLife
C
83
star
22

goldfish

A development framework for Alipay Mini Program.
TypeScript
80
star
23

SQLFlow

SQLFlow is a bridge that connects a SQL engine, e.g. MySQL, Hive, SparkSQL or SQL Server, with TensorFlow and other machine learning toolkits. SQLFlow extends the SQL language to enable model training, prediction and inference.
73
star
24

KnowledgeGraphEmbeddingsViaPairedRelationVectors_PairRE

Python
61
star
25

Antchain-MPC

Antchain-MPC is a library of MPC (Multi-Parties Computation)
Terra
57
star
26

VCSL

Video Copy Segment Localization (VCSL) dataset and benchmark [CVPR2022]
Python
49
star
27

StructuredLM_RTDT

A library for building hierarchical text representation and corresponding downstream applications.
Python
48
star
28

RJU_Ant_QA

The RJUA-QA (RenJi hospital department of Urology and Antgroup collaborative Question and Answer dataset) is an innovative medical urology specialty QA inference dataset.
47
star
29

Z-RareCharacterSolution

TypeScript
45
star
30

quic-lb

nginx-quic-lb is an implementation of ietf-quic-lb, based on nginx-release-1.18.0, you can see the detailed code in this pull request
C
41
star
31

jpmml-sparkml-lightgbm

JPMML-SparkML plugin for converting LightGBM-Spark models to PMML
Java
41
star
32

PASE

C
41
star
33

global-open-sdk-java

Ant global gateway SDK
Java
35
star
34

container-auto-tune

Container Auto Tune is an intelligent parameter tuning product that helps developers, operators automatically adjust the application, analyzes JVM reasonable configuration parameters through intelligent algorithms.Please visit the official site for the quick start guide and documentation.
Java
32
star
35

promo-mini-component

支付宝营销玩法小程序组件库
JavaScript
31
star
36

private_llm

Python
28
star
37

tls13-sm-spec

IETF Internet-Draft (I-D) of Chinese cipher suites in TLSv1.3 and related documentation.
Makefile
27
star
38

microservice_system_twin_graph_based_anomaly_detection

Python
26
star
39

mobile-agent

Python
26
star
40

alipay-intellij-plugin

Intellij IDEA Plugin
20
star
41

character-js

TypeScript
19
star
42

global-open-sdk-php

Ant global gateway SDK
PHP
17
star
43

ams-java-sdk

AMS Java binding
Java
13
star
44

antchain-openapi-prod-sdk

PHP
10
star
45

Pattern-Based-Compression

High-Ratio Compression for Machine-Generated Data
C
10
star
46

global-open-sdk-python

Ant global gateway SDK
Python
10
star
47

PC2-NoiseofWeb

Noise of Web (NoW) is a challenging noisy correspondence learning (NCL) benchmark containing 100K image-text pairs for robust image-text matching/retrieval models.
Python
9
star
48

YiJian-Community

YiJian-Comunity: a full-process automated large model safety evaluation tool designed for academic research
Python
9
star
49

AOP-Based-Runtime-Security-Analysis-Toolkit

TypeScript
8
star
50

ant-application-security-testing-benchmark-nodejs

JavaScript
8
star
51

agentUniverse-Guides

8
star
52

RGSL

Python
8
star
53

POA

Python
7
star
54

payment-code-widget

A lightweight library provides UI widgets to display payment code in mobile applications. The dimension of the payment code is optimal and scanner-friendly.
Java
6
star
55

TDEER

Code For TDEER: An Efficient Translating Decoding Schema for Joint Extraction of Entities and Relations (EMNLP 2021)
Python
5
star
56

Finite_State_Autoregressive_Entropy_Coding

Python
5
star
57

ComBERT

4
star
58

Parameter_Inference_Efficient_PIE

Python
4
star
59

NMCDR

Python
4
star
60

A2-efficient-automated-attacker-for-boosting-adversarial-training

Python
4
star
61

global-open-sdk-dotnet

C#
3
star
62

tldk

This is a fork of FDio/tldk.
C
3
star
63

DUPLEX

Python
3
star
64

antchain-openapi-util-sdk

C#
3
star
65

Automatic_AI_Model_Greenness_Track_Toolkit

JavaScript
3
star
66

style-tokenizer

Python
3
star
67

Timestep-aware-SentenceEmbedding-and-AcmeCoverage

Python
2
star
68

ATTEMPT_Pre-training_with_Aspect-Content_Text_Mutual_Prediction

Python
2
star
69

hypro_tpp

Python
1
star
70

BehaviorAugmentedRelevanceModel

Implementation and data of the paper "Beyond Semantics: Learning a Behavior Augmented Relevance Model with Self-supervised Learning" in CIKM'23.
Python
1
star
71

A-Knowledge-augmented-Method-DiKGRS

Python
1
star
72

Analogic-Reasoning-Augmented-Large-Language-Model

Python
1
star
73

MMDL-based-Data-Augmentation-with-Domain-Knowledge-for-Time-Series-Classification

This repository contains the official implementation for the paper: MMDL-based Data Augmentation with Domain Knowledge for Time Series Classification.
Python
1
star