Пример #1
0
def save_order_payment_result():
    """
    保存订单支付结果
    :return:
    """
    alipay_dict = request.form.to_dict()

    alipay_sign = alipay_dict.pop("sign")

    alipay_client = Alipay(
        appid='2016092500594612',
        app_notify_url=None,
        app_private_key_path=os.path.join(os.path.dirname(__file__),
                                          "keys/app_private_key.pem"),
        alipay_public_key_path=os.path.join(os.path.dirname(__file__),
                                            "keys/alilay_public_key.pem"),
        sign_type='RSA2',
        debug=True)

    result = alipay_client.verify(alipay_dict, alipay_sign)

    if request:
        order_id = alipay_dict.get("out_trade_no")
        trade_no = alipay_dict.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(code=RET.OK, msg="OK")
Пример #2
0
def save_order_payment_result():
    """保存订单支付结果"""
    alipay_dict = request.form.to_dict()

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

    # 创建支付宝sdk的工具对象
    alipay_client = AliPay(
        appid="2016081600258081",
        app_notify_url=None,  # 默认回调url
        app_private_key_path=os.path.join(os.path.dirname(__file__), "keys/app_private_key.pem"),  # 私钥
        alipay_public_key_path=os.path.join(os.path.dirname(__file__), "keys/alipay_public_key.pem"),
        # 支付宝的公钥,验证支付宝回传消息使用,不是你自己的公钥,
        sign_type="RSA2",  # RSA 或者 RSA2
        debug=True  # 默认False
    )

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

    if result:
        # 修改数据库的订单状态信息
        order_id = alipay_dict.get("out_trade_no")
        trade_no = alipay_dict.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(errno=RET.OK, errmsg="OK")
Пример #3
0
def pay(request):
    package_id = request.GET.get("setPackId")
    pay_type = request.GET.get('type')
    if package_id is not None:
        order_id = str(int(time.time() * 1000))
        package = Package.objects.get(id=package_id)
        if pay_type == "0":
            alipay = Alipay(pid='2088021435732027',
                            key='g5eerb3z111h75kpo3mfa1cibacbloo6',
                            seller_email='*****@*****.**')
            url = alipay.create_direct_pay_by_user_url(
                out_trade_no=order_id,
                subject=package.name + u" - 亚马逊辅助工具",
                total_fee=package.price,
                return_url=domain + '/alipay/return-url',
                notify_url=domain + '/alipay/notify-url')
            Order.objects.create(order_id=int(order_id),
                                 createuser=request.user,
                                 package=package,
                                 pay_method=pay_type)
            return HttpResponseRedirect(url)
    else:
        template = loader.get_template('404.html')
        context = {}
        return HttpResponse(template.render(context, request))
Пример #4
0
    def post(self, request, *args, **kwargs):

        account = request.POST.get('account')
        print account
        your_alipay_pid = '2088201436263456'
        your_alipay_key = 'zrm0gapvir2dfrjmixcis2dfntxoy3ja'
        alipay = Alipay(pid=your_alipay_pid, key=your_alipay_key, seller_email='*****@*****.**')
        print alipay
        trade_no = self.make_time_id(10)
        print trade_no
        params = dict(
            out_trade_no=trade_no,
            subject=u'象云科技',
            total_fee='%.2f' % float(account),
            return_url='http://122.115.43.61:9999/alipay/alipay_return_url',
            notify_url='http://122.115.43.61:9999/alipay/alipay_notify_url',
        )
        alipay_url = alipay.create_direct_pay_by_user_url(**params)
        print alipay_url
        # return HttpResponse(alipay_url)
        new_html = """
            <script type='text/javascript'>
                window.open('%(alipay_url)s');
            </script>
        """ % {'alipay_url': alipay_url}
        # return HttpResponse(new_html)
        return HttpResponseRedirect(alipay_url)
