/**
         * AUTO_GENERATED
         */
        public PayResponse Pay(PayRequest payRequest, string apiUserName)
        {
            string  response = Call("Pay", payRequest.ToNVPString(""), apiUserName);
            NVPUtil util     = new NVPUtil();

            return(PayResponse.CreateInstance(util.ParseNVPString(response), "", -1));
        }
Beispiel #2
0
        public async Task <PayResponse> PayCardless(string payerId, Payment payment)
        {
            if (channel.State == ChannelState.Shutdown)
            {
                var response = new PayResponse();
                response.PaymentErrors.Add(setClientShutDownError());
                return(response);
            }

            PayCardlessRequest request = new PayCardlessRequest()
            {
                Provider   = Enum.Parse <Provider>(payment.Provider),
                PaymentSum = payment.Sum,
                Currency   = payment.Currency,
                PaymentId  = payment.Token,
                PayerId    = payerId,
                Intent     = Enum.Parse <Intent>(payment.Intent)
            };

            try
            {
                return(await client.PayCardlessAsync(request));
            }
            catch (RpcException ex)
            {
                var response = new PayResponse();
                response.PaymentErrors.Add(setGatewayError(ex.Message));
                return(response);
            }
        }
Beispiel #3
0
        public async Task <ActionResult <PayResponse> > Pay(LightningInvoicePayRequest req)
        {
            var wallet = await _walletService.GetWallet(new WalletQuery {
                UserId              = UserId,
                WalletId            = req.WalletId,
                IncludeTransactions = true
            });

            if (wallet == null)
            {
                return(NotFound());
            }

            var paymentRequest = req.PaymentRequest;
            var bolt11         = _walletService.ParsePaymentRequest(paymentRequest);

            try
            {
                await _walletService.Send(wallet, bolt11, paymentRequest);

                var response = new PayResponse(PayResult.Ok);
                return(Ok(response));
            }
            catch (Exception exception)
            {
                return(new PayResponse(PayResult.Error, exception.Message));
            }
        }
Beispiel #4
0
        public IActionResult Pay(ViewModel_Pay model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            try
            {
                PayResponse paymentResponse = Payment.Pay(new PayRequest
                {
                    api      = myApi,
                    amount   = model.Amount,
                    redirect = "http://localhost:5100" + Url.Action("Verify")
                });

                if (paymentResponse.status == 1)
                {
                    return(Redirect(Payment.GatewayAddress(paymentResponse.transId)));
                }

                ViewBag.Error = "خطای \"" + paymentResponse.errorCode + "\": " + paymentResponse.errorMessage;
            }
            catch (Exception e)
            {
                ViewBag.Error = e.Message;
            }

            return(View(model));
        }
Beispiel #5
0
        public async Task <IActionResult> CapturePayment(string transactionId)
        {
            TempData["actionInitiated"] = true;
            if (string.IsNullOrEmpty(transactionId))
            {
                setError(EmptyTransactionId);
                return(redirectToLandingPage());
            }

            var payment = await paymentRepository.TrackByTransactionId(transactionId);

            if (payment == null)
            {
                setError(PaymentNotFound);
                return(redirectToLandingPage());
            }

            PayResponse response = await rcpgClient.Capture(payment);

            if (response.PaymentErrors.Any())
            {
                TempData["notificationText"] = $"Notikusi kļūda. Kļūdas avots: \"{response.PaymentErrors.First().Source}\", kļūdas kods: \"{response.PaymentErrors.First().ErrorCode}\"";
                return(redirectToLandingPage());
            }

            payment.Status        = PaymentStatus.Captured.ToString();
            payment.TransactionId = response.PaymentId;
            payment.CapturedOn    = DateTime.Parse(response.ExecutedOn);

            await paymentRepository.Update(payment);

            TempData["notificationText"] = $"Veiksmīga nokārtošana ar identifikatoru: \"{response.PaymentId}\"";
            return(redirectToAllPayments());
        }
Beispiel #6
0
        public async Task <PayResponse> Capture(Payment payment)
        {
            if (channel.State == ChannelState.Shutdown)
            {
                var response = new PayResponse();
                response.PaymentErrors.Add(setClientShutDownError());
                return(response);
            }

            CaptureRequest request = new CaptureRequest()
            {
                Provider   = Enum.Parse <Provider>(payment.Provider),
                PaymentSum = payment.Sum,
                Currency   = payment.Currency,
                PaymentId  = payment.TransactionId
            };

            try
            {
                return(await client.CaptureAsync(request));
            }
            catch (RpcException ex)
            {
                var response = new PayResponse();
                response.PaymentErrors.Add(setGatewayError(ex.Message));
                return(response);
            }
        }
        public ActionResult Index(int?id)
        {
            //decimal price = 50;
            //Bids bid = db.Bids.Find(id);
            ReceiverList receiverList = new ReceiverList();

            receiverList.receiver = new List <Receiver>();
            Receiver receiver = new Receiver(50);

            //var query = from v in db.Ventures where v.Id == bid.ventureID select v.investorID;
            //string receiverID = query.ToList().ElementAt(0);
            //ApplicationUser recvUser = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(receiverID.ToString());
            receiver.email   = "*****@*****.**";
            receiver.primary = true;
            receiverList.receiver.Add(receiver);
            Receiver receiver2 = new Receiver(10);

            //var query = from v in db.Ventures where v.Id == bid.ventureID select v.investorID;
            //string receiverID = query.ToList().ElementAt(0);
            //ApplicationUser recvUser = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(receiverID.ToString());
            receiver2.email   = "*****@*****.**";
            receiver2.primary = false;
            receiverList.receiver.Add(receiver2);

            RequestEnvelope requestEnvelope = new RequestEnvelope("en_US");
            string          actionType      = "PAY";

            string successUrl = "http://" + System.Web.HttpContext.Current.Request.Url.Authority + "/PayPal/SuccessView/{0}";
            string failureUrl = "http://" + System.Web.HttpContext.Current.Request.Url.Authority + "/PayPal/FailureView/{0}";

            successUrl = String.Format(successUrl, id);
            failureUrl = String.Format(failureUrl, id);
            string returnUrl = successUrl;
            string cancelUrl = failureUrl;

            string     currencyCode = "USD";
            PayRequest payRequest   = new PayRequest(requestEnvelope, actionType, cancelUrl, currencyCode, receiverList, returnUrl);

            payRequest.ipnNotificationUrl = "http://de3b6191.ngrok.io";

            Dictionary <string, string> sdkConfig = new Dictionary <string, string>();

            sdkConfig.Add("mode", "sandbox");
            sdkConfig.Add("account1.apiUsername", "mattjheller-facilitator_api1.yahoo.com");                    //PayPal.Account.APIUserName
            sdkConfig.Add("account1.apiPassword", "DG6GB55TRBWLESWG");                                          //PayPal.Account.APIPassword
            sdkConfig.Add("account1.apiSignature", "AFcWxV21C7fd0v3bYYYRCpSSRl31AafAKKwBsAp2EBV9PExGkablGWhj"); //.APISignature
            sdkConfig.Add("account1.applicationId", "APP-80W284485P519543T");                                   //.ApplicatonId

            AdaptivePaymentsService adaptivePaymentsService = new AdaptivePaymentsService(sdkConfig);
            PayResponse             payResponse             = adaptivePaymentsService.Pay(payRequest);

            ViewData["paykey"] = payResponse.payKey;
            //string payKey = payResponse.payKey; ////////
            //string paymentExecStatus = payResponse.paymentExecStatus;
            //string payURL = String.Format("https://www.sandbox.paypal.com/webscr?cmd=_ap-payment&paykey={0}", payKey);
            SimpleListenerExample("localhost: 80");
            return(View());
        }
