Пример #1
0
        public ActionResult PaymentResponse(
            String VERSION, String STAMP, String REFERENCE,
            String PAYMENT, String STATUS, String ALGORITHM, String MAC)
        {
            PaymentResponse paymentResponse = new PaymentResponse();

            paymentResponse.SetValues(merchantSecretKey, Request.Params);

            //if response valid (ok data)
            if (paymentResponse.IsValid())
            {
                ViewBag.PaymentResponseMessage =
                    PaymentUtils.GetPaymentResponseStatusMessage(paymentResponse.Status);
            }
            else //invalid response (corrupt data)
            {
                ViewBag.PaymentResponseMessage = "response invalid";
                return(View("PaymentResponseError"));
            }

            //set form values ready for payment status query
            QueryViewModel queryViewModel = new QueryViewModel();

            queryViewModel.Stamp     = paymentResponse.Stamp;
            queryViewModel.Reference = paymentResponse.Reference;
            //Get Amount from Session, because it's not available
            //from PaymentResponse (for testing).
            queryViewModel.Amount = (string)Session["Amount"];

            return(View(queryViewModel));
        }
Пример #2
0
        public ActionResult Query(QueryViewModel queryViewModel)
        {
            //testing query functionality
            Query query = new Query();

            query.InitializeValues(queryViewModel.Stamp, queryViewModel.Reference,
                                   this.merchantId, queryViewModel.Amount, this.merchantSecretKey);

            //send Query to Checkout Finland
            try
            {
                ViewBag.QueryResponse = CheckoutClient.postQueryData(query.FormData());
            }
            catch (WebException ex)
            {
                //exception handling for testing
                ViewBag.PaymentResponseMessage = "error: " + ex.ToString();
                return(View("PaymentResponseError"));
            }

            //get status value
            XDocument xmlDoc      = XDocument.Parse(ViewBag.QueryResponse);
            XElement  statusNode  = (XElement)xmlDoc.FirstNode;
            string    statusValue = statusNode.Value;

            ViewBag.QueryResponseMessage =
                PaymentUtils.GetPaymentResponseStatusMessage(statusValue);

            return(View());
        }
Пример #3
0
    /// <summary>
    /// Check received signature validity.
    ///
    /// Vérification de la signature reçue.
    /// </summary>
    /// <param name="values">Received data.</param>
    /// <param name="shakey">The secret key.</param>
    /// <returns>True if received signature is the same as computed one.</returns>
    private bool CheckAuthenticity(NameValueCollection values, string shakey)
    {
        // Compute the signature.
        string computedSign = PaymentUtils.GetSignature(values, shakey);

        // Check signature consistency.
        return(String.Equals(values.Get("signature"), computedSign, System.StringComparison.InvariantCultureIgnoreCase));
    }
Пример #4
0
        public ActionResult AccountsBalance()
        {
            //Redirect Based on Business Rules
            PaymentUtils.PrePageLoadRedirectUrlsAccountsBalance();

            AccountsBalanceHelper accountsBalanceRepo = new AccountsBalanceHelper();
            var model = accountsBalanceRepo.GetOwnerAssociationBalance();

            Session["AccountPaymentData"] = model.AccountList;
            return(View(model));
        }
