支付寶接口

螞蟻金服開放平臺

一、沙箱環境html

 

 

二、設置公鑰私鑰python

 

下載完解壓,查看文檔數據庫

 

按要求執行django

點擊RSA簽名驗籤工具.bat文件json

 

生成後以下api

 

而後在文件中會自動保存生成的祕鑰公鑰服務器

 

複製應用公鑰,而後保存。app

保存後生成以下dom

上傳應用公鑰自動生成支付寶公鑰,ide

而後須要下載沙箱支付寶APP。注意:僅供安卓手機。


沙箱帳號

 

具體項目使用

依賴  pip install pycryptodome

utils中的pay.py

from datetime import datetime
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA256
from urllib.parse import quote_plus
from urllib.parse import urlparse, parse_qs
from base64 import decodebytes, encodebytes
import json


class AliPay(object):
    """
    支付寶支付接口(PC端支付接口)
    """

    def __init__(self, appid, app_notify_url, app_private_key_path,
                 alipay_public_key_path, return_url, debug=False):
        self.appid = appid
        self.app_notify_url = app_notify_url
        self.app_private_key_path = app_private_key_path
        self.app_private_key = None
        self.return_url = return_url
        with open(self.app_private_key_path) as fp:
            self.app_private_key = RSA.importKey(fp.read())
        self.alipay_public_key_path = alipay_public_key_path
        with open(self.alipay_public_key_path) as fp:
            self.alipay_public_key = RSA.importKey(fp.read())

        if debug is True:
            self.__gateway = "https://openapi.alipaydev.com/gateway.do"
        else:
            self.__gateway = "https://openapi.alipay.com/gateway.do"

    def direct_pay(self, subject, out_trade_no, total_amount, return_url=None, **kwargs):
        biz_content = {
            "subject": subject,
            "out_trade_no": out_trade_no,
            "total_amount": total_amount,
            "product_code": "FAST_INSTANT_TRADE_PAY",
            # "qr_pay_mode":4
        }

        biz_content.update(kwargs)
        data = self.build_body("alipay.trade.page.pay", biz_content, self.return_url)
        return self.sign_data(data)

    def build_body(self, method, biz_content, return_url=None):
        data = {
            "app_id": self.appid,
            "method": method,
            "charset": "utf-8",
            "sign_type": "RSA2",
            "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            "version": "1.0",
            "biz_content": biz_content
        }

        if return_url is not None:
            data["notify_url"] = self.app_notify_url
            data["return_url"] = self.return_url

        return data

    def sign_data(self, data):
        data.pop("sign", None)
        # 排序後的字符串
        unsigned_items = self.ordered_data(data)
        unsigned_string = "&".join("{0}={1}".format(k, v) for k, v in unsigned_items)
        sign = self.sign(unsigned_string.encode("utf-8"))
        # ordered_items = self.ordered_data(data)
        quoted_string = "&".join("{0}={1}".format(k, quote_plus(v)) for k, v in unsigned_items)

        # 得到最終的訂單信息字符串
        signed_string = quoted_string + "&sign=" + quote_plus(sign)
        return signed_string

    def ordered_data(self, data):
        complex_keys = []
        for key, value in data.items():
            if isinstance(value, dict):
                complex_keys.append(key)

        # 將字典類型的數據dump出來
        for key in complex_keys:
            data[key] = json.dumps(data[key], separators=(',', ':'))

        return sorted([(k, v) for k, v in data.items()])

    def sign(self, unsigned_string):
        # 開始計算簽名
        key = self.app_private_key
        signer = PKCS1_v1_5.new(key)
        signature = signer.sign(SHA256.new(unsigned_string))
        # base64 編碼,轉換爲unicode表示並移除回車
        sign = encodebytes(signature).decode("utf8").replace("\n", "")
        return sign

    def _verify(self, raw_content, signature):
        # 開始計算簽名
        key = self.alipay_public_key
        signer = PKCS1_v1_5.new(key)
        digest = SHA256.new()
        digest.update(raw_content.encode("utf8"))
        if signer.verify(digest, decodebytes(signature.encode("utf8"))):
            return True
        return False

    def verify(self, data, signature):
        if "sign_type" in data:
            sign_type = data.pop("sign_type")
        # 排序後的字符串
        unsigned_items = self.ordered_data(data)
        message = "&".join(u"{}={}".format(k, v) for k, v in unsigned_items)
        return self._verify(message, signature)
