Пример #1
0
        //public void DoImageResizing(out string error)
        //{
        //    error = string.Empty;
        //    var total = 0;
        //    var skipped = 0;
        //    var resized = 0;
        //    try
        //    {
        //        var courses = CourseRepository.GetAll().Select(x => new
        //        {
        //            id= x.Id
        //            ,name = x.CourseName
        //            ,image = x.SmallImage
        //        }).ToList();



        //        foreach (var course in courses)
        //        {
        //            if(String.IsNullOrEmpty(course.image)) continue;

        //            total++;

        //            try
        //            {
        //                var url = course.image.ToThumbUrl(ImageBaseUrl);

        //                var original = url.Url2Bitmap();

        //                if (original == null) continue;

        //                if (original.Width <= COURSE_THUMB_W)
        //                {
        //                    skipped++;
        //                    continue;
        //                }

        //                if (original.Height <= COURSE_THUMB_H)
        //                {
        //                    skipped++;
        //                    continue;
        //                }

        //                var msStream = new MemoryStream();

        //                var name = course.image.Replace(Path.GetFileName(course.image), Path.GetFileNameWithoutExtension(course.image) + String.Format(".{0}", ImageFormat.Jpeg.ToString().ToLower()));

        //                var image = ImageHelper.LimitBitmapSize(original, COURSE_THUMB_W, COURSE_THUMB_H);

        //                image.Save(msStream, ImageFormat.Jpeg);

        //                msStream.Seek(0, SeekOrigin.Begin);

        //                _s3Wrapper.Upload(name, "image/jpeg", msStream, out error);

        //                var courseEntity = CourseRepository.GetById(course.id);
        //                if (courseEntity != null)
        //                {
        //                    courseEntity.SmallImage = name;

        //                    CourseRepository.UnitOfWork.CommitAndRefreshChanges();

        //                }

        //                resized++;
        //            }
        //            catch (Exception)
        //            {

        //            }

        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        error = Utils.FormatError(ex);
        //    }
        //}
        #endregion

        #region sales data conversion
        //public void DoDataMigration(out int totalRows, out int rowsProceed, out string error)
        //{
        //    totalRows = 0;
        //    rowsProceed = 0;
        //    error = string.Empty;

        //    try
        //    {
        //        using (var context = new lfeAuthorEntities())
        //        {
        //            totalRows = context.UserCourses.Count();

        //            foreach (var userCourse in context.UserCourses.OrderBy(x=>x.Created).ThenBy(x=>x.UserId).ThenBy(x=>x.CourseId).ToList())
        //            {
        //                var uc = userCourse;

        //                if(UserCourseRepository.IsAny(x=>x.UserId==uc.UserId && x.CourseId==uc.CourseId)) continue;

        //                var userId = uc.UserId;
        //                var courseId = uc.CourseId;

        //                var crs = CourseRepository.GetById(courseId);

        //                if (crs == null) continue;
        //                var itemName = String.Format("{0} - {1}", crs.CourseName,  "Unlimited Access");
        //                const BillingEnums.ePaymentTerms paymentTerm = BillingEnums.ePaymentTerms.IMMEDIATE;
        //                BillingEnums.ePaymentMethods paymentMethod;
        //                string externalTrxId = null;
        //                decimal price;
        //                int? couponInstanceId = null;
        //                int? storeId = null;
        //                DateTime pd;
        //                var trx = context.UserTransactions.Where(x=>x.TransactionUser==uc.UserId && x.TransactionCourse==uc.CourseId).ToArray();

        //                switch (trx.Count())
        //                {
        //                    case 0:
        //                        price = 0;
        //                        paymentMethod = BillingEnums.ePaymentMethods.Charge_Free;
        //                        pd = uc.Created;
        //                        break;
        //                    default:
        //                        var t = trx[0];
        //                        price = t.TransactionAmount > (decimal) 0.01 ? t.TransactionAmount : 0;
        //                        couponInstanceId = t.CouponInstanceId;
        //                        storeId = t.WebStoreID;
        //                        paymentMethod = price > 0 ? BillingEnums.ePaymentMethods.Paypal : BillingEnums.ePaymentMethods.Charge_Free;
        //                        externalTrxId = t.ExternalTransactionID;
        //                        pd = t.TransactionDate;
        //                        break;
        //                }

        //                var orderId = Guid.NewGuid();

        //                var orderCreated = DC_CreateSalesOrder(orderId, uc.Created,paymentTerm, userId, itemName, null, price,
        //                                                        courseId, null, (byte) paymentMethod, null, storeId, couponInstanceId, string.Empty,
        //                                                        out error);

        //                if(!orderCreated) continue;

        //                var lineId = GetOrderLineId(orderId, BillingEnums.eOrderLineTypes.SALE);

        //                if (lineId < 0) continue;
        //                if (price > 0)
        //                {
        //                    int paymentId;
        //                    if (DC_CreateOrderLinePayment(lineId, price, pd, pd, 1, BillingEnums.ePaymentStatuses.COMPLETED, BillingEnums.ePaymentTypes.ONE_TIME, out paymentId, out error)) DC_SaveSaleTransaction(lineId,paymentId,BillingEnums.eTransactionTypes.DirectPaymentTransaction, price,pd,externalTrxId,out error);
        //                }


        //                if (DC_AttachCourse2User(userId, lineId, courseId, out error))
        //                {
        //                    if (uc.LastChapterID != null)
        //                    {
        //                        UserCourseWatchStateRepository.Add(new USER_CourseWatchState
        //                        {
        //                            CourseId       = courseId
        //                            ,UserId        = userId
        //                            ,LastChapterID = uc.LastChapterID
        //                            ,LastVideoID   = uc.LastVideoID
        //                            ,LastViewDate  = uc.LastViewDate
        //                            ,AddOn         = DateTime.Now
        //                        });
        //                    }
        //                }

        //                rowsProceed++;



        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        error = Utils.FormatError(ex);
        //    }
        //}


        //private bool DC_AttachCourse2User(int userId, int orderLineId, int courseId, out string error)
        //{
        //    UserCourseRepository.Add(UserEntityMapper.NewUserCourseEntity(courseId, orderLineId, userId, null, BillingEnums.eAccessStatuses.ACTIVE));

        //    return UserCourseRepository.UnitOfWork.CommitAndRefreshChanges(out error);
        //}


        //private bool DC_CreateSalesOrder(Guid orderId,
        //                            DateTime orderDate,
        //                            BillingEnums.ePaymentTerms paymentTerm,
        //                            int userId,
        //                            string itemName,
        //                            int? addressId,
        //                            decimal price,
        //                            int courseId,
        //                            int? bundleId,
        //                            byte paymentMethodId,
        //                            Guid? paymentIntrsrumentId,
        //                            int? storeId,
        //                            int? couponInstanceId,
        //                            string paypalProfileId,
        //                            out string error)
        //{
        //    error = string.Empty;
        //    try
        //    {
        //        var sellerUserId = GetSellerUserId(courseId, bundleId, out error);

        //        if (sellerUserId < 0)
        //        {
        //            return false;
        //        }

        //        OrderLinePriceDTO priceToken;
        //        if (!ValidateOrderLinePrice(price, courseId, couponInstanceId, out priceToken, out error))
        //        {
        //            priceToken = new OrderLinePriceDTO
        //            {
        //               Price  = CourseRepository.GetById(courseId).PriceUSD ?? price
        //               ,FinalPrice = price
        //            };

        //            priceToken.Discount = priceToken.Price - priceToken.FinalPrice;
        //        }

        //        #region create  header
        //        var orderEntity = new SALE_Orders
        //        {
        //            OrderId          = orderId
        //            ,BuyerUserId     = userId
        //            ,SellerUserId    = sellerUserId
        //            ,PaymentMethodId = paymentMethodId
        //            ,InstrumentId    = paymentIntrsrumentId
        //            ,WebStoreId      = storeId
        //            ,AddressId       = addressId
        //            ,StatusId        = (byte)BillingEnums.eOrderStatuses.COMPLETE
        //            ,OrderDate       = orderDate
        //            ,AddOn           = orderDate
        //            ,CreatedBy       = userId
        //        };

        //        OrderRepository.Add(orderEntity);

        //        if (!OrderRepository.UnitOfWork.CommitAndRefreshChanges(out error))return false;
        //        #endregion

        //        #region create line
        //        var lineSaved = DC_CreateOrderLine(orderId,
        //                                            paymentTerm,
        //                                            BillingEnums.eOrderLineTypes.SALE,
        //                                            sellerUserId,
        //                                            itemName,
        //                                            courseId,
        //                                            bundleId,
        //                                            couponInstanceId,
        //                                            paypalProfileId,
        //                                            priceToken,
        //                                            out error);

        //        if (lineSaved) return true;

        //        OrderRepository.Delete(x=>x.OrderId==orderId);
        //        OrderRepository.UnitOfWork.CommitAndRefreshChanges();

        //        return false;

        //        #endregion
        //    }
        //    catch (Exception )
        //    {
        //        return false;
        //    }
        //}


        //private bool DC_CreateOrderLine(Guid orderId,
        //                                BillingEnums.ePaymentTerms paymentTerm,
        //                                BillingEnums.eOrderLineTypes lineType,
        //                                int sellerUserId,
        //                                string itemName,
        //                                int? courseId,
        //                                int? bundleId,
        //                                int? couponInstanceId,
        //                                string paypalProfileId,
        //                                OrderLinePriceDTO priceToken,
        //                                out string error)
        //{
        //    var lineEntity = new SALE_OrderLines
        //    {
        //        OrderId           = orderId
        //        ,LineTypeId       = (byte)lineType
        //        ,SellerUserId     = sellerUserId
        //        ,ItemName         = itemName
        //        ,CourseId         = courseId
        //        ,BundleId         = bundleId
        //        ,CouponInstanceId = couponInstanceId
        //        ,Price            = priceToken.Price
        //        ,Discount         = priceToken.Discount
        //        ,TotalPrice       = priceToken.FinalPrice
        //        ,PaypalProfileID  = paypalProfileId
        //        ,PaymentTermId    = (byte)paymentTerm
        //        ,AddOn            = DateTime.Now
        //        ,CreatedBy        = CurrentUserId
        //    };

        //    OrderLineRepository.Add(lineEntity);

        //    return OrderLineRepository.UnitOfWork.CommitAndRefreshChanges(out error);
        //}

        //private void DC_SaveSaleTransaction(int lineId, int? paymentId, BillingEnums.eTransactionTypes type, decimal amount, DateTime trxDate, string externalTrxId, out string error)
        //{
        //    TransactionRepository.Add(new SALE_Transactions
        //    {
        //        OrderLineId            = lineId
        //        ,PaymentId             = paymentId
        //        ,Amount                = amount
        //        ,TransactionTypeId     = (byte)type
        //        ,TransactionDate       = trxDate
        //        ,ExternalTransactionID = externalTrxId
        //        ,Fee                   = 0
        //        ,AddOn                 = DateTime.Now
        //    });

        //    TransactionRepository.UnitOfWork.CommitAndRefreshChanges(out error);
        //}

        //private bool DC_CreateOrderLinePayment(int lineId,
        //                                    decimal amount,
        //                                    DateTime? paymentDate,
        //                                    DateTime scheduledDate,
        //                                    short paymentNum,
        //                                    BillingEnums.ePaymentStatuses status,
        //                                    BillingEnums.ePaymentTypes type,
        //                                    out int paymentId,
        //                                    out string error)
        //{

        //    paymentId = -1;

        //    var paymentEntity = new SALE_OrderLinePayments
        //    {
        //        OrderLineId    = lineId
        //        ,Amount        = amount
        //        ,Currency      = "USD"
        //        ,PaymentDate   = paymentDate
        //        ,ScheduledDate = scheduledDate
        //        ,PaymentNumber = paymentNum
        //        ,StatusId      = (byte)status
        //        ,TypeId        = (byte)type
        //        ,AddOn         = DateTime.Now
        //    };

        //    OrderLinePaymentRepository.Add(paymentEntity);

        //    if (!OrderLinePaymentRepository.UnitOfWork.CommitAndRefreshChanges(out error)) return false;

        //    paymentId = paymentEntity.PaymentId;

        //    return true;
        //}



        // private bool ValidateOrderLinePrice(decimal? price, int? courseId, int? couponInstanceId, out OrderLinePriceDTO priceToken, out string error)
        //{
        //    priceToken = new OrderLinePriceDTO();
        //    error = string.Empty;

        //    try
        //    {
        //        if (courseId == null)
        //        {
        //            error = "course or bundle required";
        //            return false;
        //        }

        //        if (price == null)
        //        {
        //            error = "price required";
        //            return false;
        //        }
        //        var itemPrice = CourseRepository.GetById((int)courseId).PriceUSD;
        //        if (itemPrice == null)
        //        {
        //            error = "price not defined";
        //            return false;
        //        }
        //        priceToken.Price = (decimal)itemPrice;

        //        if (couponInstanceId != null)
        //        {
        //            var couponResult = ValidateCoupon(courseId, (int)couponInstanceId);

        //            if (!couponResult.IsValid)
        //            {
        //                error = couponResult.Message;
        //                return false;
        //            }

        //            priceToken.Discount = couponResult.Discount;
        //            priceToken.FinalPrice = couponResult.FinalPrice;
        //        }
        //        else
        //        {
        //            priceToken.Discount = 0;
        //            priceToken.FinalPrice = priceToken.Price;
        //        }

        //        if (priceToken.FinalPrice == (decimal)price) return true;

        //        error = "price not matched";
        //        return false;
        //    }
        //    catch (Exception ex)
        //    {
        //        error = Utils.FormatError(ex);
        //        return false;
        //    }

        //}

        //public CouponValidationToken ValidateCoupon(int? courseId,int couponInstanceId)
        //{
        //    var result = new CouponValidationToken
        //    {
        //        IsValid = false
        //        ,Discount = 0
        //    };

        //    decimal basePrice;

        //    if (courseId != null)
        //    {

        //        var course = CourseRepository.GetById((int) courseId);

        //        if (course == null)
        //        {
        //            result.Message = "course not found";
        //            return result;
        //        }

        //        var itemPrice = course.CourseEntity2Price(false);

        //        if (itemPrice == null)
        //        {
        //            result.Message = "invalid price";
        //            return result;
        //        }

        //        basePrice = (decimal) itemPrice;
        //    }
        //     else
        //    {
        //        result.Message = "course or bundle required";
        //        return result;
        //    }

        //    result.OriginalPrice = basePrice;
        //    result.FinalPrice    = basePrice;

        //    var inst = CouponInstanceRepository.GetById(couponInstanceId);
        //    if (inst == null)
        //    {
        //        result.Message = "coupon instance not found";
        //        return result;
        //    }

        //    var coupon = CouponRepository.GetById(inst.CouponId).Entity2CourseCouponDTO();
        //    if (coupon == null)
        //    {
        //        result.Message = "coupon not found";
        //        return result;
        //    }

        //    switch (coupon.Type)
        //    {
        //        case CourseEnums.CouponType.PERCENT:
        //            result.Discount = (decimal)(coupon.Amount != null ? basePrice * (coupon.Amount / 100) : 0);
        //            result.FinalPrice = CalculateDiscountedPrice(basePrice, coupon.Amount ?? 0, CourseEnums.CouponType.PERCENT);
        //            break;
        //        case CourseEnums.CouponType.FIXED:
        //                result.Discount = coupon.Amount ?? 0;
        //                result.FinalPrice = CalculateDiscountedPrice(basePrice, coupon.Amount ?? 0, CourseEnums.CouponType.FIXED);
        //            break;
        //        case CourseEnums.CouponType.FREE:
        //            result.Discount = basePrice;
        //            result.FinalPrice = 0;
        //            break;
        //    }

        //    return result;
        //}

        //private static decimal CalculateDiscountedPrice(decimal price, decimal couponDiscountAmount, CourseEnums.CouponType type)
        //{
        //    try
        //    {
        //        var finalPrice = price;

        //        switch (type)
        //        {
        //            case CourseEnums.CouponType.PERCENT:
        //                finalPrice = price - (price * (couponDiscountAmount / 100));
        //                break;
        //            case CourseEnums.CouponType.FIXED:
        //                finalPrice = Math.Max(price - couponDiscountAmount, 0);
        //                break;
        //            case CourseEnums.CouponType.FREE:
        //                return 0;
        //        }

        //        return decimal.Round(finalPrice, 2, MidpointRounding.AwayFromZero);
        //    }
        //    catch (Exception)
        //    {
        //        return price;
        //    }
        //}

        public void RunIpnTrxDetailRequests()
        {
            try
            {
                var    requests = PaypalIpnLogRepository.GetMany(x => x.txn_type == "cart" || x.txn_type == "paypal_here").ToList();
                string error;
                foreach (var log in requests)
                {
                    var token = log.response.Qs2IpnResponseToken(out error);

                    if (token == null)
                    {
                        continue;
                    }

                    _paypalIpnServices.HandleIpnResponse(token);
                }
            }
            catch (Exception)
            {
            }
        }