Пример #5
0
        /// <summary>
        /// 获取扫码支付的Html
        /// </summary>
        /// <param name="transaction">支付交易</param>
        /// <returns></returns>
        public virtual HtmlString GetQRCodePaymentHtml(PaymentTransaction transaction)
        {
            var templateManager = Application.Ioc.Resolve <TemplateManager>();

#if !NETCORE
            // 获取商户Id等设置
            var apiData = transaction.Api.ExtraData.GetOrDefault <ApiData>("ApiData") ?? new ApiData();
            // 获取货币信息,目前仅支持人民币支付
            var currencyManager = Application.Ioc.Resolve <CurrencyManager>();
            var info            = currencyManager.GetCurrency(transaction.CurrencyType);
            if (info == null || info.Type != "CNY")
            {
                return(new HtmlString(templateManager.RenderTemplate(
                                          "finance.payment/error_text.html",
                                          new { error = new T("Alipay only support CNY") })));
            }
            // 如果交易之前没有获取过二维码Url,则通过支付宝Api获取二维码Url
            // 当前沙箱环境中交易流水号相同时不会重复创建支付宝交易,仅可能会返回不同的二维码
            // 如果正式环境有变化可能需要做出更多处理,例如缓存之前的二维码(并考虑二维码的过期时间)
            var client  = GetAopClient(apiData);
            var request = new AlipayTradePrecreateRequest();
            request.BizContent = JsonConvert.SerializeObject(new {
                out_trade_no = transaction.Serial,                             // 交易流水号
                seller_id    = apiData.PayeePartnerId,                         // 收款商户Id
                total_amount = transaction.Amount.ToString("0.00"),            // 金额
                subject      = transaction.Description.TruncateWithSuffix(15), // 交易标题
                body         = transaction.Description,                        // 交易描述
            }, Formatting.Indented);
            var notifyUrl = PaymentUtils.GetReturnOrNotifyUrl(
                apiData.ReturnDomain, AlipayQRCodePayNotifyUrl);
            request.SetNotifyUrl(notifyUrl);
            var response = client.Execute(request);
            if (response.IsError)
            {
                return(new HtmlString(templateManager.RenderTemplate(
                                          "finance.payment/error_text.html",
                                          new { error = $"{response.Msg}: {response.SubMsg}" })));
            }
            // 生成二维码图片
            var generator    = new QRCodeGenerator();
            var qrCodeData   = generator.CreateQrCode(response.QrCode, QRCodeGenerator.ECCLevel.Q);
            var qrCode       = new Base64QRCode(qrCodeData);
            var qrCodeBase64 = qrCode.GetGraphic(20);
            // 返回模板
            return(new HtmlString(templateManager.RenderTemplate(
                                      "finance.payment.alipaymobile/qrcode_pay.html",
                                      new { transactionId = transaction.Id, qrCodeBase64 })));
#else
            return(new HtmlString(templateManager.RenderTemplate(
                                      "finance.payment/error_text.html",
                                      new { error = new T("Alipay qrcode pay is unsupported on .net core yet") })));
#endif
        }
Пример #6
0
 /// <summary>
 /// 初始化
 /// </summary>
 /// <param name="apiData">接口数据</param>
 public WxPayConfig(WechatApiHandler.ApiData apiData)
 {
     APPID            = apiData.AppId;
     MCHID            = apiData.PartnerId;
     KEY              = apiData.PartnerKey;
     APPSECRET        = null;
     SSLCERT_PATH     = null;
     SSLCERT_PASSWORD = null;
     NOTIFY_URL       = PaymentUtils.GetReturnOrNotifyUrl(
         apiData.ReturnDomain, WeChatQRCodePayNotifyUrl);
     var ipAddress = NetworkUtils.GetClientIpAddress();
 }
Пример #7
0
        public ActionResult AccountsBalance(AccountViewModel account)
        {
            AccountsBalanceHelper accountsBalanceHelper = new AccountsBalanceHelper();

            try
            {
                if (!ModelState.IsValid || !accountsBalanceHelper.ValidateAccountData(account))
                {
                    throw new Exception();
                }

                Session.Add("AccountDetails", account);
                //Session["PaymentProjNo"] = account.GroupID;
                //Session["ProjectName"] = account.GroupTitle;
                //Session["TotalDue"] = account.UserPayInfoList.Select(x => x.PaymentAmount).Sum();

                //var accountData = accountsBalanceHelper.GetAccountInfoForProject(account.GroupID);
                //var accList = account.UserPayInfoList.Select<AccountBalanceInfo, AccountDetailsForACH>(x => GetAccountDetailsForACH(x, account.GroupID)).ToList();
                //Session["AccountList"] = accList;
                //Session["accNumList"] = accList.Select(x => x.accountNumber).ToList();
                //Session["PaymentPayments"] = accList.Select(x => x.paymentamount).ToList();
                //Session["ArdaCollections"] = account.UserPayInfoList.Select(x => !x.IsARDAAmount && x.ARDAAmount > 0 ? "Y" : "").ToList();

                var context = new SitecoreContext();
                PaymentsConfiguration getContextItem = context.GetItem <PaymentsConfiguration>(PaymentsConfiguration.PaymentsConfigurationItem);

                var pathInfo = getContextItem?.PaymentsOptionPage?.Url;
                PaymentUtils.RedirectToPage(pathInfo);
                ModelState.Clear();
                return(null);
            }
            catch (Exception ex)
            {
                ModelState.Clear();
                return(AccountsBalance());
            }
        }