pay.py

url.py

from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^index/', views.index),
    url(r'^pay_result/', views.pay_result),
    url(r'^update_order/', views.update_order),
]

 models.py

from django.db import models

class Order(models.Model):

    title = models.CharField(max_length=32)
    order_num = models.CharField(max_length=32)
    status_choices = (
        (1,'未支付'),
        (2,'已支付'),
    )
    status = models.IntegerField(choices=status_choices,default=1)

 views.py

from django.shortcuts import render,redirect,HttpResponse
from django.views.decorators.csrf import csrf_exempt
from utils.pay import AliPay
import time
from django.conf import settings

def aliPay():
    obj = AliPay(
        appid=settings.APPID,
        app_notify_url=settings.NOTIFY_URL,  # 若是支付成功,支付寶會向這個地址發送POST請求(校驗是否支付已經完成)
        return_url=settings.RETURN_URL,  # 若是支付成功,重定向回到你的網站的地址。
        alipay_public_key_path=settings.PUB_KEY_PATH,  # 支付寶公鑰
        app_private_key_path=settings.PRI_KEY_PATH,  # 應用私鑰
        debug=True,  # 默認False,
    )
    return obj

def index(request):
    if request.method == 'GET':
        return render(request,'index.html')



    alipay = aliPay()

    # 對購買的數據進行加密
    money = float(request.POST.get('price'))
    out_trade_no = "x2" + str(time.time())
    # 1. 在數據庫建立一條數據:狀態(待支付)

    query_params = alipay.direct_pay(
        subject="充氣式韓紅",  # 商品簡單描述
        out_trade_no= out_trade_no,  # 商戶訂單號
        total_amount=money,  # 交易金額(單位: 元 保留倆位小數)
    )

    pay_url = "https://openapi.alipaydev.com/gateway.do?{}".format(query_params)

    return redirect(pay_url)


def pay_result(request):
    """
    支付完成後,跳轉回的地址
    :param request:
    :return:
    """
    params = request.GET.dict()
    sign = params.pop('sign', None)

    alipay = aliPay()

    status = alipay.verify(params, sign)

    if status:
        return HttpResponse('支付成功')
    return HttpResponse('支付失敗')



@csrf_exempt
def update_order(request):
    """
    支付成功後,支付寶向該地址發送的POST請求(用於修改訂單狀態)
    :param request:
    :return:
    """
    if request.method == 'POST':
        from urllib.parse import parse_qs

        body_str = request.body.decode('utf-8')
        post_data = parse_qs(body_str)

        post_dict = {}
        for k, v in post_data.items():
            post_dict[k] = v[0]

        alipay = aliPay()

        sign = post_dict.pop('sign', None)
        status = alipay.verify(post_dict, sign)
        if status:
            # 修改訂單狀態
            out_trade_no = post_dict.get('out_trade_no')
            print(out_trade_no)
            # 2. 根據訂單號將數據庫中的數據進行更新
            return HttpResponse('支付成功')
        else:
            return HttpResponse('支付失敗')
    return HttpResponse('')
views.py

settings.py

# 支付相關配置
APPID = "2016082500309412"
NOTIFY_URL = "http://47.98.134.86:80/update_order/"
RETURN_URL = "http://47.98.134.86:80/pay_result/"
PRI_KEY_PATH = "keys/app_private_2048.txt"
PUB_KEY_PATH = "keys/alipay_public_2048.txt"

 注意事項:

支付寶支付使用的是RSA加密

須要的是由app公鑰生成的支付寶公鑰,app私鑰

支付寶提交的金額最多保留兩位小數

1. 什麼是SDK?
    - 第三方服務商提供的實現軟件產品某項功能的工具包
    
2. 沙箱環境是什麼?
    - 是測試環境

3. 簡述支付寶支付流程:
    - 用戶點擊支持,根據支付寶的AppID/網關/公鑰私鑰/SDK生成地址
    - 用戶跳轉到支付寶
    - 支付成功以後,支付寶會給我發送兩個請求:
        - GET, 從支付寶網站跳轉回本身網站。
        - POST,支付發送支付信息(修改訂單狀態)
    
4. 支付寶金額的精度?
    - 小數點後兩位

5. 支付寶用的什麼加密?
    - RSA

6. 支付完成以後,服務器宕機了,怎麼辦?
    - 24小時內,支付依然發送通知。
支付總結
相關文章
相關標籤/搜索