Beispiel #8
0
        /// <summary>
        /// 支付异步通知处理
        /// </summary>
        /// <param name="input">微信发送的数据</param>
        /// <returns></returns>
        /// <exception cref="WeChatPayException"></exception>
        public async Task <string> ExecutedAsync(Stream input)
        {
            byte[] buffer = new byte[input.Length];
            input.Position = 0;
            input.Read(buffer);
            var xmlStr = Encoding.UTF8.GetString(buffer);

            XmlDocument xmlDocument = new XmlDocument();

            xmlDocument.LoadXml(xmlStr);

            var         node     = xmlDocument.FirstChild;
            PayResponse response = null;

            if (node.SelectSingleNode("return_code").InnerText == WeChatConstant.PaySuccess)
            {
                foreach (var handler in _handlers)
                {
                    if (handler is IRefundNotificationHandler refundHandler &&
                        node.SelectSingleNode("req_info") != null)
                    {
                        var encrypt      = node.SelectSingleNode("req_info").InnerText;
                        var mchId        = node.SelectSingleNode("mch_id").InnerText;
                        var appId        = node.SelectSingleNode("appid").InnerText;
                        var nonce        = node.SelectSingleNode("nonce_str").InnerText;
                        var notification = RefundParameterCheck(encrypt, mchId, appId, nonce);
                        response = await refundHandler.SuccessExecuted(notification);
                    }

                    if (handler is IUnifiedOrderNotificationHandler unifiedHandler &&
                        node.SelectSingleNode("result_code").InnerText == WeChatConstant.PaySuccess)
                    {
                        if (Check.PaySignCheck(xmlDocument, _securityKey) == false)
                        {
                            throw new WeChatPayException("签名验证失败");
                        }

                        var notification =
                            XmlSerializeHelper.StringToObject <UnifiedOrderNotificationRequest>(xmlStr);

                        response = await unifiedHandler.SuccessExecuted(notification);
                    }
                }
            }
            else
            {
                string errorCode = node.SelectSingleNode("err_code").InnerText;
                string errorMsg  = node.SelectSingleNode("err_code_des").InnerText;
                return(Failed(errorCode, errorMsg));
            }

            if (response == null)
            {
                throw new WeChatPayException("未找到可用的Handler");
            }

            return(Succeed());
        }
Beispiel #9
0
    // # Pay API Operations
    // Use the Pay API operations to transfer funds from a sender’s PayPal account to one or more receivers’ PayPal accounts. You can use the Pay API operation to make simple payments, chained payments, or parallel payments; these payments can be explicitly approved, preapproved, or implicitly approved.
    public PayResponse PayAPIOperations(PayRequest reqPay)
    {
        // Create the PayResponse object
        PayResponse responsePay = new PayResponse();

        try
        {
            // Create the service wrapper object to make the API call
            AdaptivePaymentsService service = new AdaptivePaymentsService();

            // # API call
            // Invoke the Pay method in service wrapper object
            responsePay = service.Pay(reqPay);

            if (responsePay != null)
            {
                // Response envelope acknowledgement
                string acknowledgement = "Pay API Operation - ";
                acknowledgement += responsePay.responseEnvelope.ack.ToString();
                logger.Info(acknowledgement + "\n");
                Console.WriteLine(acknowledgement + "\n");

                // # Success values
                if (responsePay.responseEnvelope.ack.ToString().Trim().ToUpper().Equals("SUCCESS"))
                {
                    // The pay key, which is a token you use in other Adaptive
                    // Payment APIs (such as the Refund Method) to identify this
                    // payment. The pay key is valid for 3 hours; the payment must
                    // be approved while the pay key is valid.
                    logger.Info("Pay Key : " + responsePay.payKey + "\n");
                    Console.WriteLine("Pay Key : " + responsePay.payKey + "\n");

                    // Once you get success response, user has to redirect to PayPal
                    // for the payment. Construct redirectURL as follows,
                    // `redirectURL=https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_ap-payment&paykey="
                    // + responsePay.payKey;`
                }
                // # Error Values
                else
                {
                    List <ErrorData> errorMessages = responsePay.error;
                    foreach (ErrorData error in errorMessages)
                    {
                        logger.Debug(error.message);
                        Console.WriteLine(error.message + "\n");
                    }
                }
            }
        }
        // # Exception log
        catch (System.Exception ex)
        {
            // Log the exception message
            logger.Debug("Error Message : " + ex.Message);
            Console.WriteLine("Error Message : " + ex.Message);
        }
        return(responsePay);
    }
 public static StatusRequest GenerateStatusRequest(PayResponse payResponse)
 {
     return(new StatusRequest()
     {
         SESSION = payResponse.SESSION,
         TRANSID = payResponse.TRANSID,
         ACCEPT_KEYS = TestConfigurations.ManagerConfiguration.PublicKeySerial,
     });
 }
 private static void Check(PayResponse response)
 {
     if (response.ReturnCode != WeChatConstant.PaySuccess)
     {
         throw new WeChatApiException(response.ReturnCode, response.ReturnMsg, string.Empty);
     }
     if (response.ResultCode != WeChatConstant.PaySuccess)
     {
         throw new WeChatApiException(response.ErrorCode, response.ErrorMsg, string.Empty);
     }
 }
Beispiel #12
0
        private bool ChargePayPalSuccess(Subscription sub, ManBoxEntities ent, string thankYouUrl, string cancelUrl)
        {
            var payPalAccount = ConfigurationManager.AppSettings[AppConstants.AppSettingsKeys.PayPalAccount] as string;
            var paymentInfo   = GetPaymentInfo(sub, ent);

            var receiverList = new ReceiverList();

            receiverList.receiver = new List <Receiver>();
            receiverList.receiver.Add(new Receiver(paymentInfo.Total)
            {
                email = payPalAccount
            });

            var         service  = new AdaptivePaymentsService();
            PayResponse response = service.Pay(new PayRequest(
                                                   new RequestEnvelope("en_US"),
                                                   "PAY",
                                                   cancelUrl,
                                                   "EUR",
                                                   receiverList,
                                                   thankYouUrl)
            {
                senderEmail    = sub.PayPalSenderEmail,
                preapprovalKey = sub.PayPalPreapprovalKey
            });

            if (response == null)
            {
                logger.Log(LogType.Fatal, "No Response was received from PayPal Payrequest service");
            }

            logger.Log(LogType.Info, string.Format("paykey is {0} . exec status is {1}", response.payKey ?? "", response.paymentExecStatus ?? ""));

            // error handling
            if (response.error != null && response.error.FirstOrDefault() != null)
            {
                logger.Log(LogType.Error, string.Format("error {0}", response.error.FirstOrDefault().message));
            }

            // error handling
            if (response.payErrorList != null && response.payErrorList.payError.FirstOrDefault() != null)
            {
                logger.Log(LogType.Error, string.Format("payerror {0}", response.payErrorList.payError.FirstOrDefault().error.message));
            }

            //payment exec status must be : COMPLETED
            if (!string.IsNullOrEmpty(response.paymentExecStatus) &&
                response.paymentExecStatus.ToLower() == PayPalConstants.PaymentExecStatus.Completed.ToLower())
            {
                return(true);
            }

            return(false);
        }
        public override ProcessPaymentResult ProcessPayment(ProcessPaymentEvaluationContext context)
        {
            var retVal = new ProcessPaymentResult();

            if (context.Store == null)
            {
                throw new NullReferenceException("Store is required!");
            }

            if (string.IsNullOrEmpty(context.Store.SecureUrl) && string.IsNullOrEmpty(context.Store.Url))
            {
                throw new NullReferenceException("Store must have Url or SecureUrl property assigned!");
            }

            PayResponse payResponse = null;
            string      errorText;

            try
            {
                var service = new AdaptivePaymentsService(GetConfiguration());
                var request = CreatePayRequest(context);

                // submit payment data for redirection to paypal website
                payResponse = service.Pay(request);

                errorText = GetErrors(payResponse.error);

                //var setPaymentOptionsResponse = service.SetPaymentOptions(new SetPaymentOptionsRequest { payKey = payResponse.payKey, senderOptions = new SenderOptions { referrerCode = "Virto_SP" }, requestEnvelope = new RequestEnvelope { errorLanguage = "en_US" } });
                //errorText += GetErrors(setPaymentOptionsResponse.error);

                //var executePaymentResponse = service.ExecutePayment(new ExecutePaymentRequest { payKey = payResponse.payKey, actionType = "PAY", requestEnvelope = new RequestEnvelope { errorLanguage = "en_US" } });
                //errorText += GetErrors(executePaymentResponse.error);
            }
            catch (Exception ex)
            {
                errorText = ex.Message;
            }

            if (string.IsNullOrEmpty(errorText))
            {
                retVal.OuterId          = payResponse.payKey;
                retVal.IsSuccess        = true;
                retVal.RedirectUrl      = string.Format(PaypalBaseUrlFormat, retVal.OuterId);
                retVal.NewPaymentStatus = context.Payment.PaymentStatus = PaymentStatus.Pending;
            }
            else
            {
                retVal.Error            = errorText;
                retVal.NewPaymentStatus = context.Payment.PaymentStatus = PaymentStatus.Voided;
                // context.Payment.VoidedDate = DateTime.UtcNow;
            }

            return(retVal);
        }
        /// <summary>
        ///
        /// </summary>
        ///<param name="payRequest"></param>
        ///<param name="credential">An explicit ICredential object that you want to authenticate this call against</param>
        public PayResponse Pay(PayRequest payRequest, ICredential credential)
        {
            IAPICallPreHandler apiCallPreHandler = new PlatformAPICallPreHandler(this.config, payRequest.ToNVPString(string.Empty), ServiceName, "Pay", credential);

            ((PlatformAPICallPreHandler)apiCallPreHandler).SDKName    = SDKName;
            ((PlatformAPICallPreHandler)apiCallPreHandler).SDKVersion = SDKVersion;
            ((PlatformAPICallPreHandler)apiCallPreHandler).PortName   = "AdaptivePayments";

            NVPUtil util = new NVPUtil();

            return(PayResponse.CreateInstance(util.ParseNVPString(Call(apiCallPreHandler)), string.Empty, -1));
        }