Пример #8
0
    protected void Page_Load(object sender, EventArgs e)
    {
        Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);

        string shakey = "PRODUCTION".Equals(config.AppSettings.Settings["ctx_mode"].Value) ? // Choose PRODUCTION or TEST SHA key.
                        config.AppSettings.Settings["key_prod"].Value :
                        config.AppSettings.Settings["key_test"].Value;

        // If vads_hash is present, then the request came from IPN call.
        if (Request.Form.Get("vads_hash") != null)
        {
            //
            // The order processing will be done here. The return to shop code part should be used only for displaying the payment result to the buyer.
            //
            // Le traitement de la commande se fera ici. La partie du code pour le retour à la boutique ne doit servir qu'à l'affichage du résultat pour l'acheteur.
            //

            // Check signature consistency.
            if (CheckAuthenticity(Request.Form, shakey))
            {
                // Use order ID to find the order to update.
                string orderId = Request.Params.Get("vads_order_id");

                // The signature is valid, we can continue processing.

                PaymentStatus status = PaymentUtils.GetPaymentStatus(Request.Params.Get("vads_trans_status"));
                if (PaymentStatus.ACCEPTED.Equals(status))
                {
                    // Payment accepted.
                    // Insert your logic here to register order, manage stock, empty shopping cart, send e-mail confirmation and more.
                    Response.Write("OK-Accepted payment, order has been updated.");
                }
                else if (PaymentStatus.PENDING.Equals(status))
                {
                    // Payment is pending.
                    // Insert your logic here to make order in a pending status, empty shopping cart and send notification about order processing.
                    Response.Write("OK-Accepted payment, order has been updated.");
                }
                else
                {
                    // Payment cancelled by the buyer or payment failed.
                    // Insert your logic here to cancel order if already created.
                    Response.Write("OK-Payment failure, order has been cancelled.");
                }
            }
            else
            {
                //
                // The computed signature is not the same as the received one. Potential risk of fraud. The received data should not be used to process order.
                //
                // La signature calculée ne correpond pas à la signature reçue. Risque potentiel de fraude. Les données reçues ne doivent pas être prises en compte pour le traitement de la commande.
                //

                // Specific error management here.
                Response.Write("KO-An error occurred while computing the signature.");
            }
        }
        else if (Request.Params.Get("vads_site_id") != null)
        {
            //
            // Return to shop case: We use Request.Params to get received parameters (either return mode is GET or POST).
            // Note : the siganture validity check is not mandatory on the return to shop because order processing is not done here.
            //
            // Cas du retour à la boutique: Nous utilisons Request.Params pour récupérer les paramètres reçus (si le mode de retour est GET ou POST).
            // Remarque: Il n'est pas obligatoire de calculer la signature sur le retour boutique, le traitement de la commande n'étant pas réalisé ici.
            //

            // In test mode, display response parameters.
            if ("TEST".Equals(Request.Params.Get("vads_ctx_mode")))
            {
                int i = 1;
                foreach (string key in Request.Params.AllKeys)
                {
                    if (key == null)
                    {
                        continue;
                    }

                    if (!key.StartsWith("vads_"))
                    {
                        continue;
                    }

                    Label field = (Label)this.FindControl("ctl00$Content$ResultData" + i);
                    field.Text += "[" + key + "=" + Request.Params.Get(key) + "]<br />";

                    if (i == 2)
                    {
                        i = 1;
                    }
                    else
                    {
                        i++;
                    }
                }

                Signature.Text = "[signature=" + Request.Params.Get("signature") + "]";

                // In this example, we add this line to display the unhashed signature string in TEST mode.
                UnhashedSignature.Text = PaymentUtils.GetSignature(Request.Params, shakey, false);
            }

            // Check signature consistency.
            if (CheckAuthenticity(Request.Params, shakey))
            {
                //
                // Here we check payment result to know which message to show to the buyer.
                // Ici nous vérifions le résultat du paiement pour déterminer le message à afficher à l'acheteur.
                //

                PaymentStatus status = PaymentUtils.GetPaymentStatus(Request.Params.Get("vads_trans_status"));
                if (PaymentStatus.ACCEPTED.Equals(status))
                {
                    // Payment accepted. Insert your code here.
                    ResultMsg.Text = Resources.WebResources.SuccessMsg;
                }
                else if (PaymentStatus.PENDING.Equals(status))
                {
                    // Payment is pending. Insert your code here.
                    ResultMsg.Text = Resources.WebResources.PendingMsg;
                }
                else if (PaymentStatus.CANCELLED.Equals(status))
                {
                    // Payment cancelled by buyer. Insert your code here.
                    ResultMsg.Text = Resources.WebResources.CancelMsg;
                }
                else
                {
                    // Payment failed. Insert your code here.
                    ResultMsg.Text = Resources.WebResources.FailureMsg;
                }
            }
            else
            {
                // Signature error. Manage error here.
                ResultMsg.Text = Resources.WebResources.FatalErrorMsg;
            }
        }
        else
        {
            //
            // Client return without parameters (vads_return_mode = NONE). Insert your processing code here.
            //
            // Retour navigateur sans paramètres (vads_return_mode = NONE). Inserez votre code de traitement ici.
            //
        }
    }