Пример #5
0
def payment(request, id):
    item = get_object_or_404(Booking, id=id)
    fee = item.hour * 35
    fee_uni = item.hour * 3500
    if item.book_type == 1:
        fee = item.hour * 50
        fee_uni = item.hour * 5000
    url = lambda path: "".join(["http://", get_current_site(request).domain, path])
    if request.method == "POST":
        data = request.POST.copy()
        if data.get("pay_method", False) == "3":
            return_url = url(reverse("userena_profile_edit", args=[item.booker.username]))
            notify_url = "http://www.merryservices.com/unipay_notify_endpoint/%s/" % (item.id)
            date = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
            msg = (
                "pickupUrl=%s&receiveUrl=%s&version=v1.0&signType=0&merchantId=109000914110001&payerName=%s&payerEmail=%s&orderNo=NO%s&orderAmount=%s&orderDatetime=%s&productName=merryservices&payType=0&key=1234567890"
                % (notify_url, return_url, item.booker.username, item.booker.email, date, str(fee_uni)[:-2], date)
            )
            m = md5.new()
            m.update(msg)
            para = m.hexdigest().upper()
            url = "http://112.65.178.184:443/gateway/index.do?" + msg + "&signMsg=" + para
            return render_to_response("booking/unipay.html", {"url": url})
        if data.get("pay_method", False) == "4":
            alipay = Alipay(pid=settings.ALIPAY_PID, key=settings.ALIPAY_KEY, seller_email=settings.ALIPAY_SELLER_EMAIL)
            url = alipay.create_direct_pay_by_user_url(
                out_trade_no=item.id,
                subject="Merry clean service",
                total_fee=fee,
                return_url=url(reverse("userena_profile_edit", args=[item.booker.username])),
                notify_url=url("/alipay_notify_endpoint/"),
            )

            return render_to_response("booking/alipay.html", {"url": url})
    return HttpResponseBadRequest()
Пример #6
0
    def get(self, request, order_id):
        user = request.user
        try:
            order = OrderInfo.objects.get(
                order_id=order_id,
                user=user,
                pay_method=OrderInfo.PAY_METHODS_ENUM["ALIPAY"],
                status=OrderInfo.ORDER_STATUS_ENUM["UNPAID"],
            )
        except OrderInfo.DoesNotExist:
            return Response({'meaaage': '订单错误'},
                            status=status.HTTP_400_BAD_REQUEST)

        alipay = Alipay(appid="2016100100641406",
                        app_notify_url=None,
                        app_private_key_path=os.path.join(
                            os.path.dirname(os.path.abspath(__file__)),
                            'app_private_key.pem'),
                        alipay_public_key_path=os.path.join(
                            os.path.dirname(os.path.abspath(__file__)),
                            'alipay_public_key.pem'),
                        sign_type="RSA2",
                        debug=True)

        sum_price = order.total_amount
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,
            total_amount=str(sum_price),
            subject='美多商城',
            return_url='http://www.meiduo.site:8080/pay_success.html',
            notify_url=None  # this is optional
        )
        alipay_url = 'https://openapi.alipaydev.com/gateway.do?' + order_string

        return Response({'alipay_url': alipay_url})
Пример #7
0
	def post(self,request):
		# 用户是否登录
		user = request.user
		if not user.is_authenticated():
			return JsonResponse({'res':0,'errmsg':'用户未登陆'})

		# 接收参数
		order_id = request.POST.get('order_id')

		# 校验参数
		if not order_id:
			return JsonResponse({'res':1,'errmsg':'无效的订单id'})
		
		try:  #查出的订单必须要符合id相同,用户相同,支付方式为3,订单状态为:未支付
			order = OrderInfo.objects.get(order_id = order_id,
											user = user,
											pay_method = 3,
											order_status = 1)
		except OrderInfo.DoesNotExist:
			return JsonResponse({'res':1,'errmsg':订单错误})

		# 业务处理:使用python sdk调用支付宝的支付接口


		# 初始化
		alipay = Alipay(
			appid = "2016093000628658", #自己沙箱中的APPID
			app_notify_url = None, #默认的回调url
			app_private_key_path = os.path.join(settings.BASE_DIR,'apps/order/app_private_key.pem'),
			alipay_public_key_path = os.path.join(settings.BASE_DIR,'apps/order/alipay_public_key.pem'),
			sign_type = "RSA2",  #RSA或者RSA2
			debug = "True"  #沙箱模式就是调试模式
			)

		# 调用支付宝的交易查询接口(可传两个参数,out_trade_no订单号;trade_no,支付宝交易号,二者只需一个即可)
		while True:
			response = alipay.api_alipay_trade_query(order_id)
			# response是一个字典

			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':3,'errmsg':'支付成功'})
			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':'支付失败'})