Beispiel #15
0
        public override PayResponse Process(IDictionary <string, string> dicParams)
        {
            try
            {
                //HttpWebHelper http = new Framework.Utility.HttpWebHelper();
                //var responseStr = http.Post("http://gateway.jbpay.net/api/gateway", dicParams, Encoding.UTF8, Encoding.UTF8);

                var responseStr = base.HttpRequest(dicParams);

                return(PayResponse.IsSuccess(responseStr));
            }
            catch (Exception ex)
            {
                return(PayResponse.IsFailed(ex.Message));
            }
        }
Beispiel #16
0
        public async Task <IActionResult> PayStandard(Provider provider, int paymentSum, PaymentCard paymentCard, Intent intent)
        {
            TempData["actionInitiated"] = true;
            if (intent == Intent.NoIntent)
            {
                setError(InvalidIntent);
                return(redirectToLandingPage());
            }

            // Let's assume payment sum and payment card gets validated on the client side, so no need to do it here.

            PayResponse response = await rcpgClient.PayStandard(provider, paymentSum, DEFAULT_CURRENCY, paymentCard, intent);

            if (response.PaymentErrors.Any())
            {
                TempData["hasErrors"]        = true;
                TempData["notificationText"] = $"Notikusi kļūda. Kļūdas avots: \"{response.PaymentErrors.First().Source}\", kļūdas kods: \"{response.PaymentErrors.First().ErrorCode}\"";
                return(redirectToLandingPage());
            }

            Payment payment = new Payment()
            {
                Token         = response.PaymentId,
                Sum           = paymentSum,
                Currency      = DEFAULT_CURRENCY,
                Provider      = provider.ToString(),
                Intent        = intent.ToString(),
                TransactionId = response.PaymentId,
                InitiatedOn   = DateTime.Parse(response.ExecutedOn)
            };

            if (intent == Intent.Purchase)
            {
                payment.Status     = PaymentStatus.Captured.ToString();
                payment.CapturedOn = DateTime.Parse(response.ExecutedOn);
            }
            else
            {
                payment.Status = PaymentStatus.Authorized.ToString();
            }
            await paymentRepository.Add(payment);

            return(redirectToAllPayments());
        }
        // GET: /WeChat/FourthPay/ResultNotifyPage/
        public ActionResult ResultNotifyPage(PayResponse result)
        {
            var redirectAction = "";

            //检查支付结果中transaction_id是否存在
            string transaction_id = result.mercOrderId;

            if (transaction_id.HasValue())
            {
                //1.开始处理
                var chargePayOrder = _accountPayService.FindPayOrder(transaction_id);
                if (chargePayOrder != null)
                {
                    chargePayOrder.ToNextState(transaction_id);
                    _accountPayService.SyncPayOrder(chargePayOrder);

                    if (result.Successful &&
                        chargePayOrder.IsValid(transaction_id))
                    {
                        //防止重复处理
                        if (!chargePayOrder.IsEnd)
                        {
                            chargePayOrder.ToNextState();
                            //2.同步支付订单
                            _accountPayService.SyncPayOrder(chargePayOrder);
                        }

                        redirectAction = "ChargeOK";
                    }
                    else
                    {
                        redirectAction = "ChargeFailed";
                    }
                }
            }
            else
            {
                //若transaction_id不存在,则立即返回结果给微信支付后台
                //Log.Error(this.GetType().ToString(), "The Pay result is error : " + res.ToXml());
                redirectAction = "ChargeFailed";
            }
            return(RedirectToAction(redirectAction));
        }
    public void Pay()
    {
        PaySample   sample                 = new PaySample();
        PayRequest  requestPay             = sample.SimplePayment();
        PayResponse responsePaymentDetails = sample.PayAPIOperations(requestPay);

        Assert.IsNotNull(responsePaymentDetails);
        Assert.AreEqual(responsePaymentDetails.responseEnvelope.ack.ToString().ToUpper(), "SUCCESS");

        requestPay             = sample.ParallelPayment();
        responsePaymentDetails = sample.PayAPIOperations(requestPay);
        Assert.IsNotNull(responsePaymentDetails);
        Assert.AreEqual(responsePaymentDetails.responseEnvelope.ack.ToString().ToUpper(), "SUCCESS");

        requestPay             = sample.ChainPayment();
        responsePaymentDetails = sample.PayAPIOperations(requestPay);
        Assert.IsNotNull(responsePaymentDetails);
        Assert.AreEqual(responsePaymentDetails.responseEnvelope.ack.ToString().ToUpper(), "SUCCESS");
    }
Beispiel #19
0
        public async Task <PayResponse> PayStandard(Provider provider, int paymentSum, string currency, PaymentCard paymentCard, Intent intent)
        {
            if (channel.State == ChannelState.Shutdown)
            {
                var response = new PayResponse();
                response.PaymentErrors.Add(setClientShutDownError());
                return(response);
            }

            PayStandardRequest request = new PayStandardRequest()
            {
                Provider    = provider,
                PaymentSum  = paymentSum,
                Currency    = currency,
                PaymentCard = paymentCard,
                Intent      = intent
            };

            // Dummy item list. Total sum of items must be equal to paymentSum.
            var items = new List <Item>()
            {
                new Item()
                {
                    Name        = "A hat",
                    Description = "And a cat in that hat!",
                    Quantity    = 1,
                    Amount      = paymentSum
                }
            };

            request.Items.AddRange(items);

            try
            {
                return(await client.PayStandardAsync(request));
            }
            catch (RpcException ex)
            {
                var response = new PayResponse();
                response.PaymentErrors.Add(setGatewayError(ex.Message));
                return(response);
            }
        }
Beispiel #20
0
        public async Task <IActionResult> PayCardless([FromQuery] string token, [FromQuery] string PayerID)
        {
            TempData["actionInitiated"] = true;

            if (string.IsNullOrEmpty(token) || string.IsNullOrEmpty(PayerID))
            {
                setError(EmptyReturnParam);
                return(redirectToLandingPage());
            }

            var payment = await paymentRepository.Track(token);

            if (payment == null)
            {
                setError(PaymentNotFound);
                return(redirectToLandingPage());
            }
            PayResponse response = await rcpgClient.PayCardless(PayerID, payment);

            if (response.PaymentErrors.Any())
            {
                TempData["hasErrors"]        = true;
                TempData["notificationText"] = $"Notikusi kļūda. Kļūdas avots: \"{response.PaymentErrors.First().Source}\", kļūdas kods: \"{response.PaymentErrors.First().ErrorCode}\"";
                return(redirectToLandingPage());
            }

            if (Enum.Parse <Intent>(payment.Intent) == Intent.Purchase)
            {
                payment.Status     = PaymentStatus.Captured.ToString();
                payment.CapturedOn = DateTime.Parse(response.ExecutedOn);
            }
            else
            {
                payment.Status = PaymentStatus.Authorized.ToString();
            }
            payment.TransactionId = response.PaymentId;

            await paymentRepository.Update(payment);

            TempData["notificationText"] = $"Veiksmīgs maksājums ar transakcijas identifikatoru: \"{response.PaymentId}\"";
            return(redirectToAllPayments());
        }
        /// <summary>
        /// Creates paypal payment and its key
        /// It uses Pay action as of now to make do the payment
        /// </summary>
        /// <returns></returns>
        private PayResponse CallPaypalPay(PayRequest request)
        {
            Dictionary <string, string> configurationMap = FWUtils.ConfigUtils.GetAppSettings().Paypal.GetAcctAndConfig();
            AdaptivePaymentsService     service          = new AdaptivePaymentsService(configurationMap);

            // executing adaptive payment pay service
            PayResponse response = service.Pay(request);

            string ack = response.responseEnvelope.ack.ToString().Trim().ToUpper();

            // if no error happened
            if (!ack.Equals(AckCode.FAILURE.ToString()) &&
                !ack.Equals(AckCode.FAILUREWITHWARNING.ToString()))
            {
                //PaymentExecStatusSEnum execStatus = new PaymentExecStatusSEnum(response.paymentExecStatus);

                return(response);
            }
            else
            {
                throw new UserException(GetPayPalErrorString(response.error));
            }
        }