Пример #9
0
        public ActionResult Payment(PaymentViewModel paymentViewModel)
        {
            //the below creates for example
            //URL: http://localhost:53416/Checkout/PaymentResponse
            string urlBeginning = this.TestUrl();
            string returnURL    = urlBeginning + "/Checkout/PaymentResponse";
            string cancelURL    = urlBeginning + "/Checkout/PaymentResponse";
            string rejectURL    = urlBeginning + "/Checkout/PaymentResponse";
            string delayedURL   = urlBeginning + "/Checkout/PaymentResponse";

            //Create Payment
            Payment payment = new Payment();

            //set merchant data (required)
            payment.InitializeValues(merchantId, merchantSecretKey);

            //other required parameters
            payment.Stamp = DateTime.Now.ToString("MMddyyyyhhmmssfff");
            string modifiedAmount = PaymentUtils.ModifyAmount(paymentViewModel.Amount); // remove comma or dot

            payment.Amount       = modifiedAmount;                                      // 1 Euro minimum purchase (100 cents)
            Session["Amount"]    = modifiedAmount;                                      //store Amount in Session for Query (just for testing)
            payment.Reference    = "123456";
            payment.ReturnUrl    = returnURL;
            payment.CancelUrl    = cancelURL;
            payment.DeliveryDate = DateTime.Now.ToString("yyyyMMdd");

            payment.Language = paymentViewModel.Language; // (required param)
            payment.Country  = "FIN";                     // (required)

            payment.Device = paymentViewModel.Device;     //HTML or XML

            //Optional
            payment.RejectUrl  = rejectURL;
            payment.DelayedUrl = delayedURL;
            payment.FirstName  = paymentViewModel.FirstName;
            payment.FamilyName = paymentViewModel.FamilyName;
            payment.Address    = paymentViewModel.Address;
            payment.Postcode   = paymentViewModel.Postcode;
            payment.PostOffice = paymentViewModel.PostOffice;
            payment.Message    = paymentViewModel.Message;

            payment.Validate(); //optional validation (Checkout Finland validates data too)

            //Send payment data to Checkout Finland,
            //then make received payment options available
            //to the view in ViewBag
            try
            {
                ViewBag.BankPaymentOptions = CheckoutClient.postPaymentData(payment.FormData());
            }
            catch (WebException ex)
            {
                //exception handling for testing
                ViewBag.PaymentResponseMessage = "error: " + ex.ToString();
                return(View("PaymentResponseError"));
            }

            //if device HTML (1), then use view for HTML page
            if (payment.Device.Equals(Checkout.Payment.Device_HTML))
            {
                return(View("BankPaymentOptionsHtml"));
            }
            else //parse XML format
            {
                //pass merchant info for view (optional)
                //some of this data is also available
                //from Payment object and XML response
                ViewBag.MerchantNameAndVatId          = "Testi Oy (123456-7)";
                ViewBag.MerchantEmail                 = "*****@*****.**";
                ViewBag.MerchantAddress               = "Testikuja 1";
                ViewBag.MerchantPostCodeAndPostOffice = "12345 Testilä";
                ViewBag.MerchantPhone                 = "012-345 678";

                //translations for Xml view
                ViewBag.Translations = PaymentUtils.TranslationsForXml[payment.Language];

                //payment for view
                ViewBag.Payment = payment;

                return(View("BankPaymentOptionsXML"));
            }
        }