Пример #8
0
    def alipayPayment2(self,
                       is_prod_server,
                       request_id,
                       user_email,
                       amount,
                       product,
                       point_for_use=0,
                       promo_type='',
                       promo_code=''):

        host_name = ""
        if is_prod_server == False:
            host_name = "http://ciceron.xyz:5000"
        else:
            host_name = "http://ciceron.me:5000"

        postprocess_endpoint = self._organizePostprocessApiAddress(
            product, request_id)
        postprocess_api = "{}/{}".format(host_name, postprocess_endpoint)

        order_no = self._orderNoGenerator()
        param_dict = {
            'payment_platform': 'alipay',
            'product': product,
            'request_id': request_id,
            'status': 'success',
            'user_email': user_email,
            'amount': amount,
            'point_for_use': point_for_use,
            'promo_type': promo_type,
            'promo_code': promo_code,
            'ciceron_order_no': order_no
        }
        return_url = ciceron_lib.dictToUrlParam(postprocess_api, **param_dict)

        alipay_obj = Alipay(pid='111',
                            key='<be_secret>',
                            seller_email='*****@*****.**')
        params = {
            'subject': '诗谐论翻译'.decode('utf-8'),
            'out_trade_no': order_no,
            'total_fee': '%.2f' % amount,
            'currency': 'USD',
            'quantity': '1',
            'return_url': return_url
        }

        provided_link = None
        try:
            if pay_by == 'web':
                provided_link = alipay_obj.create_forex_trade_url(**params)
            elif pay_by == 'mobile':
                provided_link = alipay_obj.create_forex_trade_wap_url(**params)
        except:
            return False, None

        return True, provided_link
Пример #9
0
    def get(self, request):
        """查询订单信息:如果支付成功,需要修改订单状态和记录支付宝维护的订单id,如果失败,返回失败信息"""

        # 获取订单id
        order_id = request.GET.get('order_id')

        # 校验订单id
        if not order_id:
            return JsonResponse({'code': 2, 'message': '没有订单id'})

        # 获取订单信息:状态是待支付,支付方式是支付宝
        try:
            order = OrderInfo.objects.get(order_id=order_id, user=request.user,
                                          status=OrderInfo.ORDER_STATUS_ENUM["UNPAID"],
                                          pay_method=OrderInfo.PAY_METHODS_ENUM["ALIPAY"])

        except OrderInfo.DoesNotExist:
            return JsonResponse({'code': 3, 'message': '订单错误'})

        # 创建用于支付宝支付的对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            # 自己生产的私钥
            app_private_key_path=settings.APP_PRIVATE_KEY_PATH,
            # 支付宝的公钥,验证支付宝回传消息使用,不是你自己的公钥,
            alipay_public_key_path=settings.ALIPAY_PUBLIC_KEY_PATH,
            sign_type="RSA2",  # RSA 或者 RSA2
            debug=True  # 默认False 配合沙箱模式使用
        )

        # 一直查询知道错误或者成功为止
        while True:

            # 调用查询接口 : response 封装了查询之后的结果,是个字典. code trade_status  trade_no
            response = alipay.api_alipay_trade_query(order_id)

            # 读取判断是否失败的数据
            code = response.get('code')
            trade_status = response.get('trade_status')

            # 判断查询之后的结果
            if code == '10000' and trade_status == 'TRADE_SUCCESS':
                # 支付成功:需要获取支付宝维护的订单id,存储到OrderInfo.改变订单的支付状态为待评价
                order.trade_id = response.get('trade_no')
                order.status = OrderInfo.ORDER_STATUS_ENUM['UNCOMMENT']
                order.save()

                return JsonResponse({'code': 0, 'message': '支付成功'})

            elif code == '40004' or (code == '10000' and trade_status == 'WAIT_BUYER_PAY'):
                # 业务处理失败,但是不能宣告错误,比如系统繁忙
                continue
            else:
                # 支付失败
                return JsonResponse({'code':4, 'message':'支付失败'})