Beispiel #22
0
        public XResult <PayResponse> Pay(PayRequest request)
        {
            if (request == null)
            {
                return(new XResult <PayResponse>(null, ErrorCode.INVALID_ARGUMENT, new ArgumentNullException(nameof(request))));
            }

            String service = $"{this.GetType().FullName}.Pay(...)";

            if (!request.IsValid)
            {
                return(new XResult <PayResponse>(null, ErrorCode.INVALID_ARGUMENT, new ArgumentException(request.ErrorMessage)));
            }

            var requestHash = $"pay:{request.AppId}.{request.OutTradeNo}".GetHashCode();

            if (_lockProvider.Exists(requestHash))
            {
                return(new XResult <PayResponse>(null, ErrorCode.SUBMIT_REPEAT));
            }

            try
            {
                if (!_lockProvider.Lock(requestHash))
                {
                    return(new XResult <PayResponse>(null, ErrorCode.SUBMIT_REPEAT));
                }

                var existsOutTradeNo = _fundOutOrderRepository.Exists(x => x.OutTradeNo == request.OutTradeNo);
                if (existsOutTradeNo)
                {
                    return(new XResult <PayResponse>(null, ErrorCode.OUT_TRADE_NO_EXISTED));
                }

                //申请冻结商户放款余额
                var applyFreezeLoanParas = new Dictionary <String, String>(4);
                applyFreezeLoanParas["MerchantNo"]        = request.MerchantNo;
                applyFreezeLoanParas["OrderNo"]           = request.OutTradeNo;
                applyFreezeLoanParas["FrozenLoanBalance"] = request.Amount;
                applyFreezeLoanParas["Sign"] = MerchantUtil.MD5Sign(applyFreezeLoanParas);

                var client = GetClient();

                String traceMethod = $"{nameof(client)}.PostForm(...)";

                _logger.Trace(TraceType.BLL.ToString(), CallResultStatus.OK.ToString(), service, traceMethod, LogPhase.BEGIN, "开始请求商户系统冻结放款余额", new Object[] { ApiConfig.SystemMerchantAccountBalanceFreezeRequestUrl, applyFreezeLoanParas });

                var freezeResult = client.PostForm <ApiResult>(ApiConfig.SystemMerchantAccountBalanceFreezeRequestUrl, applyFreezeLoanParas);

                _logger.Trace(TraceType.BLL.ToString(), (freezeResult.Success ? CallResultStatus.OK : CallResultStatus.ERROR).ToString(), service, traceMethod, LogPhase.END, "结束请求商户系统冻结放款余额", freezeResult.Value);

                if (!freezeResult.Success)
                {
                    _logger.Error(TraceType.BLL.ToString(), CallResultStatus.ERROR.ToString(), service, traceMethod, "商户系统冻结放款余额失败", freezeResult.FirstException, applyFreezeLoanParas);
                    return(new XResult <PayResponse>(null, ErrorCode.DEPENDENT_API_CALL_FAILED, new RemoteException("商户系统冻结放款余额失败")));
                }

                if (freezeResult.Value == null)
                {
                    _logger.Error(TraceType.BLL.ToString(), CallResultStatus.ERROR.ToString(), service, traceMethod, "商户系统冻结放款余额返回的业务数据为空", null, applyFreezeLoanParas);
                    return(new XResult <PayResponse>(null, ErrorCode.DEPENDENT_API_CALL_FAILED, new RemoteException("商户系统冻结放款余额返回的业务数据为空")));
                }

                if (freezeResult.Value.Status != "SUCCESS")
                {
                    _logger.Trace(TraceType.BLL.ToString(), CallResultStatus.ERROR.ToString(), service, traceMethod, LogPhase.ACTION, "商户系统冻结放款余额失败", freezeResult.Value);
                    return(new XResult <PayResponse>(null, ErrorCode.DEPENDENT_API_CALL_FAILED, new RemoteException("商户系统冻结放款余额失败")));
                }

                var now   = DateTime.Now;
                var newId = IDGenerator.GenerateID();

                var fundoutOrder = new FundOutOrder()
                {
                    Id         = newId,
                    TradeNo    = newId.ToString(),
                    AppId      = request.AppId,
                    OutTradeNo = request.OutTradeNo,
                    Amount     = request.Amount.ToDecimal(),
                    RealName   = request.RealName,
                    BankCardNo = request.BankCardNo,
                    Mobile     = request.Mobile,
                    Remark     = request.Remark,
                    PayStatus  = PayStatus.APPLY.ToString(),
                    CreateTime = DateTime.Now
                };

                _fundOutOrderRepository.Add(fundoutOrder);
                var saveResult = _fundOutOrderRepository.SaveChanges();
                if (!saveResult.Success)
                {
                    _logger.Error(TraceType.BLL.ToString(), CallResultStatus.ERROR.ToString(), service, $"{nameof(_fundOutOrderRepository)}.SaveChanges()", "保存代付订单数据失败", saveResult.FirstException, fundoutOrder);
                    return(new XResult <PayResponse>(null, ErrorCode.DB_UPDATE_FAILED, new DbUpdateException("保存订单数据失败")));
                }

                var dic = new Dictionary <String, String>(6);
                dic["LoanJsonList"] = JsonUtil.SerializeObject(new FundOutLoanInfo()
                {
                    Amount           = request.Amount,
                    CardNumber       = CryptoHelper.RSAEncrypt(request.BankCardNo, KeyConfig.EPay95_FundOut_PublicKey).Value,
                    IdentificationNo = request.IDCardNo,
                    Mobile           = request.Mobile,
                    OrderNo          = request.OutTradeNo,
                    RealName         = request.RealName,
                    Type             = "0"
                }).Value;
                dic["PlatformMoneymoremore"] = GlobalConfig.X95epay_FundOut_Hehua_PlatformMoneymoremore;
                dic["BatchNo"]   = request.OutTradeNo;
                dic["Remark"]    = request.Remark;
                dic["NotifyURL"] = ApiConfig.EPay95_FundOut_Pay_NotifyUrl;

                var signResult = EPay95Util.MakeSign(dic);
                if (signResult.IsNullOrWhiteSpace())
                {
                    return(new XResult <PayResponse>(null, ErrorCode.SIGN_FAILED));
                }

                dic["LoanJsonList"] = HttpUtility.UrlEncode(dic["LoanJsonList"]);
                dic["SignInfo"]     = signResult;

                _logger.Trace(TraceType.BLL.ToString(), CallResultStatus.OK.ToString(), service, traceMethod, LogPhase.BEGIN, $"开始调用{ApiConfig.EPay95_FundOut_Pay_RequestUrl}", new Object[] { ApiConfig.EPay95_FundOut_Pay_RequestUrl, dic });

                //记录请求开始时间
                fundoutOrder.ApplyTime = DateTime.Now;
                var respMsgResult = client.PostForm(ApiConfig.EPay95_FundOut_Pay_RequestUrl, dic);

                _logger.Trace(TraceType.BLL.ToString(), (respMsgResult.Success ? CallResultStatus.OK : CallResultStatus.ERROR).ToString(), service, traceMethod, LogPhase.ACTION, $"结束调用{ApiConfig.EPay95_FundOut_Pay_RequestUrl}");

                if (!respMsgResult.Success)
                {
                    _logger.Error(TraceType.BLL.ToString(), CallResultStatus.ERROR.ToString(), service, traceMethod, "代付失败", respMsgResult.FirstException, dic);
                    return(new XResult <PayResponse>(null, ErrorCode.DEPENDENT_API_CALL_FAILED, new RequestException(respMsgResult.ErrorMessage)));
                }

                String respContent = null;
                try
                {
                    respContent = respMsgResult.Value.Content.ReadAsStringAsync().GetAwaiter().GetResult();
                    _logger.Trace(TraceType.BLL.ToString(), CallResultStatus.OK.ToString(), service, traceMethod, LogPhase.END, $"调用{ApiConfig.EPay95_FundOut_Pay_RequestUrl}返回结果", respContent);
                }
                catch (Exception ex)
                {
                    _logger.Error(TraceType.BLL.ToString(), CallResultStatus.ERROR.ToString(), service, traceMethod, "读取代付返回的消息内容出现异常", ex, dic);
                    return(new XResult <PayResponse>(null, ErrorCode.RESPONSE_READ_FAILED, ex));
                }

                if (respContent.IsNullOrWhiteSpace())
                {
                    _logger.Error(TraceType.BLL.ToString(), CallResultStatus.ERROR.ToString(), service, traceMethod, "双乾未返回任何数据", null, dic);
                    return(new XResult <PayResponse>(null, ErrorCode.REMOTE_RETURN_NOTHING));
                }

                EPay95PayReturnResult respResult = JsonUtil.DeserializeObject <EPay95PayReturnResult>(respContent).Value;
                if (respResult == null)
                {
                    _logger.Error(TraceType.BLL.ToString(), CallResultStatus.ERROR.ToString(), service, "respResult", "无法将代付结果反序列化为EPay95PayReturnResult对象", null, respContent);
                    return(new XResult <PayResponse>(null, ErrorCode.DESERIALIZE_FAILED));
                }

                //记录请求结束时间
                fundoutOrder.EndTime = DateTime.Now;

                switch (respResult.ResultCode)
                {
                case "88":
                case "90":
                case "15":
                    //修改支付状态为正在处理中
                    fundoutOrder.PayStatus = PayStatus.PROCESSING.ToString();
                    break;

                default:
                    //修改支付状态为正在处理中
                    fundoutOrder.PayStatus = PayStatus.FAILURE.ToString();
                    break;
                }

                fundoutOrder.UpdateTime = DateTime.Now;
                _fundOutOrderRepository.Update(fundoutOrder);
                var updateResult = _fundOutOrderRepository.SaveChanges();
                if (!updateResult.Success)
                {
                    _logger.Error(TraceType.BLL.ToString(), CallResultStatus.ERROR.ToString(), service, $"{nameof(_fundOutOrderRepository)}.SaveChanges()", "更新支付状态失败", updateResult.FirstException, fundoutOrder);
                }

                var payResp = new PayResponse()
                {
                    Status = fundoutOrder.PayStatus,
                    Msg    = respResult.Message.HasValue() ? respResult.Message : PayStatus.PROCESSING.GetDescription()
                };

                if (respResult.LoanJsonList != null)
                {
                    payResp.Amount     = respResult.LoanJsonList.Amount;
                    payResp.BankCardNo = respResult.LoanJsonList.CardNumber;
                    payResp.OutTradeNo = respResult.LoanJsonList.OrderNo;
                }

                return(new XResult <PayResponse>(payResp));
            }
            finally
            {
                _lockProvider.UnLock(requestHash);
            }
        }
    /*
     * void OnGUI() {
     *      if(GUI.Button(new Rect(0, 0, 100, 100), "test")) {
     *              HttpRequest req = new HttpRequest(RequestType.QUERY_PAY_STATUS, 2001, "ios");
     *              string json = @"{""act"":1002,""data"":{""p"":[{""ppid"":0,""pid"":110052,""num"":120}],""billStatus"":1,""vipStatus"":{""userVip"":1,""totalCach"":600,""toNextLevle"":600,""curStone"":130}}}";
     *              PayStatusResponse resp = fastJSON.JSON.Instance.ToObject<PayStatusResponse>(json);
     *              HttpResp_UI(req, resp);
     *      }
     * } */

    #region 网络返回
    void HttpResp_UI(BaseHttpRequest request, BaseResponse response)
    {
        ComLoading.Close();
        if (response != null && response.status != BaseResponse.ERROR)
        {
            HttpRequest myRequest = (HttpRequest)request;
            switch (myRequest.Type)
            {
            case RequestType.PAY:
                PayResponse payResp = response as PayResponse;
                if (!string.IsNullOrEmpty(payResp.data.orderId))
                {
                    m_strOrderId = payResp.data.orderId;
                    AccountData ad = Native.mInstace.m_thridParty.GetAccountData();
                    ad.payCallback = payResp.data.payCallback;
                    UIDragonMallMgr.GetInstance().mUIDragonRechargeMain.SetCurPayCell(this);
                    OpenThirdPayUI(payResp.data);
                }
                else
                {
                    RED.LogWarning("订单号为null");
                }
                break;

            case RequestType.QUERY_PAY_STATUS:
                PayStatusResponse resp = response as PayStatusResponse;

                RED.Log("收到订单状态:" + resp.data.billStatus);
                if (resp.data.billStatus == 1)                                          //重置成功,展示物品
                {
                    UIDragonMallMgr.GetInstance().mUIDragonRechargeMain.Refresh();
                    CancelInvoke();
                    if (resp.data.p != null)
                    {
                        int length = resp.data.p.Length;
                        for (int i = 0; i < length; i++)
                        {
                            Core.Data.itemManager.AddRewardToBag(resp.data.p[i]);
                            //talking data add by wxl
                            ItemData itemData = Core.Data.itemManager.getItemData(resp.data.p[i].pid);
                            if (itemData != null)
                            {
                                if (m_data != null)
                                {
                                    RechargeData tdata = Core.Data.rechargeDataMgr.GetRechargeData(m_data.ID);
                                    if (tdata != null && tdata.Present2 != null)
                                    {
                                        if (tdata.Present2.Count == 2)
                                        {
                                            Core.Data.ActivityManager.OnChargeSuccess(tdata.Title, tdata.ID.ToString(), tdata.Present2 [0] [1]);
                                        }
                                    }
                                }
                            }
                        }
                    }


                    UIDragonMallMgr mallMgr = UIDragonMallMgr.GetInstance();
                    if (resp.data.vipStatus != null)
                    {
                        Core.Data.playerManager.RTData.curStone = resp.data.vipStatus.curStone;

                        Core.Data.vipManager.vipStatus = resp.data.vipStatus;
                        RED.Log("left rmb:" + resp.data.vipStatus.toNextLevle);
                        int next  = resp.data.vipStatus.toNextLevle / 100;
                        int total = resp.data.vipStatus.totalCach / 100;
                        mallMgr.SeViptPercent(next, total);
                    }

                    mallMgr.mUIDragonRechargeMain.SetCurPayCell(null);
                    if (UIFirstRechargePanel.GetInstance() == null)
                    {
                        DBUIController.mDBUIInstance.RefreshUserInfo();
                    }
                    else
                    {
                        DBUIController.mDBUIInstance.RefreshUserInfoWithoutShow();
                        UIMiniPlayerController.Instance.freshPlayerInfoView();
                    }


                    GetRewardSucUI.OpenUI(resp.data.p, Core.Data.stringManager.getString(5210), true, () => {
                        //点击OK后,出现Vip信息
                        if (resp.data.vipStatus != null)
                        {
                            PlayerManager player = Core.Data.playerManager;
                            int temp             = player.RTData.curVipLevel;
                            int now = resp.data.vipStatus.userVip;
                            player.RTData.curVipLevel = now;
                            UIDragonMallMgr.GetInstance().VipRequest();
                            if (now > temp)
                            {
                                LevelUpUIOther.OpenUI();
                                LevelUpUIOther.mInstance.showVipUpdate(now);
                                SQYMainController.mInstance.RefreshVipLv();
                            }
                        }
                    });
                    //检测是否是 月卡
                    if (m_data.ID == 1)
                    {
                        ActivityNetController.GetInstance().GetMonthStateRequest();
                    }
                    //首充   2是已充已领   1是已充未领
                    if (LuaTest.Instance.OpenFirstCharge)
                    {
                        if (Core.Data.rechargeDataMgr._canGainFirstAward == 0 || Core.Data.rechargeDataMgr._canGainFirstAward == 1 || Core.Data.rechargeDataMgr._canGainFirstAward == -1)
                        {
                            ActivityNetController.GetInstance().GetFirstChargeStateRequest();
                        }
                    }
                }
                else if (resp.data.billStatus == 2)                             //充值成功,订单过期
                {
                    CancelInvoke();
                }
                break;
            }
        }
    }