Пример #10
0
        /// <summary>
        /// 获取支付凭据
        /// </summary>
        /// <param name="transactionId">交易Id</param>
        /// <param name="paymentChannel">支付渠道</param>
        /// <param name="userAgent">客户端的UserAgent</param>
        /// <param name="ipAddress">客户端的Ip地址</param>
        /// <param name="charge">返回的支付凭据</param>
        /// <param name="realResultUrl">返回的结果Url</param
        /// <param name="waitResultUrl">等待返回的结果Url</param>>
        public virtual void GetCharge(
            Guid transactionId, string paymentChannel, string userAgent, string ipAddress,
            out Charge charge, out string realResultUrl, out string waitResultUrl)
        {
            var transactionManager = Application.Ioc.Resolve <PaymentTransactionManager>();
            PaymentTransaction transaction;
            PaymentApi         api;
            ApiData            apiData;

            using (UnitOfWork.Scope()) {
                // 获取交易和支付接口
                transaction = transactionManager.Get(transactionId);
                api         = transaction == null ? null : transaction.Api;
                // 检查交易和接口是否存在
                if (transaction == null)
                {
                    throw new BadRequestException(new T("Payment transaction not found"));
                }
                else if (api == null)
                {
                    throw new BadRequestException(new T("Payment api not exist"));
                }
                // 检查当前登录用户是否可以支付
                var result = transaction.Check(c => c.IsPayerLoggedIn);
                if (!result.First)
                {
                    throw new BadRequestException(result.Second);
                }
                result = transaction.Check(c => c.IsPayable);
                if (!result.First)
                {
                    throw new BadRequestException(result.Second);
                }
                apiData = transaction.Api.ExtraData.GetOrDefault <ApiData>("ApiData") ?? new ApiData();
            }
            // 检查货币,虽然Ping++有提供货币参数但是支付渠道里面都只能支付人民币
            if (transaction.CurrencyType != "CNY")
            {
                throw new BadRequestException(new T("Ping++ only support cny payment"));
            }
            // 获取Ping++的支付凭据
            // 注意这里非线程安全,如果添加多个Ping++接口可能会出问题
            Pingpp.SetApiKey(apiData.TradeSecretKey);
            Pingpp.SetPrivateKey(apiData.PartnerRsaPrivateKey);
            var configManager   = Application.Ioc.Resolve <GenericConfigManager>();
            var websiteSettings = configManager.GetData <WebsiteSettings>();
            var extra           = new Dictionary <string, object>();

            realResultUrl = PaymentUtils.GetReturnOrNotifyUrl(
                apiData.ReturnDomain,
                transactionManager.GetResultUrl(transactionId));
            waitResultUrl = PaymentUtils.GetReturnOrNotifyUrl(
                apiData.ReturnDomain,
                GetWaitResultUrl(transactionId));
            if (paymentChannel == "alipay_wap" ||
                paymentChannel == "alipay_pc_direct")
            {
                // 支付宝支付
                extra["success_url"] = waitResultUrl;
            }
            else if (paymentChannel == "bfb_wap")
            {
                // 百度钱包支付
                extra["result_url"] = waitResultUrl;
                extra["bfb_login"]  = apiData.BfbRequireLogin;
            }
            else if (paymentChannel == "upacp_wap" ||
                     paymentChannel == "upacp_pc")
            {
                // 银联支付
                extra["result_url"] = waitResultUrl;
            }
            else if (paymentChannel == "wx" ||
                     paymentChannel == "wx_pub" ||
                     paymentChannel == "wx_pub_qr" ||
                     paymentChannel == "wx_wap")
            {
                // 微信支付
                if (apiData.WeChatNoCredit)
                {
                    extra["limit_pay"] = "no_credit";
                }
                if (paymentChannel == "wx_pub")
                {
                    extra["open_id"] = apiData.WeChatOpenId;
                }
                else if (paymentChannel == "wx_pub_qr")
                {
                    extra["product_id"] = transaction.ExtraData
                                          .GetOrDefault <string>("WeChatProductId") ?? "0";
                }
                else if (paymentChannel == "wx_wap")
                {
                    extra["result_url"] = waitResultUrl;
                }
            }
            else if (paymentChannel == "jdpay_wap")
            {
                // 京东支付
                extra["success_url"] = waitResultUrl;
                extra["fail_url"]    = realResultUrl;
            }
            else if (paymentChannel == "fqlpay_wap")
            {
                // 分期乐支付
                extra["c_merch_id"] = apiData.FqlChildMerchantId;
                extra["return_url"] = waitResultUrl;
            }
            else if (paymentChannel == "qgbc_wap")
            {
                // 量化派支付
                extra["phone"] = transaction.ExtraData
                                 .GetOrDefault <string>("QgbcBuyerMobile") ?? "0";
                extra["return_url"] = waitResultUrl;
            }
            else if (paymentChannel == "qpay")
            {
                // QQ钱包
                var isIOS = userAgent.Contains("iphone") || userAgent.Contains("ipad");
                extra["device"] = isIOS ? "ios" : "android";
            }
            var chargeParams = new Dictionary <string, object>
            {
                { "order_no", transaction.Serial },
                { "amount", checked ((int)(transaction.Amount * 100)) },
                { "channel", paymentChannel },
                { "currency", "cny" },
                { "subject", $"{new T(websiteSettings.WebsiteName)} {transaction.Serial}" },
                { "body", transaction.Description },
                { "client_ip", ipAddress },
                { "app", new Dictionary <string, string> {
                      { "id", apiData.PingppAppId }
                  } },
                { "extra", extra }
            };

            charge = Charge.Create(chargeParams);
        }