Пример #10
0
	def post(self, request):
		'''订单支付'''

		# 用户是否登录
		user = request.user
		if not user.is_authenticated():
			return JsonResponse({'res':0,'errmsg':'用户未登陆'})

		# 接收参数
		order_id = request.POST.get('order_id')

		# 校验参数
		if not order_id:
			return JsonResponse({'res':1,'errmsg':'无效的订单id'})
		
		try:  #查出的订单必须要符合id相同,用户相同,支付方式为3,订单状态为:未支付
			order = OrderInfo.objects.get(order_id = order_id,
											user = user,
											pay_method = 3,
											order_status = 1)
		except OrderInfo.DoesNotExist:
			return JsonResponse({'res':1,'errmsg':订单错误})

		# 业务处理:使用python sdk调用支付宝的支付接口


		# 初始化
		alipay = Alipay(
			appid = "2016093000628658", #自己沙箱中的APPID
			app_notify_url = None, #默认的回调url
			app_private_key_path = os.path.join(settings.BASE_DIR,'apps/order/app_private_key.pem'),
			alipay_public_key_path = os.path.join(settings.BASE_DIR,'apps/order/alipay_public_key.pem'),
			sign_type = "RSA2",  #RSA或者RSA2
			debug = "True"  #沙箱模式就是调试模式
			)
		# 调用支付接口
		# 电脑网站支付,需要跳转到https://openapi.alipaydev.com/gateway.do? + order_string
		total_pay = order.total_price + order.transit_price  #Decimal类型,无法序列化
		order_string = alipay.api_alipay_trade_page_pay(
			out_trade_no = order_id,#订单号
			total_amount = str(total_pay), #原本是Decimal数据类型,无法序列化Json形式,只能先转化为str
			subject = '天天生鲜%s'%order_id, #标题
			return_url = None,
			notify_url = None #都不填,因为我们现在没有公网ip
			)

		# 返回应答
		pay_url = 'https://openapi.alipaydev.com/gateway.do?' + order_string
		return JsonResponse({'res':3,'pay_url':pay_url})
Пример #11
0
def alipay_notify(request):
    """ Notify callback for alipay """
    alipay = Alipay(pid=settings.ALIPAY_PID, key=settings.ALIPAY_KEY, seller_email=settings.ALIPAY_SELLER_EMAIL)
    if alipay.verify_notify(**dict(request.POST.items())):
        if request.POST.get("trade_status") in ["WAIT_SELLER_SEND_GOODS", "TRADE_SUCCESS"]:
            order = Booking.objects.get(id=request.POST.get("out_trade_no"))
            order.status = 5
            order.pay_method = 2
            order.save()
            create_sms(order.booker, order)
            create_mail_book_confirm(order.booker, order)
            internal_book_confirm(order.booker, order)
            return HttpResponse("success")
        else:
            print "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
    return HttpResponse("failure")
Пример #12
0
    def post(self, request):
        """创建alipay对象,调用支付接口"""
        # 获取订单id
        order_id = request.POST.get('order_id')

        # 校验订单id
        if not order_id:
            return JsonResponse({'code':2, 'message':'没有订单id'})

        # 获取订单信息:状态是待支付,支付方式是支付宝
        try:
            order = OrderInfo.objects.get(order_id=order_id, user=request.user,
                                          status=OrderInfo.ORDER_STATUS_ENUM["UNPAID"],
                                          pay_method=OrderInfo.PAY_METHODS_ENUM["ALIPAY"])

        except OrderInfo.DoesNotExist:
            return JsonResponse({'code': 3, 'message': '订单错误'})

        # 创建用于支付宝支付的对象
        alipay = AliPay(
            appid = settings.ALIPAY_APPID,
            app_notify_url = None,  # 默认回调url
            # 自己生产的私钥
            app_private_key_path = settings.APP_PRIVATE_KEY_PATH,
            # 支付宝的公钥,验证支付宝回传消息使用,不是你自己的公钥,
            alipay_public_key_path = settings.ALIPAY_PUBLIC_KEY_PATH,
            sign_type = "RSA2",  # RSA 或者 RSA2
            debug = True  # 默认False 配合沙箱模式使用
        )

        # 电脑网站支付,需要跳转到https://openapi.alipaydev.com/gateway.do? + order_string
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no = order_id,
            total_amount = str(order.total_amount),  # 将浮点数转成字符串
            subject = '天天生鲜',
            return_url = None,
            notify_url = None  # 可选, 不填则使用默认notify url
        )

        # 生成url:让用户进入支付宝页面的支付网址
        url = settings.ALIPAY_URL + '?' + order_string

        # 响应结果
        return JsonResponse({'code':0, 'message':'支付成功', 'url':url})