Beispiel #24
0
        // # Pay API Operations
        // Use the Pay API operations to transfer funds from a sender’s PayPal account to one or more receivers’ PayPal accounts. You can use the Pay API operation to make simple payments, chained payments, or parallel payments; these payments can be explicitly approved, preapproved, or implicitly approved.
        public PayResponse PayAPIOperations(PayRequest reqPay, bool isPreapproved)
        {
            // Create the PayResponse object
            PayResponse responsePay = new PayResponse();

            try
            {
                // Create the service wrapper object to make the API call
                AdaptivePaymentsService service = new AdaptivePaymentsService();

                // # API call
                // Invoke the Pay method in service wrapper object
                responsePay = service.Pay(reqPay);

                if (responsePay != null)
                {
                    // Response envelope acknowledgement
                    string acknowledgement = "Pay API Operation - ";
                    acknowledgement += responsePay.responseEnvelope.ack.ToString();


                    // # Success values
                    if (responsePay.responseEnvelope.ack.ToString().Trim().ToUpper().Equals("SUCCESS"))
                    {
                        // The pay key, which is a token you use in other Adaptive
                        // Payment APIs (such as the Refund Method) to identify this
                        // payment. The pay key is valid for 3 hours; the payment must
                        // be approved while the pay key is valid.

                        // Once you get success response, user has to redirect to PayPal
                        // for the payment. Construct redirectURL as follows,
                        // `redirectURL=https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_ap-payment&paykey="
                        // + responsePay.payKey;`

                        string url = String.Format("https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_ap-payment&paykey={0}", responsePay.payKey);
                        if (isPreapproved)
                        {
                            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

                            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                            //if (response.StatusCode.ToString() == "OK")
                            //{
                            //    Console.WriteLine("PAY MENT SUCCESS");
                            //}
                        }
                        else
                        if (HttpContext.Current != null)
                        {
                            HttpContext.Current.Response.Redirect(url);
                        }
                    }
                    // # Error Values
                    else
                    {
                        List <ErrorData> errorMessages = responsePay.error;
                        foreach (ErrorData error in errorMessages)
                        {
                        }
                    }
                }
            }
            // # Exception log
            catch (System.Exception ex)
            {
                string temp = ex.StackTrace.ToString();
            }
            return(responsePay);
        }
        public ActionResult Payment(int?id)
        {
            string identity = System.Web.HttpContext.Current.User.Identity.GetUserId();

            if (identity == null)
            {
                return(RedirectToAction("Unauthorized_Access", "Home"));
            }
            var    completedList  = db.CompletedBids.ToList();
            string HomeOwnerEmail = "";
            string payeeEmail     = "";
            var    person         = db.Homeowners.Where(x => x.UserId == identity).SingleOrDefault();


            foreach (var user in db.Users)
            {
                if (user.Id == identity)
                {
                    payeeEmail = user.Email;
                }
            }

            foreach (var i in completedList)
            {
                if (id == i.ID)
                {
                    HomeOwnerEmail = i.HomeEmail;
                }
            }


            if (this.User.IsInRole("Admin") || HomeOwnerEmail == payeeEmail)
            {
                if (id == null)
                {
                    return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
                }
                CompletedBids completedBids = db.CompletedBids.Find(id);
                if (completedBids == null)
                {
                    return(HttpNotFound());
                }
                ReceiverList receiverList = new ReceiverList();
                receiverList.receiver = new List <Receiver>();
                Receiver receiver = new Receiver(completedBids.Bid);
                //var query = from v in db.Ventures where v.Id == bid.ventureID select v.investorID;
                //string receiverID = query.ToList().ElementAt(0);
                //ApplicationUser recvUser = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(receiverID.ToString());
                receiver.email   = "*****@*****.**";
                receiver.primary = true;
                receiverList.receiver.Add(receiver);
                Receiver receiver2 = new Receiver(completedBids.ContractorDue);
                //var query = from v in db.Ventures where v.Id == bid.ventureID select v.investorID;
                //string receiverID = query.ToList().ElementAt(0);
                //ApplicationUser recvUser = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(receiverID.ToString());
                receiver2.email   = completedBids.ConEmail;
                receiver2.primary = false;
                receiverList.receiver.Add(receiver2);
                RequestEnvelope requestEnvelope = new RequestEnvelope("en_US");
                string          actionType      = "PAY";
                string          successUrl      = "http://" + System.Web.HttpContext.Current.Request.Url.Authority + "/CompletedBids/SuccessView/{0}";
                string          failureUrl      = "http://" + System.Web.HttpContext.Current.Request.Url.Authority + "/CompletedBids/FailureView/{0}";
                successUrl = String.Format(successUrl, id);
                failureUrl = String.Format(failureUrl, id);
                string     returnUrl    = successUrl;
                string     cancelUrl    = failureUrl;
                string     currencyCode = "USD";
                PayRequest payRequest   = new PayRequest(requestEnvelope, actionType, cancelUrl, currencyCode, receiverList, returnUrl);
                payRequest.ipnNotificationUrl = "http://cf719b5f.ngrok.io";
                string memo = completedBids.Description + " Invoice = " + completedBids.Invoice;
                payRequest.memo = memo;
                Dictionary <string, string> sdkConfig = new Dictionary <string, string>();
                sdkConfig.Add("mode", "sandbox");
                sdkConfig.Add("account1.apiUsername", "mattjheller-facilitator_api1.yahoo.com");                    //PayPal.Account.APIUserName
                sdkConfig.Add("account1.apiPassword", "DG6GB55TRBWLESWG");                                          //PayPal.Account.APIPassword
                sdkConfig.Add("account1.apiSignature", "AFcWxV21C7fd0v3bYYYRCpSSRl31AafAKKwBsAp2EBV9PExGkablGWhj"); //.APISignature
                sdkConfig.Add("account1.applicationId", "APP-80W284485P519543T");                                   //.ApplicatonId

                AdaptivePaymentsService adaptivePaymentsService = new AdaptivePaymentsService(sdkConfig);
                PayResponse             payResponse             = adaptivePaymentsService.Pay(payRequest);
                ViewData["paykey"] = payResponse.payKey;

                //string payKey = payResponse.payKey; ////////
                //string paymentExecStatus = payResponse.paymentExecStatus;
                //string payURL = String.Format("https://www.sandbox.paypal.com/webscr?cmd=_ap-payment&paykey={0}", payKey);
                return(View(completedBids));
            }
            else
            {
                return(RedirectToAction("Unauthorized_Access", "Home"));
            }
        }