Пример #11
0
        /// <summary>
        /// 获取支付Html
        /// </summary>
        /// <param name="transaction">支付交易</param>
        /// <returns></returns>
        public virtual HtmlString GetPaymentHtml(PaymentTransaction transaction)
        {
            var templateManager = Application.Ioc.Resolve <TemplateManager>();

#if !NETCORE
            // 获取商户Id等设置
            var apiData = transaction.Api.ExtraData.GetOrDefault <ApiData>("ApiData") ?? new ApiData();
            // 获取即时和异步返回地址
            var transactionManager = Application.Ioc.Resolve <PaymentTransactionManager>();
            var returnUrl          = PaymentUtils.GetReturnOrNotifyUrl(apiData.ReturnDomain, AlipayReturnUrl);
            var notifyUrl          = PaymentUtils.GetReturnOrNotifyUrl(apiData.ReturnDomain, AlipayNotifyUrl);
            // 获取货币信息,目前仅支持人民币支付
            var currencyManager = Application.Ioc.Resolve <CurrencyManager>();
            var info            = currencyManager.GetCurrency(transaction.CurrencyType);
            if (info == null || info.Type != "CNY")
            {
                return(new HtmlString(templateManager.RenderTemplate(
                                          "finance.payment/error_text.html",
                                          new { error = new T("Alipay only support CNY") })));
            }
            // 设置参数
            // 这里没有设置的参数有
            // anti_phishing_key 防钓鱼时间戳 目前不支持
            // exter_invoke_ip 客户端的IP地址 目前不支持, 防止多IP的用户不能使用
            // receive_name, receive_address, receive_zip, receive_phone, receive_mobile 目前不支持
            var parameters = new SortedDictionary <string, string>();
            parameters["partner"]           = apiData.PartnerId;                              // 商户Id
            parameters["seller_id"]         = apiData.PayeePartnerId;                         // 收款支付宝账号, 一般情况下收款账号就是签约账号
            parameters["_input_charset"]    = Config.input_charset;;                          // 请求编码,默认是utf-8
            parameters["payment_type"]      = Config.payment_type;                            // 支付类型,必须是1
            parameters["notify_url"]        = notifyUrl;                                      // 异步通知url
            parameters["return_url"]        = returnUrl;                                      // 同步返回url
            parameters["anti_phishing_key"] = Config.anti_phishing_key;                       // 防钓鱼时间戳, 目前不使用
            parameters["exter_invoke_ip"]   = Config.exter_invoke_ip;                         // 客户端的IP地址, 目前不使用
            parameters["out_trade_no"]      = transaction.Serial;                             // 交易流水号
            parameters["subject"]           = transaction.Description.TruncateWithSuffix(15); // 交易标题
            parameters["body"]     = transaction.Description;                                 // 交易描述
            parameters["show_url"] = new Uri(returnUrl).GetLeftPart(UriPartial.Authority);    // 商品展示地址,这里使用网站首页
            if (apiData.ServiceType == (int)AlipayServiceTypes.ImmediateArrival)
            {
                // 即时到账
                parameters["service"]   = "create_direct_pay_by_user";               // 服务类型 即时到账
                parameters["total_fee"] = transaction.Amount.ToString("0.00");       // 金额
            }
            else if (apiData.ServiceType == (int)AlipayServiceTypes.SecuredTransaction ||
                     apiData.ServiceType == (int)AlipayServiceTypes.DualInterface)
            {
                // 担保交易或双接口
                if (apiData.ServiceType == (int)AlipayServiceTypes.SecuredTransaction)
                {
                    parameters["service"] = "create_partner_trade_by_buyer";                     // 服务类型 担保交易
                }
                else
                {
                    parameters["service"] = "trade_create_by_buyer";                   // 服务类型 双接口
                }
                parameters["price"]             = transaction.Amount.ToString("0.00"); // 金额
                parameters["quantity"]          = "1";                                 // 商品数量,支付宝推荐为1
                parameters["logistics_fee"]     = "0";                                 // 物流费用,这套系统不支持单独传入物流费用
                parameters["logistics_type"]    = "EXPRESS";                           // 快递(可选EXPRESS, POST, EMS)
                parameters["logistics_payment"] = "SELLER_PAY";                        // 因为物流费用不单独算,只能用卖家承担运费
            }
            else if (apiData.ServiceType == (int)AlipayServiceTypes.WapPay)
            {
                // 手机支付
                parameters["service"]   = "alipay.wap.create.direct.pay.by.user";              // 服务类型 手机支付
                parameters["total_fee"] = transaction.Amount.ToString("0.00");                 // 金额
            }
            // 创建并返回支付Html
            var submit = new Submit(apiData.PartnerId, apiData.PartnerKey);
            var html   = submit.BuildRequest(parameters, "get", "submit");
            return(new HtmlString(html));
#else
            return(new HtmlString(templateManager.RenderTemplate(
                                      "finance.payment/error_text.html",
                                      new { error = new T("Alipay is unsupported on .net core yet") })));
#endif
        }
