Exemple #1
0
    def get(self, request, order_id):
        """
        0. 必须是登录用户, 获取用户信息
        1. 获取order_id
        2. 根据订单id查询订单信息
        3. 创建支付宝 支付对象
        4. 生成 order_string
        5. 拼接url
        6. 返回支付url
        :param request:
        :param order_id:
        :return:
        """
        # 0. 必须是登录用户, 获取用户信息
        user = request.user
        # 1. 获取order_id   url中有
        # 2. 根据订单id查询订单信息
        # 查询更准确,多添加一些条件
        try:
            order = OrderInfo.objects.get(order_id=order_id, user=user)
        except OrderInfo.DoesNotExist:
            return JsonResponse({'code': 400, 'errmsg': '没有此订单'})

        # https://github.com/fzlee/alipay/blob/master/README.zh-hans.md
        # 3. 创建支付宝 支付对象
        from alipay import AliPay
        from alipay.utils import AliPayConfig
        # 3.1 通过文件的形式 来 读取 美多私钥  和 支付宝 公钥
        # 我们最好设置一个相对路径,把相对路径的配置 放到 settings.py中
        from meiduo_mall import settings
        app_private_key_string = open(settings.APP_PRIVATE_KEY_PATH).read()
        alipay_public_key_string = open(settings.ALIPAY_PUBLIC_KEY_PATH).read()

        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_string=app_private_key_string,
            # 支付宝的公钥,验证支付宝回传消息使用,不是你自己的公钥,
            alipay_public_key_string=alipay_public_key_string,
            sign_type="RSA2",  # RSA 或者 RSA2
            debug=False,  # 默认False
            config=AliPayConfig(timeout=15)  # 可选, 请求超时时间
        )
        # 4. 通过电脑网址支付的方法, 来生成 order_string
        # 如果你是 Python 3的用户,使用默认的字符串即可
        subject = "测试订单"

        # 电脑网站支付,需要跳转到https://openapi.alipay.com/gateway.do? + order_string
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,  # 美多商城的订单id
            total_amount=str(order.total_amount),  # 订单总金额  类型转换为 str
            subject=subject,
            return_url=settings.ALIPAY_RETURN_URL,  # 支付成功之后,最终要跳转会美多
            #notify_url="https://example.com/notify"  # 可选, 不填则使用默认notify url
        )
        # 5. 拼接url
        alipay_url = 'https://openapi.alipaydev.com/gateway.do?' + order_string

        # 6. 返回支付url
        return JsonResponse({'code': 0, 'alipay_url': alipay_url})
Exemple #2
0
def create_recharge(money=10):
    """创建充值订单"""
    current_user_id = get_jwt_identity()
    user = User.query.get(current_user_id)
    if user is None:
        return {
            "errno": status.CODE_NO_USER,
            "errmsg": message.user_not_exists,
        }
    order_number = datetime.now().strftime(
        "%y%m%d%H%M%S") + "%08d" % user.id + "%04d" % random.randint(0, 9999)

    print(order_number)

    recharge = Recharge(status=False,
                        out_trade_number=order_number,
                        name="账号充值-%s元" % money,
                        user_id=user.id,
                        money=money)
    db.session.add(recharge)
    db.session.commit()
    # 创建支付宝sdk对象
    app_private_key_string = open(
        os.path.join(
            current_app.BASE_DIR,
            "application/apps/users/keys/app_private_key.pem")).read()
    alipay_public_key_string = open(
        os.path.join(current_app.BASE_DIR,
                     "application/apps/users/keys/app_public_key.pem")).read()

    alipay = AliPay(
        appid=current_app.config.get("ALIPAY_APP_ID"),
        app_notify_url=None,  # 默认回调url
        app_private_key_string=app_private_key_string,
        # 支付宝的公钥,验证支付宝回传消息使用,不是你自己的公钥,
        alipay_public_key_string=alipay_public_key_string,
        sign_type=current_app.config.get("ALIPAY_SIGN_TYPE"),
        debug=False,  # 默认False
        config=AliPayConfig(timeout=15)  # 可选, 请求超时时间
    )

    order_string = alipay.api_alipay_trade_app_pay(
        out_trade_no=recharge.out_trade_number,  # 订单号
        total_amount=float(recharge.money),  # 订单金额
        subject=recharge.name,  # 订单标题
        notify_url=current_app.config.get(
            "ALIPAY_NOTIFY_URL")  # 服务端的地址,自定义一个视图函数给alipay
    )

    return {
        "errno": status.CODE_OK,
        "errmsg": message.ok,
        "sandbox": current_app.config.get("ALIPAY_SANDBOX"),
        "order_string": order_string,
        "order_number": recharge.out_trade_number,
    }