Beispiel #26
0
        public ActionResult PagarViaMasterCard(string SessioId, long id_produto, decimal valor, string oque_e, string checkIn = "", string checkOut = "", bool tem_entrega = false, int id_transportadora = 0, string local_entrega = "", string nome_destinatario = "", string contacto_destinatario = "")
        {
            try
            {
                string status       = "FAILED";
                string orderID      = RandomStringNumber();
                string transationID = RandomStringNumber();

                RestClient  restClient           = new RestClient("https://millenniumbim.gateway.mastercard.com");
                RestRequest authorizationRequest = new RestRequest("/api/rest/version/54/merchant/22599/order/" + orderID + "/transaction/" + transationID, Method.PUT);
                authorizationRequest.AddHeader("Content-Type", "application/json");
                authorizationRequest.AddHeader("Authorization", $"Basic bWVyY2hhbnQuMjI1OTk6YzQwZjE1MTQ0MmQ3ZmViYWQ2MDZmZDY1YjFkNjYzZDY=");

                var data = new PayRequest()
                {
                    apiOperation = "AUTHORIZE", session = new PayRequest.Session()
                    {
                        id = SessioId
                    }, sourceOfFunds = new PayRequest.SourceOfFunds()
                    {
                        type = "CARD"
                    }, order = new PayRequest.Order()
                    {
                        amount = valor, currency = "MZN"
                    }
                };
                authorizationRequest.AddJsonBody(data);
                var         response    = restClient.Execute <PayResponse>(authorizationRequest);
                PayResponse Autorizacao = response.Data;

                if (Autorizacao.result == "ERROR")
                {
                    //return Redirect("https://localhost:44360/PubMusica/PagamentoFalhou?erro=Houve um erro inesperado, volte a tentar mais tarde ou conatcte o administrador. Codigo do Erro: APIPAY01");
                    return(Redirect("https://www.mussika.co.mz/PubMusica/PagamentoFalhou?erro=Houve um erro inesperado, volte a tentar mais tarde ou conatcte o administrador. Codigo do Erro: APIPAY01"));
                }
                else
                {
                    if (Autorizacao.order.status == "AUTHORIZED")
                    {
                        RestRequest CaptureRequest = new RestRequest("/api/rest/version/54/merchant/22599/order/" + Autorizacao.order.id + "/transaction/" + RandomStringNumber(), Method.PUT);
                        CaptureRequest.AddHeader("Content-Type", "application/json");
                        CaptureRequest.AddHeader("Authorization", $"Basic bWVyY2hhbnQuMjI1OTk6YzQwZjE1MTQ0MmQ3ZmViYWQ2MDZmZDY1YjFkNjYzZDY=");

                        var data2 = new PayRequest()
                        {
                            transaction = new PayRequest.Transaction()
                            {
                                amount = valor, currency = "MZN"
                            }, apiOperation = "CAPTURE", session = new PayRequest.Session()
                            {
                                id = SessioId
                            }, sourceOfFunds = new PayRequest.SourceOfFunds()
                            {
                                type = "CARD"
                            }
                        };
                        CaptureRequest.AddJsonBody(data2);
                        var         captura    = restClient.Execute <PayResponse>(CaptureRequest);
                        PayResponse capturacao = captura.Data;

                        if (capturacao.order.status == "CAPTURED")
                        {
                            status = "CAPTURED";
                        }
                    }
                }



                if (status == "CAPTURED")
                {
                    return(Redirect("https://www.mussika.co.mz/payment/compra?id_produto=" + id_produto + "&valor=" + valor + "&oque_e=" + oque_e + "&checkIn=" + checkIn + "&checkOut=" + checkOut + "&tem_entrega =" + tem_entrega + "&id_transportadora =" + id_transportadora + "&local_entrega=" + local_entrega + "&nome_destinatario=" + nome_destinatario + "&contacto_destinatario=" + contacto_destinatario));
                    //return Redirect("https://localhost:44360/payment/compra?id_produto=" + id_produto + "&oque_e=" + oque_e);
                }
                else
                {
                    return(Redirect("https://www.mussika.co.mz/PubMusica/PagamentoFalhou?erro=" + status));
                    //return Redirect("https://localhost:44360/PubMusica/PagamentoFalhou?erro=" + status);
                }
            }
            catch (Exception)
            {
                return(Redirect("https://www.mussika.co.mz/PubMusica/PagamentoFalhou?erro=Houve um erro inesperado, volte a tentar mais tarde ou conatcte o administrador. Codigo do Erro: APIPAY-UNKNOW"));
                //return Redirect("https://localhost:44360/PubMusica/PagamentoFalhou?erro=Houve um erro inesperado, volte a tentar mais tarde ou conatcte o administrador. Codigo do Erro: APIPAY01");
            }
        }