Пример #13
0
def order_pay(order_id):
    """发起支付宝支付"""

    # 获取用户的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.errer(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库异常')

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


    # 创建支付宝sdk的工具对象
    alipay_client = Alipay(
        appid="2016101000651363",
        app_notify_url=None,
        app_private_key_path=os.path.join(os.path.dirname(__file__), "keys/private_key.pem"),
        alipay_public_key_path=os.path.join(os.path.dirname(__file__), "keys/zfb_public_key.pem"),
        sign_type="RSA2",
        debug=True
    )

    # 手机网站支付,需要跳转到https://openhome.alipaydev.com/gateway.do+order_string

    order_string = alipay_client.api_alipay_trade_way_pay(
        out_trade_no=order.id,
        total_amount=str(order.amount/100.0),
        subject="爱家租房 %s" % order.id,
        return_url="127.0.0.1:5000/orders.html",
        notify_url=None
    )

    # 构建让用户跳转的支付链接地址
    pay_url = constants.ALIPAY_URL_PREFIX + order_string
    return jsonify(errno=RET.OK, errmsg="OK", data={"pay_url": pay_url})
Пример #14
0
    def put(self, request):
        data = request.query_params.dict()
        signature = data.pop("sign")

        alipay = Alipay(appid="2016100100641406",
                        app_notify_url=None,
                        app_private_key_path=os.path.join(
                            os.path.dirname(os.path.abspath(__file__)),
                            'app_private_key.pem'),
                        alipay_public_key_path=os.path.join(
                            os.path.dirname(os.path.abspath(__file__)),
                            'alipay_public_key.pem'),
                        sign_type="RSA2",
                        debug=True)

        success = alipay.verify(data, signature)

        if not success:
            return Response({'message': '非法请求'},
                            status=status.HTTP_403_FORBIDDEN)

        # 获取订单编号和支付宝流水号
        order_id = data.get('out_trade_no')
        trade_id = data.get('trade_no')

        # 校验订单id(order_id)
        try:
            order = OrderInfo.objects.get(
                order_id=order_id,
                user=request.user,
                status=OrderInfo.ORDER_STATUS_ENUM['UNPAID'])
        except OrderInfo.DoesNotExist:
            return Response({'message': '订单信息有误'},
                            status=status.HTTP_400_BAD_REQUEST)

        # 更新订单的支付状态
        order.status = OrderInfo.ORDER_STATUS_ENUM['UNSEND']
        order.save()

        return Response({'trade_id': trade_id})
Пример #15
0
def AlipayView(request):
    order_number = request.GET.get('order_number')
    order_total = request.GET.get('total')

    # 实例化支付
    alipay = Alipay(appid='2016101200667735',
                    app_notify_url=None,
                    app_private_key_string=alipay_private_key_string,
                    alipay_public_key_string=alipay_public_key_string,
                    sign_type='RSA2')
    # 实例化订单
    order_string = alipay.api_alipay_trade_page_pay(
        out_trade_no=str(order_number),
        total_amount=str(order_total),
        subject='服装',
        return_url="/Buyer/pay_result/",
        notify_url="/Buyer/pay_result/",
    )  # 网页支付订单

    # 拼接收款地址=支付宝网关+订单返回参数
    result = "https://openapi.alipaydev.com/gateway.do?" + order_string
    return HttpResponseRedirect(result)
Пример #16
0
def order_pay(order_id):
    """
    发起支付宝支付
    :return:
    """

    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(RET.DBERR, "数据库异常")

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

    alipay_client = Alipay(
        appid='2016092500594612',
        app_notify_url=None,
        app_private_key_path=os.path.join(os.path.dirname(__file__),
                                          "keys/app_private_key.pem"),
        alipay_public_key_path=os.path.join(os.path.dirname(__file__),
                                            "keys/alilay_public_key.pem"),
        sign_type='RSA2',
        debug=True)

    order_string = alipay_client.api_alipay_trade_wap_pay(
        out_trade_no=order.id,
        total_amount=str(order.amount / 100.0),
        subject=u"租房 %s" % order.id,
        return_url="http://127.0.0.1:5000/payComplete.html",
        notify_url=None)

    pay_url = const.ALIPAY_URL_PREFIX + order_string
    return jsonify(code=RET.OK, msg="OK", data={"pay_url": pay_url})