Пример #2
0
        public HttpResponseMessage IPN()
        {
            try
            {
                Logger.Debug("IPN call::");



                var formVals = new Dictionary <string, string>
                {
                    { "cmd", "_notify-validate" }
                };

                var req = (HttpWebRequest)WebRequest.Create(PAYPAL_URL);

                // Set values for the request back
                req.Method      = "POST";
                req.ContentType = "application/x-www-form-urlencoded";

                var param      = HttpContext.Current.Request.BinaryRead(HttpContext.Current.Request.ContentLength);
                var strRequest = Encoding.ASCII.GetString(param);

                var sb = new StringBuilder();
                sb.Append(strRequest);

                foreach (var key in formVals.Keys)
                {
                    sb.AppendFormat("&{0}={1}", key, formVals[key]);
                }
                strRequest       += sb.ToString();
                req.ContentLength = strRequest.Length;

                //Send the request to PayPal and get the response
                using (var streamOut = new StreamWriter(req.GetRequestStream(), Encoding.ASCII))
                {
                    streamOut.Write(strRequest);
                    streamOut.Close();

                    Logger.Debug("IPN call::request::" + strRequest);

                    using (var streamIn = new StreamReader(req.GetResponse().GetResponseStream()))
                    {
                        var response = streamIn.ReadToEnd();

                        if (response == "VERIFIED")
                        {
                            string error;
                            var    token = strRequest.Qs2IpnResponseToken(out error);
                            if (token == null)
                            {
                                Logger.Error("token not parsed::" + error);
                                return(Request.CreateResponse(HttpStatusCode.ExpectationFailed));
                            }

                            if (token.txn_type == null || token.txn_type.ToLower() != "masspay")
                            {
                                _paypalServices.HandleIpnResponse(token);
                            }
                            else
                            {
                                var parsedQuery = HttpUtility.ParseQueryString(strRequest);

                                var payments   = new Dictionary <int, Dictionary <string, string> >();
                                var queryRegex = new Regex(@"^(?<key>.+)_(?<index>\d+)");

                                // Parsing
                                foreach (var key in parsedQuery)
                                {
                                    var value = parsedQuery[key.ToString()];
                                    var match = queryRegex.Match(key.ToString());

                                    if (!match.Success)
                                    {
                                        continue;
                                    }

                                    var normalizedKey = match.Groups["key"];
                                    var index         = int.Parse(match.Groups["index"].Value);

                                    Dictionary <string, string> collection;
                                    if (payments.ContainsKey(index))
                                    {
                                        collection = payments[index];
                                    }
                                    else
                                    {
                                        collection = new Dictionary <string, string>();
                                        payments.Add(index, collection);
                                    }

                                    if (!collection.ContainsKey(normalizedKey.ToString()))
                                    {
                                        collection.Add(normalizedKey.ToString(), value.Split(Convert.ToChar(","))[0]);
                                    }
                                }

                                var items = new List <MassPaymentItemToken>();

                                if (payments.Count > 0)
                                {
                                    foreach (var payment in payments)
                                    {
                                        var c = payment.Value;

                                        items.Add(c.Dict2PaymentItemToken());
                                    }
                                }

                                _paypalServices.HandleIpnMasspayResponse(items);
                            }
                        }
                        else
                        {
                            Logger.Warn("IPN call::response not verified::" + response + "::" + strRequest);
                        }
                    }
                }

                return(Request.CreateResponse(HttpStatusCode.OK));
            }
            catch (Exception ex)
            {
                Logger.Error("IPN listener", ex, CommonEnums.LoggerObjectTypes.PayPal);
                return(Request.CreateResponse(HttpStatusCode.InternalServerError));
            }
        }