Exemple #3
0
    def post(self, request):
        '''订单支付'''
        #判断登录
        user = request.user
        if not user.is_authenticated:
            return JsonResponse({'res': 1, 'error': '用户未登录'})
        #接收参数
        order_id = request.POST.get('order_id')
        #校验参数
        if not order_id:
            return JsonResponse({'res': 2, 'error': '订单无效'})
        try:
            order = OrderInfo.objects.get(order_id=order_id,
                                          user=user,
                                          pay_method=3,
                                          order_status=1)
        except OrderInfo.DoesNotExist:
            return JsonResponse({'res': 3, 'error': '订单无效'})
        #业务处理,调用支付接口
        # 配置地址
        app_private_path = os.path.join(settings.BASE_DIR,
                                        'apps/order/app_private_key.pem')
        alipay_public_path = os.path.join(settings.BASE_DIR,
                                          'apps/order/alipay_public_key.pem')
        app_private_key_string = open(app_private_path).read()
        alipay_public_key_string = open(alipay_public_path).read()

        alipay = AliPay(
            appid="2021000117608619",
            app_notify_url=None,  # 默认回调url
            app_private_key_string=app_private_key_string,
            # 支付宝的公钥,验证支付宝回传消息使用,不是你自己的公钥,
            alipay_public_key_string=alipay_public_key_string,
            sign_type="RSA2",  # RSA 或者 RSA2
            debug=True,  # 默认False
            verbose=False,  # 输出调试数据
            config=AliPayConfig(timeout=15)  # 可选, 请求超时时间
        )

        # 如果你是 Python 3的用户,使用默认的字符串即可
        subject = "天天生鲜:" + order_id

        # 电脑网站支付,需要跳转到https://openapi.alipay.com/gateway.do? + order_string
        total_pay = order.total_price + order.transit_price
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,
            total_amount=str(total_pay),
            subject=subject,
            return_url="https://example.com",
            notify_url="https://example.com/notify"  # 可选, 不填则使用默认notify url
        )

        #返回应答
        pay_url = 'https://openapi.alipaydev.com/gateway.do?' + order_string
        return JsonResponse({'res': 0, 'pay_url': pay_url})
Exemple #4
0
def order_pay(order_id):
    '''发起支付宝支付'''

    user_id = g.user_id
    # 判断订单状态
    try:
        order = Order.query.filter(Order.id == order_id,
                                   Order.user_id == user_id,
                                   Order.status == "WAIT_PAYMENT").first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(error=RET.PARAMERR, errmsg="MYSQL异常")

    if order is None:
        return jsonify(error=RET.NODATA, errmsg="订单数据有误")

    # 私钥
    app_private_key_string = os.path.join(os.path.dirname(__file__),
                                          "keys/app_private_key.pem")
    app_private_key_string = open(app_private_key_string, "r").read()
    print(app_private_key_string)
    print("=======================================")
    print(type(app_private_key_string))

    # 公钥
    alipay_public_key_string = os.path.join(os.path.dirname(__file__),
                                            "keys/alipay_public_key.pem")
    alipay_public_key_string = open(alipay_public_key_string, "r").read()
    print(alipay_public_key_string)
    print("=======================================")
    print(type(alipay_public_key_string))
    # 创建支付宝sdk工具对象
    alipay = AliPay(
        appid="2021000118642729",
        app_notify_url=None,  # 默认回调url
        app_private_key_string=app_private_key_string,
        # 支付宝的公钥,验证支付宝回传消息使用,不是你自己的公钥,
        alipay_public_key_string=alipay_public_key_string,
        sign_type="RSA2",  # RSA 或者 RSA2
        debug=True,  # 默认False
        config=AliPayConfig(timeout=15)  # 可选, 请求超时时间
    )

    # 手机网站支付,需要跳转到https://openapi.alipay.com/gateway.do? + order_string
    # 沙箱环境:https: // openapi.alipaydev.com / gateway.do? + order_string
    order_string = alipay.api_alipay_trade_wap_pay(
        out_trade_no=order.id,  # 订单编号
        total_amount=str(order.amount / 100.0),  # 总金额
        subject="云猫爱家租房 %s" % order.id,  # 订单标题
        return_url="http://127.0.0.1:5000/payComplete.html",  # 返回的连接地址
        notify_url=None  # 可选, 不填则使用默认notify url
    )
    # 构建让用户跳转的支付链接
    pay_url = ALIPAY_URL + order_string
    return jsonify(error=RET.OK, errmsg="ok", data={"pay_url": pay_url})
