支付宝支付

一、支付宝支付:沙箱测试环境

支付宝支付
  a. 去支付宝申请
    - 正式:营业执照
    - 测试:沙箱测试环境  https://openhome.alipay.com/platform/appDaily.htm?tab=info

              https://open.alipay.com/platform/homeRoleSelection.htm
               

  开发者中心,研发服务,沙箱环境。。。

  下载沙箱APP.作为测试得支付宝


  APPID:
    2016091700535390
  买家:
    买家账号 jtyapr6187@sandbox.com
    登录密码 111111
    支付密码 111111

 

 

 

二、生成公钥,私钥

b. 开发程序
  SDK
    - 官方
    - github
      utils/pay.py
    依赖:pip3 install pycryptodome

  公钥私钥:用公钥加密数据,用私钥来解密数据
    - 应用公钥
      - 支付宝公钥
    - 应用私钥

 

 

 

三、测试支付

用之前,下载好得沙箱环境得app,里面可以设置账户余额,扫码,支付

即:

  买家:
    买家账号 jtyapr6187@sandbox.com
    登录密码 111111
    支付密码 111111

 

支付成功,返回到商户界面时,需要校验是否是阿里得 签名!!!

支付成功,阿里返回得数据:

{'charset': 'utf-8', 'out_trade_no': 'x21533095384.3803577', 'method': 'alipay.trade.page.pay.return', 'total_amount': '100.00', 'sign': 'I4AYXuDOt7kzQuzCu8sAQptRjbQQXamBJDCArQ+2NSy4JpuA0QM06/82SwHwglT4vVgv8xMP1U6UXYP3+1/A1lNuyAwUa0gp/C3XAa8W19vaQucR/VQUJi5MCXtMx5BG07MviepyBlwdud0YpScfTlmY2cNum0Kc02nD/icFJQwEM0+6sPzKTAeuJz21poX3HqFnJAfTSktocvLYqLj4QLoopGbzvzQ+vp70r1Cp5OX7QaZkwDtD8lpRSymNEntu6nr/4V5iJ6iE0J55W7kwfIOJfWymkCtKE1mo0NBVe9CslsA1HnWYkW+fQBgq9tl5+fGxG0JYlz1TiGchfSFc/Q==', 'trade_no': '2018080121001004080200706519', 'auth_app_id': '2016091700535390', 'version': '1.0', 'app_id': '2016091700535390', 'sign_type': 'RSA2', 'seller_id': '2088102176095872', 'timestamp': '2018-08-01 11:50:16'}

 

 

 

 

 

 

订单状态修改:

中间有一个环节:支付成功,校验是否完成,修改订单状态,返回商家页面

app_notify_url=settings.NOTIFY_URL,  # 如果支付成功,支付宝会向这个地址发送POST请求(校验是否支付已经完成)
return_url=settings.RETURN_URL, # 如果支付成功,重定向回到你的网站的地址。

 

# 支付相关配置
APPID = "2016091700535390"
NOTIFY_URL = "http://10.0.0.200/update_order/" # 得是公网ip 阿里返回得只能是 公网;
RETURN_URL = "http://127.0.0.1:8000/pay_result/"
PUB_KEY_PATH = "keys/alipay_public_2048.txt"
PRI_KEY_PATH = "keys/app_private_2048.txt"

 

四、代码copy到服务器运行 

只有公网ip,才能让支付宝找到,调用函数,校验:是否是阿里得签名,才能修改订单得状态;

 

 

 

 

五、code

https://github.com/alice-bj/alipay

 

  

 

 

settings.py

# 支付相关配置
APPID = "2016091700535390"
NOTIFY_URL = "http://10.0.0.200:8000/update_order/"  # 得是公网ip
RETURN_URL = "http://10.0.0.200:8000/pay_result/"
PUB_KEY_PATH = "keys/alipay_public_2048.txt"
PRI_KEY_PATH = "keys/app_private_2048.txt"

 

urls.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),
]

 

utils/pay.py  对商品 价格 加密

# -*- coding:utf-8 -*-
"""
github 上得一个 支付宝支付得 sdk

pip3 install pycryptodome
"""
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)

 

app01/views.py

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