Beispiel #27
0
        /// <summary>
        /// Handle Pay API calls
        /// </summary>
        /// <param name="context"></param>
        private void Pay(HttpContext context)
        {
            NameValueCollection parameters = context.Request.Params;
            ReceiverList receiverList = new ReceiverList();
            receiverList.receiver = new List<Receiver>();
            string[] amt = context.Request.Form.GetValues("receiverAmount");
            string[] receiverEmail = context.Request.Form.GetValues("receiverEmail");
            string[] phoneCountry = context.Request.Form.GetValues("phoneCountry");
            string[] phoneNumber = context.Request.Form.GetValues("phoneNumber");
            string[] phoneExtn = context.Request.Form.GetValues("phoneExtn");
            string[] primaryReceiver = context.Request.Form.GetValues("primaryReceiver");
            string[] invoiceId = context.Request.Form.GetValues("invoiceId");
            string[] paymentType = context.Request.Form.GetValues("paymentType");
            string[] paymentSubType = context.Request.Form.GetValues("paymentSubType");
            for (int i = 0; i < amt.Length; i++)
            {
                Receiver rec = new Receiver(Decimal.Parse(amt[i]));
                if(receiverEmail[i] != "")
                    rec.email = receiverEmail[i];
                if (phoneCountry[i] != "" && phoneNumber[i] != "")
                {
                    rec.phone = new PhoneNumberType(phoneCountry[i], phoneNumber[i]);
                    if (phoneExtn[i] != "")
                    {
                        rec.phone.extension = phoneExtn[i];
                    }
                }
                if (primaryReceiver[i] != "")
                    rec.primary = Boolean.Parse(primaryReceiver[i]);
                if (invoiceId[i] != "")
                    rec.invoiceId = invoiceId[i];
                if (paymentType[i] != "")
                    rec.paymentType = paymentType[i];
                if (paymentSubType[i] != "")
                    rec.paymentSubType = paymentSubType[i];
                receiverList.receiver.Add(rec);
            }            
            PayRequest req = new PayRequest(new RequestEnvelope("en_US"), parameters["actionType"], 
                                parameters["cancelUrl"], parameters["currencyCode"], 
                                receiverList, parameters["returnUrl"]);
            // set optional parameters
            if (parameters["reverseAllParallelPaymentsOnError"] != "")
                req.reverseAllParallelPaymentsOnError = 
                    Boolean.Parse(parameters["reverseAllParallelPaymentsOnError"]);
            if (parameters["senderEmail"] != "")
                req.senderEmail = parameters["senderEmail"];
            if (parameters["trackingId"] != "")
                req.trackingId = parameters["trackingId"];
            if (parameters["fundingConstraint"] != "")
            {
                req.fundingConstraint = new FundingConstraint();
                req.fundingConstraint.allowedFundingType = new FundingTypeList();
                req.fundingConstraint.allowedFundingType.fundingTypeInfo.Add(
                    new FundingTypeInfo(parameters["fundingConstraint"]));
            }
            if (parameters["emailIdentifier"] != ""
                || (parameters["senderPhoneCountry"] != "" && parameters["senderPhoneNumber"] != "")
                || parameters["useCredentials"] != "")
            {
                req.sender = new SenderIdentifier();
                if (parameters["emailIdentifier"] != "")
                    req.sender.email = parameters["emailIdentifier"];
                if (parameters["senderPhoneCountry"] != "" && parameters["senderPhoneNumber"] != "")
                {
                    req.sender.phone = new PhoneNumberType(parameters["senderPhoneCountry"], parameters["senderPhoneNumber"]);
                    if (parameters["senderPhoneExtn"] != "")
                        req.sender.phone.extension = parameters["senderPhoneExtn"];
                }
                if (parameters["useCredentials"] != "")
                    req.sender.useCredentials = Boolean.Parse(parameters["useCredentials"]);
            }

            // All set. Fire the request            
            AdaptivePaymentsService service = new AdaptivePaymentsService();
            PayResponse resp = null;
            try
            {
                resp = service.Pay(req);
            }
            catch (System.Exception e)
            {
                context.Response.Write(e.Message);
                return;
            }

            // Display response values. 
            Dictionary<string, string> keyResponseParams = new Dictionary<string, string>();
            string redirectUrl = null;
            if ( !(resp.responseEnvelope.ack == AckCode.FAILURE) && 
                !(resp.responseEnvelope.ack == AckCode.FAILUREWITHWARNING) )
            {
                redirectUrl = ConfigurationManager.AppSettings["PAYPAL_REDIRECT_URL"]
                                     + "_ap-payment&paykey=" + resp.payKey;
                keyResponseParams.Add("Pay key", resp.payKey);
                keyResponseParams.Add("Payment execution status", resp.paymentExecStatus);
                if (resp.defaultFundingPlan != null && resp.defaultFundingPlan.senderFees != null)
                {
                    keyResponseParams.Add("Sender fees", resp.defaultFundingPlan.senderFees.amount +
                                                resp.defaultFundingPlan.senderFees.code);
                }
            }
            displayResponse(context, "Pay", keyResponseParams, service.getLastRequest(), service.getLastResponse(), 
                resp.error, redirectUrl);            
        }
        public static String BuyTickets(string data)
        {
            bool   tableValid = true;
            String UserInfo   = ConfigurationManager.ConnectionStrings["KcGameOnSQL"].ConnectionString;

            //Payment paymnt = null;
            quantity  = 0;
            extraLife = 0.00;
            List <Users>         payment  = new List <Users>();
            JavaScriptSerializer json     = new JavaScriptSerializer();
            List <String[]>      mystring = json.Deserialize <List <string[]> >(data);

            for (int i = 0; i < mystring.Count; i++)
            {
                String user           = mystring.ElementAt(i).ElementAt(0).ToString();
                String first          = mystring.ElementAt(i).ElementAt(1).ToString();
                String last           = mystring.ElementAt(i).ElementAt(2).ToString();
                bool   byoc           = Convert.ToBoolean(mystring.ElementAt(i).ElementAt(6));
                Double donationAmount = Convert.ToDouble(mystring.ElementAt(i).ElementAt(5));

                MySqlCommand    cmd  = null;
                MySqlConnection conn = null;

                try
                {
                    conn = new MySqlConnection(UserInfo);
                    conn.Open();

                    cmd             = new MySqlCommand("spValidateUsersForPayment", conn);
                    cmd.CommandType = System.Data.CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("UserName", user);
                    cmd.Parameters.AddWithValue("Firstname", first);
                    cmd.Parameters.AddWithValue("Lastname", last);

                    int userValue = Convert.ToInt32(cmd.ExecuteScalar());

                    switch (userValue)
                    {
                    case -1:     // Successfully Validated
                        //if (mystring.ElementAt(i).ElementAt(0).Equals("True"))
                        //    quantity += remainingEvents;
                        //else
                        //    quantity += 1;
                        if (byoc)
                        {
                            byocQuantity += 1;
                        }
                        else
                        {
                            quantity += 1;
                        }
                        if (donationAmount > 0)
                        {
                            extraLife += donationAmount;
                        }
                        break;

                    case -2:     // Unsuccessfully validated
                        tableValid = false;
                        //return String.Format("User: {0}, {1}, {2} is not correct, please choose the correct username, first name, and last name.", user, first, last);
                        break;

                    default:
                        break;
                    }
                    conn.Close();
                }
                catch (Exception)
                {
                    //return "An internal error has occurred, please contact an administrator.";
                    //return;
                }
                finally
                {
                    if (conn != null)
                    {
                        conn.Close();
                    }
                }
            }
            if (tableValid)
            {
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                PayRequest  requestPay  = Payment(quantity, byocQuantity, extraLife);
                PayResponse responsePay = PayAPIOperations(requestPay);
                RedirectURL = "https://www.paypal.com/cgi-bin/webscr?cmd=_ap-payment&paykey=" + responsePay.payKey;
                //RedirectURL = "https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_ap-payment&paykey=" + responsePay.payKey;
                if (responsePay.payKey != null)
                {
                    for (int i = 0; i < mystring.Count; i++)
                    {
                        String fullYear;
                        String BYOC;
                        //if (mystring.ElementAt(i).ElementAt(0).ToString().Equals("True"))
                        //    fullYear = "Y";
                        //else
                        //    fullYear = "N";

                        // Change this to new column/variable for BYOC
                        if (Convert.ToBoolean(mystring.ElementAt(i).ElementAt(6)))
                        {
                            BYOC = "Y";
                        }
                        else
                        {
                            BYOC = "N";
                        }

                        String user   = mystring.ElementAt(i).ElementAt(1).ToString();
                        String payKey = responsePay.payKey;

                        String verfiedPaid   = "N";
                        String paymentMethod = "PayPal";

                        Double donationAmount = Convert.ToDouble(mystring.ElementAt(i).ElementAt(5));

                        MySqlCommand    cmd  = null;
                        MySqlConnection conn = null;

                        try
                        {
                            conn = new MySqlConnection(UserInfo);
                            conn.Open();

                            cmd             = new MySqlCommand("spAddPayment", conn);
                            cmd.CommandType = System.Data.CommandType.StoredProcedure;
                            cmd.Parameters.AddWithValue("Username", user);
                            cmd.Parameters.AddWithValue("VerifiedPaid", verfiedPaid);
                            //cmd.Parameters.AddWithValue("PaidFullYear", fullYear);
                            // Change this "PaidFullYear" to new column for BYOC also prob have to change the stored proc spAddPayment
                            cmd.Parameters.AddWithValue("PaidFullYear", BYOC);
                            cmd.Parameters.AddWithValue("PaymentMethod", paymentMethod);
                            cmd.Parameters.AddWithValue("PaymentKey", payKey);
                            cmd.Parameters.AddWithValue("DonationAmount", donationAmount);

                            int userValue = Convert.ToInt32(cmd.ExecuteScalar());
                        }
                        catch (Exception)
                        {
                            //return "An internal error has occurred, please contact an administrator.";
                            //return;
                        }
                        finally
                        {
                            if (conn != null)
                            {
                                conn.Close();
                            }
                        }
                    }
                }
                else
                {
                    quantity    = 0;
                    RedirectURL = "https://kcgameon.com/Default.aspx";
                    //RedirectURL = "https://nickthenerd.com/Default.aspx";
                }
            }
            //HttpContext.Current.Response.Redirect(RedirectURL, true);
            return(RedirectURL);
        }