Exemple #5
0
 def __init__(self):
     if not settings.USE_ALIPAY:
         return
     # NOTE 暂时只支持支付宝
     self.alipay = AliPay(
         app_notify_url="",
         appid=settings.ALIPAY_APP_ID,
         app_private_key_string=settings.ALIPAY_APP_PRIVATE_KEY_STRING,
         alipay_public_key_string=settings.ALIPAY_PUBLIC_KEY_STRING,
         config=AliPayConfig(timeout=3),
     )
Exemple #6
0
def get_payment():
    '''获取支付结果'''

    alipay_data = request.form.to_dict()

    # 对支付宝的数据进行分离  提取出支付宝的签名参数sign 和剩下的其他数据
    signature = alipay_data.pop("sign")

    app_private_key_string = os.path.join(os.path.dirname(__file__),
                                          "keys/app_private_key.pem")
    app_private_key_string = open(app_private_key_string, "r").read()

    # 公钥
    alipay_public_key_string = os.path.join(os.path.dirname(__file__),
                                            "keys/alipay_public_key.pem")
    alipay_public_key_string = open(alipay_public_key_string, "r").read()

    # 创建支付宝sdk工具对象
    alipay = AliPay(
        appid="2021000118642729",
        app_notify_url=None,  # 默认回调url
        app_private_key_string=app_private_key_string,
        # 支付宝的公钥,验证支付宝回传消息使用,不是你自己的公钥,
        alipay_public_key_string=alipay_public_key_string,
        sign_type="RSA2",  # RSA 或者 RSA2
        debug=True,  # 默认False
        config=AliPayConfig(timeout=15)  # 可选, 请求超时时间
    )

    # 借助工具验证参数的合法性
    # 如果确定参数是支付宝的,返回True,否则返回false
    result = alipay.verify(alipay_data, signature)

    if result:
        # 修改数据库的订单
        order_id = alipay_data.get("out_trade_no")
        trade_no = Order.query.get("trade_no")
        try:
            Order.query.filter_by(id=order_id).update({
                "status": "WAIT_COMMENT",
                "trade_no": trade_no
            })
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            db.session.rollback()

    return jsonify(error=RET.OK, errmsg="ok")
Exemple #7
0
 def __init__(self):
     from service.util.pay.pay_config import get_config
     config = get_config('支付宝当面付')
     self.APPID = config['APPID']
     self.app_private_key_string = '-----BEGIN RSA PRIVATE KEY-----\n' + config[
         'app_private_key'] + '\n-----END RSA PRIVATE KEY-----'
     self.alipay_public_key_string = '-----BEGIN PUBLIC KEY-----\n' + config[
         'alipay_public_key'] + '\n-----END PUBLIC KEY-----'
     self.alipay = AliPay(
         appid=self.APPID,
         app_notify_url=None,  # 默认回调url
         app_private_key_string=self.app_private_key_string,
         alipay_public_key_string=self.alipay_public_key_string,
         sign_type="RSA2",  # RSA 或者 RSA2
         debug=False,  # True后为开发环境,所有走dev接口,正式环境用False
         config=AliPayConfig(timeout=15)  # 可选, 请求超时时间
     )