from utils.pay import AliPay


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")

    # 价格、购买得商品加密,这就用到了util中得pay.py(sdk)加密并生成url
    # 拼接成URL

    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('')

 

keys/alipay_public_2048.txt  (支付宝得公钥)

-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4KooG9xZ2AUbsvxf0BaAmt9ivUZADBMeT7h5xj9sxzGEpHFfh8wABoOm2i2jOa/1CQniDqDrarbM3yGDk7Ee5LoaHfPCJrObF8jI+mlu59rBF6XLy3woJwM7W555Ku2o2pcxQ0lQhMuNG4dnaxGGkp5gk9TY/4YR8N1nai9Hq7VpcoqMb+xFk2yExhORfIeRIJBlLNsGeJhBull8I5xsUeTeUlc7I4RzfhV8SEMrg2h7kAkJtiC4PljqrLaSGWD0DWVZ03od/fh9/XNjxOXJSv7F6iObgnYwcQYYZV3RH1uzMDo17aGP70tNMsGWmfFNOa80JG4j0ky/Uq9LKxzbEQIDAQAB
-----END PUBLIC KEY-----

 

keys/app_private_2048.txt (商家得私钥)

-----BEGIN RSA PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCt2B0eZIiyxZL+nV70gE0rFHupuJzthM96BkfVXSxcp9BY1IPvTba9Ks58SJ6KJiPHAk/XyWjvPYL0LkvGNJxS+Eqsem4EoWbqt/UJyz4N+4ZoK5+2sjY941soQvDYQesLNB491l+LxCzU1hXwylII4VBThAiv/+lWOAdShCajINZx7DnRWNhcLuVTrFGAabhqLEQ0Mm+Xsyd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408jDJnpvkblmWbgtNVo7Uo0mUzOaXZPy/Zjml9p8qZ3RQdS8zYKhnM/OVFHChQT5VIQs1rp040j6WIT5AAKVyrJYhdISdjCx/a3G8TzAoGBAIWmJtyPbAwr69ddcNZfqMkJWcjh/bhWH1S8czJ3Pbr3x6xPBbpN+XF49x9h7HAtUILlOiXWYnQCVu19xv0D06CodiF00m5dcmP3WTPGxmOqm7tmXvFk2Z1SrL1FNUqxlFqWM/WpNCWXYeXv1GDwaxcW3WuG+mIVE7XVMpmC/tkC
-----END RSA PRIVATE KEY-----

 

六、总结

支付
  - rsa 加密
  - 商户私钥+支付宝公钥
  - 精度,小数点后2位
  - 宕机,程序需要返回success,否则支付宝一天一直会发

 

申请:

        a. 去支付宝申请 
            - 正式:营业执照
            - 测试:沙箱测试环境 https://openhome.alipay.com/platform/appDaily.htm?tab=info
                               
                    开发者中心,研发服务,沙箱环境。。。
                    
                    下载沙箱APP.作为测试得支付宝;
        
                    
                    APPID:
                        2016091700535390
                    买家:
                        买家账号  jtyapr6187@sandbox.com
                        登录密码  111111
                        支付密码  111111
        b. 开发程序
            SDK
                - 官方
                - github
                    utils/pay.py 
                    依赖:pip3 install pycryptodome
            
            公钥私钥:用公钥加密数据,用私钥来解密数据 
                - 应用公钥 
                    - 支付宝公钥
                - 应用私钥

 

开发:

  1. 引入一个sdk(AliPay) 需要对 商品价格 加密

  2. 需要用:

        APPID、

          支付成功发得post请求(修改订单得状态)地址、

       支付成功,重定向得网站地址、

       支付宝得公钥、

       商家得私钥、

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,
)

 

  

       3. 实例化AliPay对象后,对商品,价格加密后,就可以跳转到二维码得支付页面

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)

    

  

      4. 支付成功,跳转回的页面,验证阿里得签名

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('支付失败')

  

      5. 支付之后,阿里会发一个post请求,我们可以修改订单状态,验证阿里得签名(这个得在公网ip下,阿里得能找到)

@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('支付失败')

        

posted @ 2018-08-01 08:57  Alice的小屋  阅读(2374)  评论(0编辑  收藏  举报