Пример #12
0
    protected void PayButton_Click(object sender, EventArgs e)
    {
        //
        // Configuration settings such as shop ID and keys are stored in Web.config file. These settings will be available throught the config object below.
        //
        // Les paramètres de configuration tels que l'identifiant de la boutique et les clés sont stockés dans le fichier Web.config. Ces paramètres seront accessibles au travers de l'objet config ci-dessous.
        //
        Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);

        //
        // Prepare form data to be posted to payment gateway :
        // - The use of SortedDictionary<key, value> allow sorting data alphabetically to compute signature.
        // - To add field, use the method SortedDictionary.Add().
        // - Keys and values must be strings.
        // - The data sort order is case insensitive.
        //
        // Préparation des données du formulaire à poster à la plateforme de paiement :
        // - L'utilisation d'un SortedDictionary<clé, valeur> permet d'organiser les données par ordre alphabétique en vue de calculer la signature.
        // - L'ajout d'un champ se fait avec la méthode SortedDictionary.Add().
        // - Les clés et les valeurs stockées doivent être de type string.
        // - Le tri par ordre alphabétique ne tient pas compte de la casse.
        //

        var data = new SortedDictionary <string, string>(StringComparer.InvariantCultureIgnoreCase);

        //
        // Mandatory parameters.
        //

        data.Add("vads_site_id", config.AppSettings.Settings["shop_id"].Value);              // Store identifier.

        string shakey = "PRODUCTION".Equals(config.AppSettings.Settings["ctx_mode"].Value) ? // Choose PRODUCTION or TEST SHA key.
                        config.AppSettings.Settings["key_prod"].Value :
                        config.AppSettings.Settings["key_test"].Value;

        // Operating parameters.

        data.Add("vads_version", "V2");                                           // Payment form version. V2 is the only possible value.
        data.Add("vads_contrib", "ASP.NET_Form_Examples_" + PaymentUtils.VERSION);
        data.Add("vads_ctx_mode", config.AppSettings.Settings["ctx_mode"].Value); // Context mode.

        data.Add("vads_trans_date", PaymentUtils.GetTransDate());                 // Generate UTC payment date in the format expected by the payment gateway : yyyyMMddHHmmss.
        data.Add("vads_page_action", "PAYMENT");                                  // This field defines the action executed by the payment gateway. See gateway documentation for more information.
        data.Add("vads_action_mode", "INTERACTIVE");                              // This allows to define the bank data acquisition mode : INTERACTIVE | SILENT.

        // Payment information.

        data.Add("vads_currency", "978");          // Currency code in ISO-4217 standard.
        data.Add("vads_payment_config", "SINGLE"); // Payment type : SINGLE | MULTI | MULTI_EXT. For more information about advanced payment types, please see gateway documentation.

        // The amount to pay must be expressed in the smallest monetary unit (in cents for euro).
        var amount = decimal.Parse(Amount.Text.Replace(".", ",")); // Conversion to decimal and replacement of '.' by ','.

        amount = Convert.ToInt32(amount * 100);                    // Conversion to cents then to integer to remove the decimal part.
        data.Add("vads_amount", Convert.ToString(amount));         // Set amount as string.

        data.Add("vads_trans_id", PaymentUtils.GetTransId());      // Method generating transaction ID based on 1/10 of a second since midnight.

        //
        // Optional parameters.
        //

        // Payment configuration.

        data.Add("vads_validation_mode", config.AppSettings.Settings["validation_mode"].Value);
        data.Add("vads_capture_delay", config.AppSettings.Settings["capture_delay"].Value);
        data.Add("vads_payment_cards", config.AppSettings.Settings["payment_cards"].Value);

        // Payment page customization.

        data.Add("vads_language", (string)Session["language"]);
        // data.Add("vads_available_languages", "");
        // data.Add("vads_shop_name", "");
        // data.Add("vads_shop_url", "");

        // Return to shop.

        data.Add("vads_return_mode", "GET"); // GET | POST.
        data.Add("vads_url_return", ReturnURL());
        // data.Add("vads_url_success", "");
        // data.Add("vads_url_refused", "");
        // data.Add("vads_url_cancel", "");
        // data.Add("vads_redirect_success_timeout", ""); // Time in seconds (0-300) before the buyer is automatically redirected to your website after a successful payment.
        // data.Add("vads_redirect_success_message", ""); // Message displayed on the payment page prior to redirection after a successful payment.
        // data.Add("vads_redirect_error_timeout", ""); // Time in seconds (0-300) before the buyer is automatically redirected to your website after a declined payment.
        // data.Add("vads_redirect_error_message", ""); // Message displayed on the payment page prior to redirection after a declined payment.

        // Information about customer.

        // data.Add("vads_cust_id", "");
        // data.Add("vads_cust_status", ""); // PRIVATE | COMPANY.
        if (!String.IsNullOrEmpty(Civility.Text))
        {
            data.Add("vads_cust_title", Civility.Text);
        }
        // data.Add("vads_cust_name", "");
        if (!String.IsNullOrEmpty(FirstName.Text))
        {
            data.Add("vads_cust_first_name", FirstName.Text);
        }
        if (!String.IsNullOrEmpty(LastName.Text))
        {
            data.Add("vads_cust_last_name", LastName.Text);
        }
        if (!String.IsNullOrEmpty(Address.Text))
        {
            data.Add("vads_cust_address", Address.Text);
        }
        // data.Add("vads_cust_number_address", "");
        // data.Add("vads_cust_district", "");
        if (!String.IsNullOrEmpty(ZipCode.Text))
        {
            data.Add("vads_cust_zip", ZipCode.Text);
        }
        if (!String.IsNullOrEmpty(City.Text))
        {
            data.Add("vads_cust_city", City.Text);
        }
        // data.Add("vads_cust_state", "");
        // data.Add("vads_cust_country", "");
        if (!String.IsNullOrEmpty(Phone.Text))
        {
            data.Add("vads_cust_phone", Phone.Text);
        }
        // data.Add("vads_cust_cell_phone", "");
        if (!String.IsNullOrEmpty(Email.Text))
        {
            data.Add("vads_cust_email", Email.Text);
        }

        // Delivery method.

        // data.Add("vads_ship_to_status", ""); // PRIVATE | COMPANY.
        // data.Add("vads_ship_to_type", ""); // RECLAIM_IN_SHOP | RELAY_POINT | RECLAIM_IN_STATION | PACKAGE_DELIVERY_COMPANY | ETICKET.
        // data.Add("vads_ship_to_delivery_company_name", ""); // ex:UPS, La Poste, etc.
        // data.Add("vads_shipping_amount", "");
        // data.Add("vads_tax_amount", "");
        // data.Add("vads_insurance_amount", "");

        // Delivery address.

        // data.Add("vads_ship_to_name", "");
        // data.Add("vads_ship_to_first_name", "");
        // data.Add("vads_ship_to_last_name", "");
        // data.Add("vads_ship_to_address_number", "");
        // data.Add("vads_ship_to_street", "");
        // data.Add("vads_ship_to_street2", "");
        // data.Add("vads_ship_to_district", "");
        // data.Add("vads_ship_to_zip", "");
        // data.Add("vads_ship_to_city", "");
        // data.Add("vads_ship_to_state", "");
        // data.Add("vads_ship_to_country", "");
        // data.Add("vads_ship_to_phone_num", "");

        // Order information.

        if (!String.IsNullOrEmpty(OrderNumber.Text))
        {
            data.Add("vads_order_id", OrderNumber.Text);
        }                                                                                              // Retrieve order information entered in previous page.
        // data.Add("vads_order_info", "");
        // data.Add("vads_order_info2", "");
        // data.Add("vads_order_info3", "");

        // Compute signature.
        data.Add("signature", PaymentUtils.GetSignature(data, shakey));

        // Build payment form and redirect to payment gateway.
        string payForm = PaymentUtils.GetPaymentForm(config.AppSettings.Settings["gateway_url"].Value, data);

        CheckoutConfirmForm.Parent.Controls.Add(new LiteralControl(payForm));
    }