Exemple #8
0
def alipay_ini():
    with open(os.path.join(current_app.root_path,
                           'trade/app_private_key.pem')) as f:
        app_private_key_string = f.read()
    with open(
            os.path.join(current_app.root_path,
                         'trade/alipay_public_key.pem')) as f:
        alipay_public_key_string = f.read()
    alipay = AliPay(
        appid="2021001146618124",
        app_notify_url="http://sorapage.com/alipay/callback",
        app_private_key_string=app_private_key_string,
        alipay_public_key_string=alipay_public_key_string,
        sign_type="RSA2",
        debug=False,  # 默认False
        verbose=False,  # 输出调试数据
        config=AliPayConfig(timeout=15)  # 可选, 请求超时时间
    )
    return alipay
Exemple #9
0
def order_pay(order_id):
    """发起支付宝支付"""
    user_id = g.user_id
    # user_id = 7
    # app_private_key_string = open("./keys\keysapp_private_key").read()
    # alipay_public_key_string = open("./keys/alipay_public_key").read()

    # 判断订单状态
    try:
        order = Order.query.filter(Order.id == order_id,
                                   Order.user_id == user_id,
                                   Order.status == "WAIT_PAYMENT").first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库异常")

    if order is None:
        return jsonify(errno=RET.NODATA, errmsg="订单数据有误")

    # 创建支付宝sdk的工具对象
    alipay = AliPay(
        appid="2016110400791021",
        app_notify_url=None,  # 默认回调url
        app_private_key_string=app_private_key_string,
        # 支付宝的公钥,验证支付宝回传消息使用,不是你自己的公钥,
        alipay_public_key_string=alipay_public_key_string,
        sign_type="RSA2",  # RSA 或者 RSA2
        debug=True,  # 默认False
        config=AliPayConfig(timeout=15)  # 可选, 请求超时时间
    )

    order_string = alipay.api_alipay_trade_wap_pay(
        out_trade_no=1111,  # 订单编号
        total_amount=str(8000000 / 100.0),  # 总金额
        subject=u"爱家租房 %s" % 1111,  # 订单标题
        return_url="http://www.baidu.com",  # 返回的连接地址
        notify_url=None  # 可选, 不填则使用默认notify url
    )
    pay_url = 'https://openapi.alipaydev.com/gateway.do?' + order_string
    print(pay_url)
    # 构建让用户跳转的支付连接地址
    return jsonify(errno=RET.OK, errmsg="OK", data={"pay_url": pay_url})
Exemple #10
0
    def get(self, request, order_id):
        # 必须是登录用户
        user = request.user
        #  获取order_id  url中有
        # 根据订单id查询订单信息
        # 为了更准确的进行查询,我们增加一些条件
        try:
            order = OrderInfo.objects.get(order_id=order_id, user=user)
        except:
            return JsonResponse({'code': 400, 'errmsg': "没有此订单"})
        # 创建支付宝对象
        # 通过文件形式来读取美多的私钥支付宝的公钥
        # 我们将公钥和私钥放在setting中 设置一个相对路径
        app_private_key_string = open(settings.APP_PRIVATE_KEY_PATH).read()
        alipay_public_key_string = open(settings.ALIPAY_PUBLIC_KEY_PATH).read()
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_string=app_private_key_string,
            # 支付宝的公钥,验证支付宝回传消息使用,不是你自己的公钥,
            alipay_public_key_string=alipay_public_key_string,
            sign_type="RSA2",  # RSA 或者 RSA2
            debug=False,  # 默认False
            config=AliPayConfig(timeout=15)  # 可选, 请求超时时间
        )
        # 我们通过电脑网址支付的方式来生成order_string
        subject = "测试订单"

        # 电脑网站支付,需要跳转到https://openapi.alipay.com/gateway.do? + order_string
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,  # 美多商城的订单id
            total_amount=str(order.total_amount),  # 订单总金额  类型转换为 str
            subject=subject,
            return_url=settings.ALIPAY_RETURN_URL,  # 支付成功之后,最终要跳转会美多
            # notify_url="https://example.com/notify"  # 可选, 不填则使用默认notify url
        )
        # 5. 拼接url
        alipay_url = 'https://openapi.alipaydev.com/gateway.do?' + order_string

        # 6. 返回支付url
        return JsonResponse({'code': 0, 'alipay_url': alipay_url})