Пример #17
0
    def post(self,request):
        user = request.user
        if not user.is_authenticated():
            return redirect(reverse('user:login'))

        ordid_after = request.POST.get('order_id')
        if not ordid_after:
            return JsonResponse({'info':'订单不存在'})
        try:
            Order.objects.get(order_id=ordid_after,user=user,pay_style=1,states=0)
        except Exception as e:
            return JsonResponse({'indo':'订单不存在'})
        # alipay = Alipay(
        #     appid=''
        #     app_notify
        # )
        alipay = Alipay(
            appid='2016091400508206',
            app_notify_url=None,  # 默认回调url
            app_private_key_path=os.path.join(settings.BASE_DIR, "user/orderform/app_private_key.pem"),
            alipay_public_key_path=os.path.join(settings.BASE_DIR, "user/orderform/app_public_key.pem"),
        # 支付宝的公钥,验证支付宝回传消息使用,不是你自己的公钥,
            sign_type="RSA2",  # RSA 或者 RSA2
            debug=True  # 默认False  配合沙箱模式使用
            )

        ord_cost = order.tprice
        order_sit=alipay.api_alipay_trade_page_pay(
            subject='hsrsc',
            out_trade_no=ordid_after,
            total_amount=ord_cost,
            return_url=None,
            notify_url=None,
        )
        # alipay.api_alipay_trade_page_pay这里应该有个结果返回接口
        url = 'https://openapi.alipaydev.com/gateway.do'+ordid_after
        return JsonResponse({'info':'','cost_url':url})
Пример #18
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(errno=RET.DBERR, errmsg="数据库异常")

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

    # 创建支付宝sdk的工具对象
    alipay_client = AliPay(
        appid="2016081600258081",
        app_notify_url=None,  # 默认回调url
        app_private_key_path=os.path.join(os.path.dirname(__file__), "keys/app_private_key.pem"),  # 私钥
        alipay_public_key_path=os.path.join(os.path.dirname(__file__), "keys/alipay_public_key.pem"),  # 支付宝的公钥,验证支付宝回传消息使用,不是你自己的公钥,
        sign_type="RSA2",  # RSA 或者 RSA2
        debug=True  # 默认False
    )

    # 手机网站支付,需要跳转到https://openapi.alipaydev.com/gateway.do? + order_string
    order_string = alipay_client.api_alipay_trade_wap_pay(
        out_trade_no=order.id,  # 订单编号
        total_amount=str(order.amount/100.0),   # 总金额
        subject=u"爱家租房 %s" % order.id,  # 订单标题
        return_url="http://127.0.0.1:5000/payComplete.html",  # 返回的连接地址
        notify_url=None  # 可选, 不填则使用默认notify url
    )

    # 构建让用户跳转的支付连接地址
    pay_url = constants.ALIPAY_URL_PREFIX + order_string
    return jsonify(errno=RET.OK, errmsg="OK", data={"pay_url": pay_url})
Пример #19
0
def return_alipay_action(request):
    payment = get_object_or_404(Payment, label='alipay')
    alipay = Alipay(
        pid=payment.pid,
        key=payment.key,
        seller_email=payment.seller_email)
    if alipay.verify_notify(**request.GET.dict()):
        # this is a valid notify, code business logic here
        number = request.GET.get('out_trade_no')
        dpo = get_object_or_404(DirectPaymentOrder, number=number)
        fee = int(float(request.GET.get('total_fee')))
        if dpo.money == fee:
            dpo.pay_number = request.GET.get('trade_no')
            dpo.pay_status = request.GET.get('trade_status')
            dpo.buyer_id = request.GET.get('buyer_id')
            dpo.buyer_email = request.GET.get('buyer_email')
            dpo.notify_id = request.GET.get('notify_id')
            dpo.paid_date = timezone.now()
            dpo.status = 'paid'
            dpo.save()
        return True
    else:
        # this is a invalid notify
        return False
Пример #20
0
def create_alipay():
    """
    创建支付宝对象
    :return: 支付宝对象
    """
    alipay = Alipay(
        appid=settings.ALIPAY_APPID,
        # 回调地址
        app_notify_url=None,
        # 公钥路径
        alipay_public_key_path=settings.ALIPAY_PUBLIC_KEY_PATH,
        # 私钥路径
        app_private_key_path=settings.APP_PRIVATE_KEY_PATH,
        # 加密方式
        sign_type='RSA2',
        debug=True,
    )
    return alipay
Пример #21
0
from django.core.urlresolvers import reverse
from payment.config import settings
from alipay import Alipay
from .models import Bill
import urllib
from accounts.models import UserSettings
from django.db.models import F
from django.views.decorators.csrf import csrf_exempt
from actions.utils import create_action
from asin_keyword.emails import send_email
from short_url.shorten_url import get_short_code
from django.http import HttpResponse
#import datetime