Beispiel #29
0
        public void Pay()
        {
            Random r = new Random();
            int    PayPalPurchaseTransactionId = r.Next();      // -10;
            string PayPalRedirectUrl           = "www.cnn.com"; // ConfigurationManager.AppSettings["PAYPAL_REDIRECT_URL"];
            // Instantiate PayPalResponse class
            GIBSPayPal objPayPalResponse = new GIBSPayPal();

            objPayPalResponse.PayPalPaykey            = " ";
            objPayPalResponse.PayPalPaymentExecStatus = " ";
            objPayPalResponse.PayPalRedirectUrl       = PayPalRedirectUrl;
            objPayPalResponse.PayPalErrorMessage      = " ";
            objPayPalResponse.PayPalError             = false;
            string currentPath =
                System.Web.HttpContext.Current.Request.Url.OriginalString
                .Replace(@"/PayPal_Call_back.ashx", "");

            string strActionType = "PAY";
            string currencyCode  = "USD";
            string cancelUrl     = string.Format(@"{0}&mode=cancel", currentPath);
            string returnUrl     = String.Format(@"{0}&payment=complete", currentPath);
            string IpnURL        = String.Format(@"{0}/PayPal/IPNListener.aspx", currentPath);

            ReceiverList receiverList = new ReceiverList();

            receiverList.receiver = new List <Receiver>();

            Receiver Receiver1 = new Receiver(Decimal.Parse("5.59"));

            Receiver1.email     = "*****@*****.**";
            Receiver1.primary   = false;
            Receiver1.invoiceId = "";

            Receiver1.paymentType = "SERVICE";

            receiverList.receiver.Add(Receiver1);

            PayRequest req = new PayRequest(new RequestEnvelope("en_US"),
                                            strActionType,
                                            cancelUrl,
                                            currencyCode,
                                            receiverList,
                                            returnUrl);

            //// IPN Url (only enable with a published internet accessable application)
            //req.ipnNotificationUrl = IpnURL;
            //req.reverseAllParallelPaymentsOnError = true;
            //req.trackingId = PayPalPurchaseTransactionId.ToString();


            // Call PayPal to get PayKey
            Dictionary <string, string> configMap = new Dictionary <string, string>();

            //configMap = GetConfig();
            configMap.Add("mode", "sandbox");
            // Signature Credential
            configMap.Add("account1.apiUsername", "joe-facilitator_api1.gibs.com");
            configMap.Add("account1.apiPassword", "5UX8EJBTREJQ33MH");
            configMap.Add("account1.apiSignature", "An5ns1Kso7MWUdW4ErQKJJJ4qi4-AM3p4jdO1vcSS2ClRObAqbmoxWeN");
            configMap.Add("account1.applicationId", "APP-80W284485P519543T");

            //configMap.Add("account1.apiUsername", "joe_api1.gibs.com");
            //configMap.Add("account1.apiPassword", "Y5M699WXLTEF976T");
            //configMap.Add("account1.apiSignature", "AUHOQLvCB6h8yLQ2ZC0YcUb3EuZjAY-OG4J5Hkaj35SjMEkMxhoMslvt");
            //configMap.Add("account1.applicationId", "APP-80W284485P519543T");
            // Sandbox Email Address
            //configMap.Add("sandboxEmailAddress", "*****@*****.**");

            AdaptivePaymentsService service = new AdaptivePaymentsService(configMap);
            PayResponse             resp    = null;

            try
            {
                resp = service.Pay(req);
            }

            catch (System.Exception e)
            {
                objPayPalResponse.PayPalError        = true;
                objPayPalResponse.PayPalErrorMessage = e.Message;
                PayPalPaykey = " Catch " + e.Message; // resp.payKey;
            }
            // Check for errors
            if ((resp.responseEnvelope.ack == AckCode.FAILURE) ||
                (resp.responseEnvelope.ack == AckCode.FAILUREWITHWARNING))
            {
                string strError = "";
                objPayPalResponse.PayPalError = true;
                foreach (var error in resp.error)
                {
                    strError = strError + " " + error.message;
                }
                objPayPalResponse.PayPalErrorMessage = strError;
                PayPalPaykey = " " + strError;// resp.payKey;
            }
            else
            {
                objPayPalResponse.PayPalPaykey = resp.payKey;
                PayPalPaykey = resp.payKey;
                objPayPalResponse.PayPalPaymentExecStatus = resp.paymentExecStatus;
            }
        }
Beispiel #30
0
        public ActionResult Index(string orderId)
        {
            var           response    = new BaseResponse();
            BaseRequest   baseRequest = new BaseRequest();
            ServiceResult result      = new ServiceResult();
            var           bizCode     = string.Empty;
            string        errMsg      = "";
            PayOrder      order       = null;
            PayChannel    payChannel  = null;

            if (orderId.IsNullOrWhiteSpace())
            {
                return(Json(result.IsFailed("参数错误,orderid")));
            }
            //订单校验
            if (!OrderVerify(orderId, out order, out payChannel, out errMsg))
            {
                return(Json(result.IsFailed(errMsg)));
            }

            baseRequest.Order      = order;
            baseRequest.PayChannel = payChannel;
            bizCode = payChannel.ChannelCode;
            if (bizCode.IsNullOrWhiteSpace())
            {
                return(Json(result.IsFailed("无效交易类型,ChannelCode为空")));
            }

            if (!ProcessorUtil.BizCodeValid(bizCode))
            {
                return(Json(result.IsFailed("支付标识和DescriptionAttribute不一致")));
            }
            var processor = this.factory.Create(bizCode);

            //构建请求参数
            var payParams = processor.CreatePayRequest(baseRequest);

            //如果是浏览器表单提交
            if (processor.IsPostForm)
            {
                ViewData["url"]    = processor.PayUrl;
                ViewData["method"] = processor.RequestMethod;
                return(View(payParams));
            }

            //异步请求
            PayResponse payResponse = processor.Process(payParams);

            if (!payResponse.Success)
            {
                return(Json(result.IsFailed(payResponse.Message)));
            }
            switch (processor.PayModel)
            {
            case PayModelEnum.无:
                break;

            case PayModelEnum.URL跳转:
                return(Redirect(payResponse.Data));

            case PayModelEnum.扫码:
                break;

            case PayModelEnum.二维码生成:
                return(QRCode(payResponse.Data));

            case PayModelEnum.HTML输出:
                return(Content(payResponse.Data, "text/html"));

            default:
                break;
            }
            return(View());
        }