Exemple #11
0
def notify_response():
    """支付宝支付结果异步通知处理"""
    data = request.form.to_dict()
    # sign 不能参与签名验证
    signature = data.pop("sign")

    app_private_key_string = open(
        os.path.join(
            current_app.BASE_DIR,
            "application/apps/users/keys/app_private_key.pem")).read()
    alipay_public_key_string = open(
        os.path.join(current_app.BASE_DIR,
                     "application/apps/users/keys/app_public_key.pem")).read()

    alipay = AliPay(
        appid=current_app.config.get("ALIPAY_APP_ID"),
        app_notify_url=None,  # 默认回调url
        app_private_key_string=app_private_key_string,
        # 支付宝的公钥,验证支付宝回传消息使用,不是你自己的公钥,
        alipay_public_key_string=alipay_public_key_string,
        sign_type=current_app.config.get("ALIPAY_SIGN_TYPE"),
        debug=False,  # 默认False
        config=AliPayConfig(timeout=15)  # 可选, 请求超时时间
    )

    # verify
    success = alipay.verify(data, signature)
    if success and data["trade_status"] in ("TRADE_SUCCESS", "TRADE_FINISHED"):
        """充值成功"""
        out_trade_number = data["out_trade_no"]
        recharge = Recharge.query.filter(
            Recharge.out_trade_number == out_trade_number).first()
        if recharge is None:
            return "fail"
        recharge.status = True
        user = User.query.get(recharge.user_id)
        if user is None:
            return "fail"
        user.money += recharge.money
        db.session.commit()
    return "success"  # 必须只能是success
Exemple #12
0
# Create your views here.

#創建對接支付寶的SDK對象
alipay = AliPay(
    appid=settings.ALIPAY_APPID,
    #默認回調URL:異步通知
    app_notify_url=None,
    #商城加密私鑰
    app_private_key_string=app_private_key_string,
    alipay_public_key_string=alipay_public_key_string,
    #解密支付寶數據的支付寶公鑰
    sign_type="RSA2",
    debug=settings.ALIPAY_DEBUG,
    #請求超時時間
    config=AliPayConfig(timeout=15),
)


class PaymentStatusView(LoginRequiredJsonMixin, View):
    """保存支付訂單狀態"""
    def get(self, request):

        #獲取所有查詢字符串參數
        query_dict = request.GET
        #將查詢字符串參數轉字典類型
        data = query_dict.dict()
        #移除參數sign後簽名數據
        signature = data.pop('sign')
        #使用SDK對象調用驗證接口函數進行驗證
        success = alipay.verify(data, signature)
Exemple #13
0
app_private_key_string = '-----BEGIN RSA PRIVATE KEY-----\n' + config[
    'app_private_key'] + '\n-----END RSA PRIVATE KEY-----'
alipay_public_key_string = '-----BEGIN PUBLIC KEY-----\n' + config[
    'alipay_public_key'] + '\n-----END PUBLIC KEY-----'

# 注意加上开头结尾

alipay = AliPay(
    appid=config['APPID'],
    app_notify_url=None,  # 默认回调url
    app_private_key_string=app_private_key_string,
    # 支付宝的公钥,验证支付宝回传消息使用,不是你自己的公钥,
    alipay_public_key_string=alipay_public_key_string,
    sign_type="RSA2",  # RSA 或者 RSA2
    debug=False,  # True后为开发环境,所有走dev接口,正式环境用False
    config=AliPayConfig(timeout=15)  # 可选, 请求超时时间
)