alipay = Alipay(pid=settings.ALIPAY_PARTNER,
                key=settings.ALIPAY_KEY,
                seller_email=settings.ALIPAY_SELLER_EMAIL)


def buy_credit(user, credit, request):
    user.update(credit=F('credit') + credit)
    create_action(request.user, '购买了%s积分' % (credit))


@login_required
def upgrade_account(request, add_credit):

    user = request.user
    try:
        bill = user.bill
    except:
Пример #22
0
 def get_alipay(self):
     from alipay import Alipay
     return Alipay(self.app_id, self.app_secret, self.seller_email)
Пример #23
0
 def Alipay(self, *a, **kw):
     from alipay import Alipay
     return Alipay(*a, **kw)
Пример #24
0
    def alipayPayment(self,
                      is_prod_server,
                      request_id,
                      user_email,
                      amount,
                      point_for_use=0,
                      promo_type='',
                      promo_code='',
                      is_additional=False,
                      is_groupRequest=False,
                      is_public=False):

        host_name = ""
        if is_prod_server == False:
            host_name = "http://ciceron.xyz:5000"
        else:
            host_name = "http://ciceron.me:5000"
        pay_by = "web"

        postprocess_api = "%s/%s" % (
            host_name, 'api/user/requests/%d/payment/postprocess' % request_id)

        order_no = self._orderNoGenerator()
        param_dict = {
            'pay_via': 'alipay',
            'status': 'success',
            'user_id': user_email,
            'pay_amt': amount,
            'pay_by': pay_by,
            'use_point': point_for_use,
            'promo_type': promo_type,
            'promo_code': promo_code,
            'ciceron_order_no': order_no,
            'is_additional': 'false' if is_additional == False else 'true',
            'is_groupRequest': 'false' if is_groupRequest == False else 'true',
            'is_public': 'false' if is_public == False else 'true'
        }
        return_url = ciceron_lib.apiURLOrganizer(postprocess_api, **param_dict)

        alipay_obj = Alipay(pid='111',
                            key='secret',
                            seller_email='*****@*****.**')
        params = {
            'subject': '诗谐论翻译'.decode('utf-8'),
            'out_trade_no': order_no,
            #'subject': 'TEST',
            'total_fee': '%.2f' % amount,
            'currency': 'USD',
            'quantity': '1',
            'return_url': return_url
        }

        provided_link = None
        try:
            if pay_by == 'web':
                provided_link = alipay_obj.create_forex_trade_url(**params)
            elif pay_by == 'mobile':
                provided_link = alipay_obj.create_forex_trade_wap_url(**params)
        except:
            return False, None

        return True, provided_link
Пример #25
0
            m = UserProfile.objects.filter(user_id=id).update(
                usermoney=personnewmoney)
            return render(request, 'error.html', {
                'title': '恭喜您',
                'context': '充值成功'
            })
        else:
            return render(request, 'error.html', {
                'title': '发生错误',
                'context': '代金卷未发现或已失效'
            })
    else:
        return HttpResponseRedirect(reverse('signin'))


alipay = Alipay(pid='zzz', key='zzz', seller_email='*****@*****.**')


#set alipay
def trade_check(request):
    '''doc https://github.com/lxneng/alipay'''
    if request.user.is_authenticated():
        if request.method == 'GET':
            return render_to_response('change-password.html', {},
                                      context_instance=RequestContext(request))
        elif request.method == 'POST':
            try:
                money = request.POST['money']
                try:
                    if int(money) >= 0:
                        id = request.user.id
Пример #26
0
import json
import time
import tornado.web
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.websocket
import urllib.parse
from alipay import Alipay
from micropay import Micropay
from history import History
from configs.config import configs

payment_methods = {
    'alipay':
    Alipay(configs.alipay.app_id, configs.alipay.cert_path,
           configs.alipay.default_subject),
    'mircopay':
    Micropay(configs.mircopay.app_id, configs.mircopay.mch_id,
             configs.mircopay.key, configs.mircopay.cert_path,
             configs.mircopay.cert_key_path)
}

history = History('lemonpay')


class root_handler(tornado.web.RequestHandler):
    def get(self):
        self.render('index.html')


class payment_handler(tornado.web.RequestHandler):