public void SetUp()
        {
            _braintree = new Braintree(PublicKey);
            var version = _braintree.GetVersion().Replace(".", "_");

            _encryptedPrefix = "$bt3|wp7_" + version + "$";
        }
Ejemplo n.º 2
0
        static void Main(string[] args)
        {
            string publicKey = "MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAoUID6FPckCjF4YHm8x7pDfoM0YeDx2ZPfdaVs7neGJWHnwYVZpj6X+hg5r8hqazHmFjonN3/SA0CahnN+MLPr4E6cAdUF1eTQnzVfqNVq3lKxYk0twT4Yv7X4oQ2EHYmisFm1A97ujgRwQ5xsbYRHgACe8US1X5S3c7pJDLcM1Ssjr4R3x3/F2e5T7+pWlG/J+tvLRyTvyPuv21KR/ZePHExO1jQ+HYf3gMh1eZfdj2jAPnfPbUSORbOKZtFms8B8ojuGPiSOr5hmBt7gy4UyJDR6tlxhpodqEOpqTv2WfZ/dRoNukETa65eZ0jnmQKnIdXRsNMFUqEF5A4cNVrLhHujwxsOXm5vIeOOWmG/HM8wnltETOF7Fdjs/cXVOicM3d09xL3ePCLe671YjSSb7T7oo/cCI5nK1xzPkQX9q+Yb3OvhoFlF3Mebf94L8te9GCUqt7Dk5Ukrnfn+G53CwH4jeuln2/8lVbE3XFVYT342IGOHpJ+XNbRd9CUTqIH8ESsK0DFeVR3qVCq4zJfQJ9UAKy6tWOHmijIPhpOijWNVgh+HTKUxoloWs3PSWUkOBJUZX4EYUThphCCf8Cedvf2nY0XNwWAmb4FDele8H4/J/NaNFYm/hWK7+Y+DIrL37rLrIb/hjHL1UqaK8osbXQkfohnFVw/pDCuXNemDvJkCAwEAAQ==";
            int    cvv       = 413;

            var    braintree = new Braintree(publicKey);
            string encrypted = braintree.Encrypt(cvv.ToString());

            Console.WriteLine("Encrypted CVV: " + encrypted);
            Console.ReadKey();
        }