# #本地开发环境测试
# app_private_key_string = '-----BEGIN RSA PRIVATE KEY-----\n'+'MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCqWmxsyPLwRmZHwoLYlUJXMF7PATKtvp7BrJfwLbxwrz6I48G11HpPPyAoNynwAMG7DCXjVX76NCbmfvvPqnbk09rNRULqGju8G6NkQTbLfDjhJs+CE8kdIs89btxqDG70ebePiZTGpQngPLfrziKDOhRfXkA5qRPImbC+PUXiXq9qvkp9Yu/8IYjyxUpNBNjZuTK+fTjSI0RCt7eE+wR0KqpNIzot1q/ds1KTIYmJQM5tEFie4BK0pDtGiIs/VrUG8PTPqLyzEyIMy1N75olUWAiGrk0USqiieP3TYj0PdlQDX2T14DOwMkl5Rjvt7Knc+WGdolPIBssUX1wTE+J7AgMBAAECggEAWpRP+Jv0yRu1wMxFRKJArxmSH+GUL9wej/6Un2nCO+yChMkNtAAxtLdtAtUqIGpWmH2CG9nW9XULhh3ZCPer1kprmiAMz2t5fbD4dRNT7miz2cwIJDMfCbX7mb+7xUutJ6Mcnl7aU7FnierfJKvrn/ke4gK8haxIT66g0tbDtPQhYnGPawyM+gqFulaMBcuqH0naAIq5ZBWHkKuuwJ1SD6yGrWgHdq3Kt2pE8b9yjfdUl15IeW0rszXG6fTika9WX6qaulyoGAAZdjiXED+mbRyqZA3jq7RI38qBP9+/jAb+fdwE8EwqnpPvfGHMBdkREOXK0kzRU8rpd9GbH7INaQKBgQDwpuW+bK/qxKx3BSAXL98f0J2I7YVuk0EFCStGoxnzWRv0yvL0QEDwN+QPiVMmcVQcr79mW5zTBkd4vmr3ud+v1f/X6UPI82kQhZlVWry8LEnisPlZuE0E/EaJrLgF7z4l3ItzCVi8IfpgizPcCYSz/vY49a5W34eKjXHWUB1jDwKBgQC1N8PgGKI2LRDaJeqt5Ef6yyYSMOgVe0WSqAlgyMECb1pjmMBjcNG1AFE/FfgNu4thOaXIogElGVoQFvA5GuJQY48HOJNgx3Ua2SxiowcXkAN0gIm4FY+ozkp7xhizvLVfsmX+MKqPtl6nggiWETJJyvMQnjMgKLmSvhsopMwZ1QKBgGV36az2BOK3VITGq3Y7YBf5DUN76uPpwOOPryiUgs+hhfEcVX55TSg8WLPYUjAGXtHNpKVTAXfU0PPvTgjv3Yo1cC+okkU7pNQrkLB1lti8z9Z+ilSzKf5tJIzOP7V437p1GHNDwJ9qsDhe2VnwxXxjh4wSwxSsIWlhJFuZ4hovAoGAFgm8Fmqof3InlH/79D3IyyUdciTkdIhTQ6yPx2dioYstMOOIsg8sUZjCSKvBSNo/7wj1slqRTROyMja37Bnq39/bqwMkWSaohSVYEn7FBAaNhQOEvBBTMjI0OK00n9cZL5QgdzMv6t5A0JottSJOPU8jFChJC2Yoe0IHR4ATGikCgYB2smi7/ptKiGdwmiuUHsF/U3jfjpHyHwLrXjoSU+mwV+GjqcdbtkSP1suGjN8tcdbFvLSCRX/IRdFHYJeuPUXQtZtiC431+upasbEiJ1xZ2KcK3lKf0mOn10kPD5QC7mmsfmjz4cw9cSrBjmcWGXeIwIXPLhOAAIzpHqy8oP/F/g=='+'\n-----END RSA PRIVATE KEY-----'

# alipay_public_key_string = '-----BEGIN PUBLIC KEY-----\n'+'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4AHTfGleo8WI3qb+mSWOjJRyn6Vh8XvO6YsQmJjPnNKhvACHTHcU+PCUWUKZ54fSVhMkFZEQWMtAGeOt3lGy3pMBS96anh841gxJc2NUljU14ESXnDn4QdVe4bosmYvfko46wfA0fGClHdpO8UUiJGLj1W5alv10CwiCrYRDtx93SLIuQgwJn4yBC1/kE/KENOaWaA45dXIQvKh2P0lTbm0AvwYMVvYB+eB1GtOGQbuFJXUxWaMa0byTo9wSllhgyiIkOH+HJ9oOZIweGlsrezeUUdr3EEX97k25LdnUt/oQK8FIfthexfWZpTDDlHqmI7p6gCtRVDJenU4sxwpEyQIDAQAB'+'\n-----END PUBLIC KEY-----'