Ejemplo n.º 3
0
        private void PostToMerchantServer()
        {
            var braintree  = new Braintree(PublicKey);
            var parameters = new Dictionary <string, object>
            {
                { "cc_number", braintree.Encrypt(CreditCardNumber.Text) },
                { "cc_exp_date", braintree.Encrypt(ExpirationDate.Text) },
                { "cc_cvv", braintree.Encrypt(Cvv.Text) }
            };

            var client = new BraintreeHttpClient(_merchantServerUrl, UploadStringCompleted);

            client.Post(parameters);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Create a subscription invoice
        /// </summary>
        /// <param name="planId"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public Invoice CreateSubscriptionInvoice(Braintree.Plan planDetail, Guid userId, string transactionId)
        {
            //var planDetail = new PaymentService(UnitOfWork, Repository, Settings).GetPlanById(planId);
            try
            {
                User user = Repository.FindById<User>(userId);

                if (planDetail == null || user == null)
                {
                    throw new ArgumentException("Generate subscription invoice. Cannot find Plan or User with id:" + userId);
                }
                var invoice = new Invoice()
                {
                    InvoiceNumber = GetInvoiceNumber(),
                    User = user,
                    Description = string.Format(InvoiceConst.InvoiceSubscriptionDescription, planDetail.BillingFrequency.Value),
                    CreatedDate = DateTime.UtcNow,
                    GST = SubtractGSTCalculator(planDetail.Price.Value),
                    Amount = planDetail.Price.Value,
                    Currency = planDetail.CurrencyIsoCode,
                    Duration = planDetail.BillingFrequency.Value,
                    Type = InvoiceType.Subscription,
                    PaymentStatus = true,
                    TransactionId = transactionId,
                };

                Repository.Insert<Invoice>(invoice);
                UnitOfWork.Save();

                if (!invoice.Id.Equals(Guid.Empty))
                {
                    string mailContent = GetEmailContentOfInvoice(invoice.ExposedAs<InvoiceDto>());

                    string mailToPdf = TranformToInvoiceTemplate(invoice.User.ExposedAs<UserDto>(),
                        invoice.ExposedAs<InvoiceDto>(), "months", ConstEmailTemplateKey.SubscriptionInvoiceTemplate, null);
                    System.Threading.Tasks.Task.Factory.StartNew(() =>
                    {
                        byte[] pdfAsByte = HtmlToPdf.GetPdfData(mailToPdf, baseUrl);

                        string fileName = string.Format("invoice_{0}.pdf", invoice.InvoiceNumber);

                        SendInvoice(fileName, pdfAsByte, mailContent, user.Email, ConstEmailSubject.SubscriptionInvoice);
                    });
                }
                else
                {
                    throw new ArgumentException("Cannot save subscription invoice to database");
                }

                return invoice;
            }
            catch (Exception e)
            {
                throw new ArgumentException(e.Message);
            }
        }
 public void SetUp()
 {
     _braintree = new Braintree(PublicKey);
     var version = _braintree.GetVersion().Replace(".", "_");
     _encryptedPrefix = "$bt3|wp7_" + version + "$";
 }
Ejemplo n.º 6
0
        public PaymentResult StoreSubscription(Braintree.Plan plan, string userId, bool hasTrialPeriod)
        {
            try
            {
                var customer = Gateway.Customer.Find(userId);
                //Get customcer's credit card
                var card = customer.CreditCards.Single(x => x.IsDefault == true);

                //If only you have more than one merchant account
                var merchantAccountId = ConfigurationManager.AppSettings["BrainTreeMerchantAccountIdAud"];

                //create a new subscription request
                var request = new SubscriptionRequest
                {
                    PaymentMethodToken = card.Token,
                    PlanId = plan.Id,
                    MerchantAccountId = merchantAccountId,
                };

                if (!hasTrialPeriod)
                {
                    request.HasTrialPeriod = false;
                }

                //Create a subscription
                var response = Gateway.Subscription.Create(request);

                if (response.IsSuccess())
                {
                    return new PaymentResult
                    {
                        Success = true,
                        TrialDuration = plan.TrialPeriod.Value ? plan.TrialDuration.Value : 0,
                        TrialPeriod = plan.TrialPeriod.Value,
                        BillingFrequency = plan.BillingFrequency.Value,
                    };
                }
                else
                {
                    return new PaymentResult { Success = false, ErrorMessage = response.Message };
                }

            }
            catch (Exception ex)
            {
                Log.Error("Unknown error when creating subscription", ex);
                throw new ApplicationException("Cannot create subscription." + ex.Message);
            }
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            this.loginView = new LoginButton(new CGRect(10, 10, 300, 40))
            {
                ReadPermissions = new[] { "email" }
            };
            this.loginView.Completed += (sender, e) =>
            {
                if (e.Error == null)
                {
                    var request = new Facebook.CoreKit.GraphRequest("me", null);
                    request.Start((con, result, error) =>
                    {
                        if (error == null)
                        {
                            this.EmailInputField.Text = ((NSDictionary)result).ValueForKeyPath(new NSString("email")).ToString();
                        }
                    });
                }
            };

            this.Add(this.loginView);

            this.BuyButton.TouchUpInside += async(sender, e) =>
            {
                LeanplumBindings.Leanplum.SetUserId(this.UserEmail);
                LeanplumBindings.Leanplum.Track("Purchase intent", 10);
                Insights.Identify(this.UserEmail, "a", "b");
                TaperecorderBinding.TapeRecorder.SetUserID(this.UserEmail);

                try
                {
                    this.BuyButton.Enabled = false;

                    var endpoint = string.Format("{0}/payment/token", Constants.ServerApiAddress);
                    var token    = await HttpRequestHelper.Post <string>(endpoint, this.UserEmail);

                    var braintree = Braintree.Create(token);
                    var btVC      = braintree.CreateDropInViewController(this.braintreeDelegate);
                    btVC.FetchPaymentMethods();

                    btVC.SummaryTitle       = "New subscription";
                    btVC.SummaryDescription = "New subscription for June for everything!";
                    btVC.DisplayAmount      = "$10.00";
                    btVC.CallToActionText   = "Get it now!";

                    var nav = new UINavigationController(btVC);

                    btVC.NavigationItem.LeftBarButtonItem = new UIBarButtonItem(UIBarButtonSystemItem.Cancel, (_, __) =>
                    {
                        this.PaymentFailure();
                    });
                    this.PresentViewController(nav, true, null);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                finally
                {
                    this.BuyButton.Enabled = true;
                }
            };
        }
Ejemplo n.º 8
0
        public ActionResult Autocomplete(string term)
        {
            var items = new[] { "Modena", "Roccavivara", "Fabbrico", "Assisi", "Rolo", "Reggio Emilia" };

            /*
            var filteredItems = items.Where(
                item => item.IndexOf(term, StringComparison.InvariantCultureIgnoreCase) >= 0
                );
             */
            var filteredItems = items.Where(
                item => item.StartsWith(term, StringComparison.InvariantCultureIgnoreCase)
                );

            return Json(filteredItems, JsonRequestBehavior.AllowGet);
        }
Ejemplo n.º 9
0
        public static string GenerateValidUsBankAccountNonce(BraintreeGateway gateway)
        {
            var clientToken = GenerateDecodedClientToken(gateway);
            var def =  new {
                braintree_api = new {
                    url = "",
                    access_token = ""
                }
            };
            var config = JsonConvert.DeserializeAnonymousType(clientToken, def);
            var url = config.braintree_api.url + "/tokens";
            var accessToken = config.braintree_api.access_token;
            string postData = @"
            {
                ""type"": ""us_bank_account"",
                ""billing_address"": {
                    ""street_address"": ""123 Ave"",
                    ""region"": ""CA"",
                    ""locality"": ""San Francisco"",
                    ""postal_code"": ""94112""
                },
                ""account_type"": ""checking"",
                ""routing_number"": ""021000021"",
                ""account_number"": ""567891234"",
                ""account_holder_name"": ""Dan Schulman"",
                ""account_description"": ""PayPal Checking - 1234"",
                ""ach_mandate"": {
                    ""text"": """"
                }
            }";

#if netcore
            var request = new HttpRequestMessage(new HttpMethod("POST"), url);
            byte[] buffer = Encoding.UTF8.GetBytes(postData);
            request.Content = new StringContent(postData, Encoding.UTF8, "application/json");
            request.Headers.Add("Braintree-Version", "2015-11-01");
            request.Headers.Add("Authorization", "Bearer " + accessToken);

            var httpClientHandler = new HttpClientHandler{};

            HttpResponseMessage response;
            using (var client = new HttpClient(httpClientHandler))
            {
                response = client.SendAsync(request).GetAwaiter().GetResult();
            }
            StreamReader reader = new StreamReader(response.Content.ReadAsStreamAsync().Result, Encoding.UTF8);
            string responseBody = reader.ReadToEnd();
#else
            string curlCommand = $@"-s -H ""Content-type: application/json"" -H ""Braintree-Version: 2015-11-01"" -H ""Authorization: Bearer {accessToken}"" -d '{postData}' -XPost ""{url}""";
            Process process = new Process {
                StartInfo = new ProcessStartInfo {
                    FileName = "curl",
                             Arguments = curlCommand,
                             UseShellExecute = false,
                             RedirectStandardOutput = true,
                }
            };
            process.Start();

            StringBuilder responseBodyBuilder = new StringBuilder();
            while (!process.HasExited) {
                responseBodyBuilder.Append(process.StandardOutput.ReadToEnd());
            }
            responseBodyBuilder.Append(process.StandardOutput.ReadToEnd());
            string responseBody = responseBodyBuilder.ToString();
#endif
            var resDef =  new {
                data = new {
                    id = "",
                }
            };
            var json = JsonConvert.DeserializeAnonymousType(responseBody, resDef);
            return json.data.id;
        }