# # 注意加上开头结尾

# alipay = AliPay(
#     appid="2016091800537528",
#     app_notify_url=None,  # 默认回调url
#     app_private_key_string=app_private_key_string,
#     # 支付宝的公钥,验证支付宝回传消息使用,不是你自己的公钥,
#     alipay_public_key_string=alipay_public_key_string,
Exemple #14
0
    def post(self, request):
        '''查询支付结果'''
        # 判断登录
        user = request.user
        if not user.is_authenticated:
            return JsonResponse({'res': 1, 'error': '用户未登录'})
        # 接收参数
        order_id = request.POST.get('order_id')
        # 校验参数
        if not order_id:
            return JsonResponse({'res': 2, 'error': '订单无效'})
        try:
            order = OrderInfo.objects.get(order_id=order_id,
                                          user=user,
                                          pay_method=3,
                                          order_status=1)
        except OrderInfo.DoesNotExist:
            return JsonResponse({'res': 3, 'error': '订单无效'})
        # 业务处理,调用支付接口
        # 配置地址
        app_private_path = os.path.join(settings.BASE_DIR,
                                        'apps/order/app_private_key.pem')
        alipay_public_path = os.path.join(settings.BASE_DIR,
                                          'apps/order/alipay_public_key.pem')
        app_private_key_string = open(app_private_path).read()
        alipay_public_key_string = open(alipay_public_path).read()

        alipay = AliPay(
            appid="2021000117608619",
            app_notify_url=None,  # 默认回调url
            app_private_key_string=app_private_key_string,
            # 支付宝的公钥,验证支付宝回传消息使用,不是你自己的公钥,
            alipay_public_key_string=alipay_public_key_string,
            sign_type="RSA2",  # RSA 或者 RSA2
            debug=True,  # 默认False
            verbose=False,  # 输出调试数据
            config=AliPayConfig(timeout=15)  # 可选, 请求超时时间
        )

        # 调用支付宝的交易查询接口
        import ssl
        ssl._create_default_https_context = ssl._create_unverified_context
        while True:
            response = alipay.api_alipay_trade_query(order_id)

            # response = {
            #         "trade_no": "2017032121001004070200176844", # 支付宝交易号
            #         "code": "10000", # 接口调用是否成功
            #         "invoice_amount": "20.00",
            #         "open_id": "20880072506750308812798160715407",
            #         "fund_bill_list": [
            #             {
            #                 "amount": "20.00",
            #                 "fund_channel": "ALIPAYACCOUNT"
            #             }
            #         ],
            #         "buyer_logon_id": "csq***@sandbox.com",
            #         "send_pay_date": "2017-03-21 13:29:17",
            #         "receipt_amount": "20.00",
            #         "out_trade_no": "out_trade_no15",
            #         "buyer_pay_amount": "20.00",
            #         "buyer_user_id": "2088102169481075",
            #         "msg": "Success",
            #         "point_amount": "0.00",
            #         "trade_status": "TRADE_SUCCESS", # 支付结果
            #         "total_amount": "20.00"
            # }

            code = response.get('code')

            if code == '10000' and response.get(
                    'trade_status') == 'TRADE_SUCCESS':
                # 支付成功
                # 获取支付宝交易号
                trade_no = response.get('trade_no')
                # 更新订单状态
                order.trade_no = trade_no
                order.order_status = 4  # 待评价
                order.save()
                # 返回结果
                return JsonResponse({'res': 0, 'message': '支付成功'})
            elif code == '40004' or (code == '10000'
                                     and response.get('trade_status')
                                     == 'WAIT_BUYER_PAY'):
                # 等待买家付款
                # 业务处理失败,可能一会就会成功
                import time
                time.sleep(5)
                continue
            else:
                # 支付出错
                return JsonResponse({'res': 4, 'errmsg': '支付失败'})