コード例 #1
0
ファイル: Session.cs プロジェクト: Hankahn/sdk-core-dotnet
 /// <summary>
 /// Returns the URL to which the user must be redirected to logout from the
 /// OpenID provider (i.e. PayPal)
 /// </summary>
 /// <param name="redirectURI"></param>
 /// <param name="idToken"></param>
 /// <param name="apiContext"></param>
 /// <returns></returns>
 public static string GetLogoutUrl(string redirectURI, string idToken,
     APIContext apiContext)
 {
     string logoutURL = null;
     Dictionary<string, string> config = null;
     if (apiContext.Config == null)
     {
         config = ConfigManager.getConfigWithDefaults(ConfigManager.Instance.GetProperties());
     }
     else
     {
         config = ConfigManager.getConfigWithDefaults(apiContext.Config);
     }
     string baseURL = null;
     if (config.ContainsKey(BaseConstants.OPENID_REDIRECT_URI))
     {
         baseURL = config[BaseConstants.OPENID_REDIRECT_URI];
     }
     else
     {
         baseURL = BaseConstants.OPENID_REDIRECT_URI_CONSTANT;
     }
     if (baseURL.EndsWith("/"))
     {
         baseURL = baseURL.Substring(0, baseURL.Length - 1);
     }
     StringBuilder stringBuilder = new StringBuilder();
     stringBuilder.Append("id_token=")
             .Append(HttpUtility.UrlEncode(idToken))
             .Append("&redirect_uri=")
             .Append(HttpUtility.UrlEncode(redirectURI))
             .Append("&logout=true");
     logoutURL = baseURL + "/v1/endsession?" + stringBuilder.ToString();
     return logoutURL;
 }
コード例 #2
0
        public void testGetAuthUrl()
        {
            Dictionary<String, String> configurationMap = new Dictionary<string, string>();
            string clientId = "AQkquBDf1zctJOWGKWUEtKXm6qVhueUEMvXO_-MCI4DQQ4-LWvkDLIN2fGsd";
            string clientSecret = "EL1tVxAjhT7cJimnz5-Nsx9k2reTKSVfErNQF-CmrwJgxRtylkGTKlU4RvrX";
            configurationMap.Add("mode", "sandbox");

            APIContext apiContext = new APIContext();
            apiContext.Config = configurationMap;
            List<string> scopelist = new List<string>();
            scopelist.Add("openid");
            scopelist.Add("email");
            string redirectURI = "https://devtools-paypal.com";
            string redirectURL = Session.GetRedirectURL(clientId, redirectURI, scopelist, apiContext);
            Console.WriteLine(redirectURL);
            CreateFromAuthorizationCodeParameters param = new CreateFromAuthorizationCodeParameters();

            param.setClientId(clientId);
            param.setClientSecret(clientSecret);
            // code you will get back as part of the url after redirection
            param.setCode("VxirnJHENB8k5slnoqZOdmjQcCMJRvbI-ispixwWHke-gsOh6XJaWQNJuTCTp3n3o6ttQs3VoNX1De3HOVpmH2PLN53PPedZcTujzLqYrlTS-CqKHYb5wb0NT2joumArOdEy51D4HgoCa46dxuPMm79nX40RQXRP8J0OQsgrEbhf_Kna");
            Tokeninfo info = Tokeninfo.CreateFromAuthorizationCode(apiContext, param);
            UserinfoParameters userinfoParams = new UserinfoParameters();
            userinfoParams.setAccessToken(info.access_token);
            Userinfo userinfo = Userinfo.GetUserinfo(apiContext, userinfoParams);

            Console.WriteLine("Email" + userinfo.email);
        }
コード例 #3
0
 public static string GetRedirectURL(string redirectURI, List<string> scope,
     APIContext apiContext)
 {
     string clientId = null;
     if (apiContext.Config[BaseConstants.CLIENT_ID] != null){
         clientId = apiContext.Config[BaseConstants.CLIENT_ID];
     }
     return GetRedirectURL(clientId, redirectURI, scope, apiContext );
 }
コード例 #4
0
ファイル: Session.cs プロジェクト: paypal/sdk-core-dotnet
        /// <summary>
        /// Returns the PayPal URL to which the user must be redirected to start the authentication / authorization process
        /// </summary>
        /// <param name="redirectUri"></param>
        /// <param name="scope"></param>
        /// <param name="apiContext"></param>
        /// <returns></returns>
        public static string GetRedirectUrl(string redirectUri, List<string> scope, APIContext apiContext)
        {
            string redirectUrl = null;
            string baseUrl = null;
            Dictionary<string, string> config = null;

            if (apiContext.Config == null)
            {
                config = ConfigManager.GetConfigWithDefaults(ConfigManager.Instance.GetProperties());
            }
            else
            {
                config = ConfigManager.GetConfigWithDefaults(apiContext.Config);
            }

            if (config.ContainsKey(BaseConstants.OpenIdRedirectUri))
            {
                baseUrl = config[BaseConstants.OpenIdRedirectUri];
            }
            else
            {
                baseUrl = BaseConstants.OpenIdRedirectUriConstant;
            }
            if (baseUrl.EndsWith("/"))
            {
                baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
            }
            if (scope == null || scope.Count <= 0)
            {
                scope = new List<string>();
                scope.Add("openid");
                scope.Add("profile");
                scope.Add("address");
                scope.Add("email");
                scope.Add("phone");
                scope.Add("https://uri.paypal.com/services/paypalattributes");
            }
            if (!scope.Contains("openid"))
            {
                scope.Add("openid");
            }
            StringBuilder builder = new StringBuilder();
            builder.Append("client_id=").Append(HttpUtility.UrlEncode((config.ContainsKey(BaseConstants.ClientId)) ? config[BaseConstants.ClientId] : string.Empty)).Append("&response_type=").Append("code").Append("&scope=");
            StringBuilder scpBuilder = new StringBuilder();
            foreach (string str in scope)
            {
                scpBuilder.Append(str).Append(" ");
            }
            builder.Append(HttpUtility.UrlEncode(scpBuilder.ToString()));
            builder.Append("&redirect_uri=").Append(HttpUtility.UrlEncode(redirectUri));
            redirectUrl = baseUrl + "/signin/authorize?" + builder.ToString();
            return redirectUrl;
        }
コード例 #5
0
ファイル: Session.cs プロジェクト: Hankahn/sdk-core-dotnet
 /// <summary>
 /// Returns the PayPal URL to which the user must be redirected to start the 
 /// authentication / authorization process.
 /// </summary>
 /// <param name="redirectURI"></param>
 /// <param name="scope"></param>
 /// <param name="apiContext"></param>
 /// <returns></returns>
 public static string GetRedirectURL(string redirectURI, List<string> scope,
     APIContext apiContext)
 {
     string redirectURL = null;
     Dictionary<string, string> config = null;
     if (apiContext.Config == null)
     {
         config = ConfigManager.getConfigWithDefaults(ConfigManager.Instance.GetProperties());
     }
     else
     {
         config = ConfigManager.getConfigWithDefaults(apiContext.Config);
     }
     string baseURL = null;
     if (config.ContainsKey(BaseConstants.OPENID_REDIRECT_URI))
     {
         baseURL = config[BaseConstants.OPENID_REDIRECT_URI];
     }
     else
     {
         baseURL = BaseConstants.OPENID_REDIRECT_URI_CONSTANT;
     }
     if (baseURL.EndsWith("/"))
     {
         baseURL = baseURL.Substring(0, baseURL.Length - 1);
     }
     if (scope == null || scope.Count <= 0)
     {
         scope = new List<string>();
         scope.Add("openid");
         scope.Add("profile");
         scope.Add("address");
         scope.Add("email");
         scope.Add("phone");
         scope.Add("https://uri.paypal.com/services/paypalattributes");
     }
     if (!scope.Contains("openid"))
     {
         scope.Add("openid");
     }
     StringBuilder strBuilder = new StringBuilder();
     strBuilder.Append("client_id=").Append(HttpUtility.UrlEncode((config.ContainsKey(BaseConstants.CLIENT_ID)) ? config[BaseConstants.CLIENT_ID] : "")).Append("&response_type=").Append("code").Append("&scope=");
     StringBuilder scpBuilder = new StringBuilder();
     foreach (string str in scope)
     {
         scpBuilder.Append(str).Append(" ");
     }
     strBuilder.Append(HttpUtility.UrlEncode(scpBuilder.ToString()));
     strBuilder.Append("&redirect_uri=").Append(
             HttpUtility.UrlEncode(redirectURI));
     redirectURL = baseURL + "/v1/authorize?" + strBuilder.ToString();
     return redirectURL;
 }
コード例 #6
0
ファイル: OpenIdTest.cs プロジェクト: PieterScheffers/FotoLab
        public void TestCreateFromRefreshTokenDynamic()
        {
            Dictionary<string, string> configurationMap = new Dictionary<string, string>();
            configurationMap.Add("clientId", "");
            configurationMap.Add("clientSecret", "");
            configurationMap.Add("mode", "live");
            APIContext apiContext = new APIContext();
            apiContext.Config = configurationMap;

            CreateFromRefreshTokenParameters param = new CreateFromRefreshTokenParameters();
            info = info.CreateFromRefreshToken(apiContext, param);
            Assert.AreEqual(info.access_token != null, true);
        }
コード例 #7
0
ファイル: OpenIdTest.cs プロジェクト: PieterScheffers/FotoLab
        public void TestUserinfoDynamic()
        {
            Dictionary<string, string> configurationMap = new Dictionary<string, string>();
            configurationMap.Add("clientId", "");
            configurationMap.Add("clientSecret", "");
            configurationMap.Add("mode", "live");
            APIContext apiContext = new APIContext();
            apiContext.Config = configurationMap;

            UserinfoParameters userinfoParams = new UserinfoParameters();
            userinfoParams.SetAccessToken(info.access_token);
            Userinfo userinfo = Userinfo.GetUserinfo(apiContext, userinfoParams);
            Assert.AreEqual(userinfo != null, true);
        }
コード例 #8
0
ファイル: OpenIdTest.cs プロジェクト: PieterScheffers/FotoLab
        public void TestCreateFromAuthorizationCodeDynamic()
        {
            Dictionary<string, string> configurationMap = new Dictionary<string, string>();
            configurationMap.Add("clientId", "");
            configurationMap.Add("clientSecret", "");
            configurationMap.Add("mode", "live");
            APIContext apiContext = new APIContext();
            apiContext.Config = configurationMap;
            CreateFromAuthorizationCodeParameters param = new CreateFromAuthorizationCodeParameters();

            // code you will get back as part of the url after redirection
            param.SetCode("xxxx");
            info = Tokeninfo.CreateFromAuthorizationCode(apiContext, param);
            Assert.AreEqual(true, info.access_token != null);
        }
コード例 #9
0
ファイル: OpenIdTest.cs プロジェクト: PieterScheffers/FotoLab
 public void TestGetAuthUrl()
 {
     Dictionary<string, string> configurationMap = new Dictionary<string, string>();
     configurationMap.Add("clientId", "");
     configurationMap.Add("clientSecret", "");
     configurationMap.Add("mode", "live");
     APIContext apiContext = new APIContext();
     apiContext.Config = configurationMap;
     List<string> scopelist = new List<string>();
     scopelist.Add("openid");
     scopelist.Add("email");
     string redirectURI = "http://google.com";
     string redirectURL = Session.GetRedirectUrl(redirectURI, scopelist, apiContext);
     Assert.AreEqual(redirectURL != null, true);
 }
コード例 #10
0
ファイル: GeneralApiTests.cs プロジェクト: Xamarui/Merchello
        public void Can_Create_An_APIContext()
        {
            //// Arrange
            ServicePointManager.Expect100Continue = false;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            ServicePointManager.DefaultConnectionLimit = 9999;

            var settings = ((PayPalApiService)PayPalApiService).Settings;

            var sdkConfig = settings.GetApiSdkConfig();

            var accessToken = new OAuthTokenCredential(settings.ClientId, settings.ClientSecret, sdkConfig.Result).GetAccessToken();

            //// Act
            var apiContext = new APIContext(accessToken);

            Assert.NotNull(apiContext);
        }
コード例 #11
0
 /// <summary>
 /// Returns the URL to which the user must be redirected to logout from the
 /// OpenID provider (i.e. PayPal)
 /// </summary>
 /// <param name="redirectURI"></param>
 /// <param name="idToken"></param>
 /// <param name="apiContext"></param>
 /// <returns></returns>
 public static string GetLogoutUrl(string redirectURI, string idToken,
     APIContext apiContext)
 {
     string logoutURL = null;
     Dictionary<string, string> config = null;
     if (apiContext.Config == null)
     {
         config = ConfigManager.getConfigWithDefaults(ConfigManager.Instance.GetProperties());
     }
     else
     {
         config = ConfigManager.getConfigWithDefaults(apiContext.Config);
     }
     string baseURL = null;
     if (config.ContainsKey(BaseConstants.OPENID_REDIRECT_URI))
     {
         baseURL = config[BaseConstants.OPENID_REDIRECT_URI];
     }
     else if (config.ContainsKey(BaseConstants.APPLICATION_MODE_CONFIG))
     {
         string mode = config[BaseConstants.APPLICATION_MODE_CONFIG];
         if (mode.Equals(BaseConstants.LIVE_MODE))
         {
             baseURL = BaseConstants.OPENID_LIVE_REDIRECT_URI_CONSTANT;
         }
         else if (mode.Equals(BaseConstants.SANDBOX_MODE))
         {
             baseURL = BaseConstants.OPENID_SANDBOX_REDIRECT_URI_CONSTANT;
         }
         else
         {
             throw new ConfigException("You must specify one of mode(live/sandbox) OR Redirect URI in the configuration");
         }
     }
     StringBuilder stringBuilder = new StringBuilder();
     stringBuilder.Append("id_token=")
             .Append(HttpUtility.UrlEncode(idToken))
             .Append("&redirect_uri=")
             .Append(HttpUtility.UrlEncode(redirectURI))
             .Append("&logout=true");
     logoutURL = baseURL + "/v1/endsession?" + stringBuilder.ToString();
     return logoutURL;
 }
コード例 #12
0
        public ActionResult Capture(string authorizationId)
        {
            var viewData = new PayPalViewData();

            try
            {
                var accessToken = new OAuthTokenCredential(ConfigManager.Instance.GetProperties()["ClientID"], ConfigManager.Instance.GetProperties()["ClientSecret"]).GetAccessToken();
                var apiContext = new APIContext(accessToken);
                var authorization = Authorization.Get(apiContext, authorizationId);

                if (authorization != null)
                {
                    var total = Convert.ToDecimal(authorization.amount.total);

                    var capture = authorization.Capture(apiContext, new Capture
                       {
                           is_final_capture = true,
                           amount = new Amount
                           {
                               currency = "USD",
                               total = (total + (total * .05m)).ToString("f2")
                           },
                       });

                    viewData.JsonResponse = JObject.Parse(capture.ConvertToJson()).ToString(Formatting.Indented);

                    return View("Success", viewData);
                }

                viewData.ErrorMessage = "Could not find previous authorization.";

                return View("Error", viewData);
            }
            catch (PayPalException ex)
            {
                viewData.ErrorMessage = ex.Message;

                return View("Error", viewData);
            }
        }
コード例 #13
0
        /// <summary>
        /// Creates a future payment using the specified API context and correlation ID.
        /// </summary>
        /// <param name="apiContext">APIContext used for the API call.</param>
        /// <param name="correlationId">Application correlation ID</param>
        /// <returns>A new payment object setup to be used for a future payment.</returns>
        public Payment Create(APIContext apiContext, string correlationId)
        {
            if (apiContext == null)
            {
                throw new PayPal.Exception.MissingCredentialException("apiContext cannot be null.");
            }

            if (string.IsNullOrEmpty(correlationId))
            {
                throw new PayPal.Exception.MissingCredentialException("correlationId cannot be null or empty.");
            }

            if (apiContext.HTTPHeaders == null)
            {
                apiContext.HTTPHeaders = new Dictionary<string, string>();
            }

            apiContext.HTTPHeaders["Paypal-Application-Correlation-Id"] = correlationId;
            apiContext.HTTPHeaders["PAYPAL-CLIENT-METADATA-ID"] = correlationId;

            return this.Create(apiContext);
        }
コード例 #14
0
ファイル: OpenIdTest.cs プロジェクト: Hankahn/sdk-core-dotnet
        public void testGetAuthUrl()
        {
            Dictionary<String, String> configurationMap = new Dictionary<string, string>();
            configurationMap.Add("ClientID", "dummy");
            configurationMap.Add("ClientSecret",
                    "dummypassword");
            configurationMap.Add("mode", "live");
            APIContext apiContext = new APIContext();
            apiContext.Config = configurationMap;
            List<string> scopelist = new List<string>();
            scopelist.Add("openid");
            scopelist.Add("email");
            string redirectURI = "http://google.com";
               string redirectURL = Session.GetRedirectURL(redirectURI,scopelist,apiContext);
               Console.WriteLine(redirectURL);
               CreateFromAuthorizationCodeParameters param = new CreateFromAuthorizationCodeParameters();

            // code you will get back as part of the url after redirection
               param.setCode("wm7qvCMoGwMbtuytIQPhpGn9Gac7nmwVraQIgNp9uQIovP5c-wGn8oB0LmUnhlhse4at4T8XGwXufb7D94YWgIsZpBSzXMwdFkxp4u2oH9dy3HW4");
               Tokeninfo info = Tokeninfo.CreateFromAuthorizationCode(apiContext, param);
               UserinfoParameters userinfoParams = new UserinfoParameters();
               userinfoParams.setAccessToken(info.access_token);
               Userinfo userinfo = Userinfo.GetUserinfo(apiContext, userinfoParams);
        }
コード例 #15
0
ファイル: Session.cs プロジェクト: paypal/sdk-core-dotnet
        /// <summary>
        /// Returns the URL to which the user must be redirected to logout from the OpenId provider (i.e., PayPal)
        /// </summary>
        /// <param name="redirectUri"></param>
        /// <param name="idToken"></param>
        /// <param name="apiContext"></param>
        /// <returns></returns>
        public static string GetLogoutUrl(string redirectUri, string idToken, APIContext apiContext)
        {
            string logoutUrl = null;
            string baseUrl = null;
            Dictionary<string, string> config = null;

            if (apiContext.Config == null)
            {
                config = ConfigManager.GetConfigWithDefaults(ConfigManager.Instance.GetProperties());
            }
            else
            {
                config = ConfigManager.GetConfigWithDefaults(apiContext.Config);
            }

            if (config.ContainsKey(BaseConstants.OpenIdRedirectUri))
            {
                baseUrl = config[BaseConstants.OpenIdRedirectUri];
            }
            else
            {
                baseUrl = BaseConstants.OpenIdRedirectUriConstant;
            }
            if (baseUrl.EndsWith("/"))
            {
                baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
            }
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.Append("id_token=")
                    .Append(HttpUtility.UrlEncode(idToken))
                    .Append("&redirect_uri=")
                    .Append(HttpUtility.UrlEncode(redirectUri))
                    .Append("&logout=true");
            logoutUrl = baseUrl + "/webapps/auth/protocol/openidconnect/v1/endsession?" + stringBuilder.ToString();
            return logoutUrl;
        }
コード例 #16
0
        public ActionResult Confirmed(Guid id, string token, string payerId)
        {
            var viewData = new ConfirmedViewData
            {
                Id = id,
                Token = token,
                PayerId = payerId
            };

            var accessToken = new OAuthTokenCredential(ConfigManager.Instance.GetProperties()["ClientID"], ConfigManager.Instance.GetProperties()["ClientSecret"]).GetAccessToken();
            var apiContext = new APIContext(accessToken);
            var payment = new Payment()
            {
                id = (string)Session[id.ToString()],
            };

            var executedPayment = payment.Execute(apiContext, new PaymentExecution { payer_id = payerId });

            viewData.AuthorizationId = executedPayment.transactions[0].related_resources[0].authorization.id;
            viewData.JsonRequest = JObject.Parse(payment.ConvertToJson()).ToString(Formatting.Indented);
            viewData.JsonResponse = JObject.Parse(executedPayment.ConvertToJson()).ToString(Formatting.Indented);

            return View(viewData);
        }
コード例 #17
0
ファイル: PaymentTest.cs プロジェクト: ruanzx/PayPal-NET-SDK
 public static Payment CreatePaymentAuthorization(APIContext apiContext)
 {
     return GetPaymentAuthorization().Create(apiContext);
 }
コード例 #18
0
        // ##Create
        // Sample showing to create a Payment using
        // CreditCard as a FundingInstrument
        protected void Page_Load(object sender, EventArgs e)
        {
            HttpContext CurrContext = HttpContext.Current;

            // ###Items
            // Items within a transaction.
            Item item = new Item();

            item.name     = "Item Name";
            item.currency = "USD";
            item.price    = "1";
            item.quantity = "5";
            item.sku      = "sku";

            List <Item> itms = new List <Item>();

            itms.Add(item);
            ItemList itemList = new ItemList();

            itemList.items = itms;

            // ###Address
            // Base Address object used as shipping or billing
            // address in a payment.
            Address billingAddress = new Address();

            billingAddress.city         = "Johnstown";
            billingAddress.country_code = "US";
            billingAddress.line1        = "52 N Main ST";
            billingAddress.postal_code  = "43210";
            billingAddress.state        = "OH";

            // ###CreditCard
            // A resource representing a credit card that can be
            // used to fund a payment.
            CreditCard crdtCard = new CreditCard();

            crdtCard.billing_address = billingAddress;
            crdtCard.cvv2            = 874;
            crdtCard.expire_month    = 11;
            crdtCard.expire_year     = 2018;
            crdtCard.first_name      = "Joe";
            crdtCard.last_name       = "Shopper";
            crdtCard.number          = "4417119669820331";
            crdtCard.type            = "visa";

            // ###Details
            // Let's you specify details of a payment amount.
            Details details = new Details();

            details.shipping = "1";
            details.subtotal = "5";
            details.tax      = "1";

            // ###Amount
            // Let's you specify a payment amount.
            Amount amnt = new Amount();

            amnt.currency = "USD";
            // Total must be equal to sum of shipping, tax and subtotal.
            amnt.total   = "7";
            amnt.details = details;

            // ###Transaction
            // A transaction defines the contract of a
            // payment - what is the payment for and who
            // is fulfilling it.
            Transaction tran = new Transaction();

            tran.amount         = amnt;
            tran.description    = "This is the payment transaction description.";
            tran.item_list      = itemList;
            tran.invoice_number = "123123";

            // The Payment creation API requires a list of
            // Transaction; add the created `Transaction`
            // to a List
            List <Transaction> transactions = new List <Transaction>();

            transactions.Add(tran);

            // ###FundingInstrument
            // A resource representing a Payer's funding instrument.
            // For direct credit card payments, set the CreditCard
            // field on this object.
            FundingInstrument fundInstrument = new FundingInstrument();

            fundInstrument.credit_card = crdtCard;

            // The Payment creation API requires a list of
            // FundingInstrument; add the created `FundingInstrument`
            // to a List
            List <FundingInstrument> fundingInstrumentList = new List <FundingInstrument>();

            fundingInstrumentList.Add(fundInstrument);

            // ###Payer
            // A resource representing a Payer that funds a payment
            // Use the List of `FundingInstrument` and the Payment Method
            // as `credit_card`
            Payer payr = new Payer();

            payr.funding_instruments = fundingInstrumentList;
            payr.payment_method      = "credit_card";

            // ###Payment
            // A Payment Resource; create one using
            // the above types and intent as `sale` or `authorize`
            Payment pymnt = new Payment();

            pymnt.intent       = "sale";
            pymnt.payer        = payr;
            pymnt.transactions = transactions;

            try
            {
                // ### Api Context
                // Pass in a `APIContext` object to authenticate
                // the call and to send a unique request id
                // (that ensures idempotency). The SDK generates
                // a request id if you do not pass one explicitly.
                // See [Configuration.cs](/Source/Configuration.html) to know more about APIContext..
                APIContext apiContext = Configuration.GetAPIContext();

                // Create a payment using a valid APIContext
                Payment createdPayment = pymnt.Create(apiContext);
                CurrContext.Items.Add("ResponseJson", Common.FormatJsonString(createdPayment.ConvertToJson()));
            }
            catch (PayPal.Exception.PayPalException ex)
            {
                CurrContext.Items.Add("Error", ex.Message);
            }

            CurrContext.Items.Add("RequestJson", Common.FormatJsonString(pymnt.ConvertToJson()));

            Server.Transfer("~/Response.aspx");
        }
コード例 #19
0
 public UsersController(APIContext context)
 {
     _context = context;
 }
コード例 #20
0
ファイル: PaypalController.cs プロジェクト: MarekJJ/MyStore
        private Payment CreatePayment(APIContext apiContext, string redirectUrl)
        {
            Cart cart = (Cart)HttpContext.Session["Cart"]; // cart from session

            //similar to credit card create itemlist and add item objects to it
            ItemList itemlist = new ItemList()
            {
                items = new List <Item>()
            };
            double sum = 0;
            double con = 0;

            foreach (var p in cart.Lines)
            {
                con = (double)p.Product.Price;
                itemlist.items.Add(new Item()
                {
                    name = p.Product.Name1.ToString(), currency = "PLN", price = con.ToString(), quantity = "1", sku = "sku"
                });
                sum += (double)p.Product.Price;
            }
            var itemList = itemlist;


            var payer = new Payer()
            {
                payment_method = "paypal"
            };

            // Configure Redirect Urls here with RedirectUrls object
            var redirUrls = new RedirectUrls()
            {
                cancel_url = redirectUrl,
                return_url = redirectUrl
            };

            // similar as we did for credit card, do here and create details object
            var details = new Details()
            {
                tax      = "1",
                shipping = "1",
                subtotal = sum.ToString() // here is sum of all prices
            };
            double dupa = sum + 2;
            // similar as we did for credit card, do here and create amount object
            var amount = new Amount()
            {
                currency = "PLN",
                total    = dupa.ToString(), //this is sum to all objesct tax and shipping
                details  = details
            };

            var transactionList           = new List <Transaction>();
            PayPalUniqeNumber uniqeNunber = new PayPalUniqeNumber();

            transactionList.Add(new Transaction()
            {
                description    = "Transaction description.",
                invoice_number = uniqeNunber.ProductNumberToFile(), /*here is , uniqe number */
                amount         = amount,
                item_list      = itemList
            });

            this.payment = new Payment()
            {
                intent        = "sale",
                payer         = payer,
                transactions  = transactionList,
                redirect_urls = redirUrls
            };

            // Create a payment using a APIContext
            return(this.payment.Create(apiContext));
        }
コード例 #21
0
ファイル: APIHost.cs プロジェクト: kumaryu/peercaststation
    private async Task OnProcess(IDictionary<string, object> owinenv)
    {
      var env = new OWINEnv(owinenv);
      var cancel_token = env.CallCanlelled;
      try {
        
        if (!HTTPUtils.CheckAuthorization(env.GetAuthorizationToken(), env.AccessControlInfo)) {
          throw new HTTPError(HttpStatusCode.Unauthorized);
        }
        var ctx = new APIContext(this, this.Application.PeerCast, env.AccessControlInfo);
        var rpc_host = new JSONRPCHost(ctx);
        switch (env.RequestMethod) {
        case "HEAD":
        case "GET":
          await SendJson(env, ctx.GetVersionInfo(), env.RequestMethod!="HEAD", cancel_token);
          break;
        case "POST":
          {
            if (!env.RequestHeaders.ContainsKey("X-REQUESTED-WITH")) {
              throw new HTTPError(HttpStatusCode.BadRequest);
            }
            if (!env.RequestHeaders.ContainsKey("CONTENT-LENGTH")) {
              throw new HTTPError(HttpStatusCode.LengthRequired);
            }
            var body = env.RequestBody;
            var len  = body.Length;
            if (len<=0 || RequestLimit<len) {
              throw new HTTPError(HttpStatusCode.BadRequest);
            }

            try {
              var timeout_token = new CancellationTokenSource(TimeoutLimit);
              var buf = await body.ReadBytesAsync((int)len, CancellationTokenSource.CreateLinkedTokenSource(cancel_token, timeout_token.Token).Token);
              var request_str = System.Text.Encoding.UTF8.GetString(buf);
              JToken res = rpc_host.ProcessRequest(request_str);
              if (res!=null) {
                await SendJson(env, res, true, cancel_token);
              }
              else {
                throw new HTTPError(HttpStatusCode.NoContent);
              }
            }
            catch (OperationCanceledException) {
              throw new HTTPError(HttpStatusCode.RequestTimeout);
            }
          }
          break;
        default:
          throw new HTTPError(HttpStatusCode.MethodNotAllowed);
        }
      }
      catch (HTTPError err) {
        env.ResponseStatusCode = (int)err.StatusCode;
      }
      catch (UnauthorizedAccessException) {
        env.ResponseStatusCode = (int)HttpStatusCode.Forbidden;
      }
    }
コード例 #22
0
 public ProductController(APIContext context)
 {
     _context = context;
 }
コード例 #23
0
 public ContactService(APIContext apiContext)
 {
     _context = apiContext;
 }
コード例 #24
0
        private Payment CreatePayment(APIContext apicontext, string redirectUrl)
        {
            var itemList = new ItemList()
            {
                items = new List <Item>()
            };

            var cart = Session["Cart"] as List <CartViewModel>;

            foreach (var model in cart)
            {
                itemList.items.Add(new Item()
                {
                    name     = model.Name,
                    currency = "USD",
                    price    = model.Price.ToString(),
                    quantity = model.Quantity.ToString(),
                    sku      = "sku"
                });
            }

            var payer = new Payer()
            {
                payment_method = "paypal"
            };

            var redirectUrls = new RedirectUrls()
            {
                cancel_url = redirectUrl + "&cancel=true",
                return_url = redirectUrl
            };

            //adding taxes,shipping and subtotal
            var details = new Details()
            {
                tax      = "1",
                shipping = "2",
                subtotal = cart.Sum(c => c.Price * c.Quantity).ToString()
            };

            //final amount with details
            var amount = new Amount()
            {
                currency = "USD",
                details  = details,
                total    = (Convert.ToDouble(details.tax) + Convert.ToDouble(details.shipping) + Convert.ToDouble(details.subtotal)).ToString()
            };

            var transaction = new List <Transaction>();

            transaction.Add(new Transaction()
            {
                description    = "Custom Description",
                amount         = amount,
                item_list      = itemList,
                invoice_number = Convert.ToString(new Random().Next(100000))
            });

            this.payment = new Payment()
            {
                intent        = "sale",
                payer         = payer,
                transactions  = transaction,
                redirect_urls = redirectUrls
            };
            return(this.payment.Create(apicontext));
        }
コード例 #25
0
        public Payment CreatePayment(CreateOrderRequest request, string returnUrl, string cancelUrl, string intent)
        {
            var token      = new OAuthTokenCredential(PaypalConfig.CLIENT_ID, PaypalConfig.CLIENT_SECRET).GetAccessToken();
            var apiContext = new APIContext(token);

            var menuList = _opfcUow.MenuRepository
                           .GetAll()
                           .Where(m => request.RequestMenuList.Select(rm => rm.MenuId).Contains(m.Id))
                           .ToList();

            var total = (decimal)0;
            var items = new ItemList();

            items.items = new List <Item>();
            for (int i = 0; i < menuList.Count; i++)
            {
                items.items.Add(new Item
                {
                    quantity    = "1",
                    tax         = "0",
                    price       = menuList[i].Price.ToString(),
                    description = request.RequestMenuList[i].Note,
                    currency    = "USD",
                    sku         = request.RequestMenuList[i].MenuId.ToString()
                });

                total += menuList[i].Price;
            }

            var payment = new Payment()
            {
                intent = "sale",
                payer  = new Payer()
                {
                    payment_method = "paypal"
                },

                redirect_urls = new RedirectUrls()
                {
                    cancel_url = cancelUrl,
                    return_url = returnUrl
                },
                transactions = new List <Transaction>()
                {
                    new Transaction()
                    {
                        amount = new Amount()
                        {
                            total    = total.ToString(),
                            currency = "USD"
                        },
                        item_list   = items,
                        description = request.UserId + "||" + request.EventId
                    },
                }
            };

            payment = payment.Create(apiContext);

            return(payment);
        }
コード例 #26
0
ファイル: Common.cs プロジェクト: iljafiers/FotoLab
        // Create an authorized payment
        public static Authorization CreateAuthorization(APIContext apiContext)
        {
            // ###Address
            // Base Address object used as shipping or billing
            // address in a payment.
            Address billingAddress = new Address();

            billingAddress.city         = "Johnstown";
            billingAddress.country_code = "US";
            billingAddress.line1        = "52 N Main ST";
            billingAddress.postal_code  = "43210";
            billingAddress.state        = "OH";

            // ###CreditCard
            // A resource representing a credit card that can be
            // used to fund a payment.
            CreditCard crdtCard = new CreditCard();

            crdtCard.billing_address = billingAddress;
            crdtCard.cvv2            = "874";
            crdtCard.expire_month    = 11;
            crdtCard.expire_year     = 2018;
            crdtCard.first_name      = "Joe";
            crdtCard.last_name       = "Shopper";
            crdtCard.number          = "4417119669820331";
            crdtCard.type            = "visa";

            // ###Details
            // Let's you specify details of a payment amount.
            Details details = new Details();

            details.shipping = "0.03";
            details.subtotal = "107.41";
            details.tax      = "0.03";

            // ###Amount
            // Let's you specify a payment amount.
            Amount amnt = new Amount();

            amnt.currency = "USD";
            // Total must be equal to sum of shipping, tax and subtotal.
            amnt.total   = "107.47";
            amnt.details = details;

            // ###Transaction
            // A transaction defines the contract of a
            // payment - what is the payment for and who
            // is fulfilling it. Transaction is created with
            // a `Payee` and `Amount` types
            Transaction tran = new Transaction();

            tran.amount      = amnt;
            tran.description = "This is the payment transaction description.";

            // The Payment creation API requires a list of
            // Transaction; add the created `Transaction`
            // to a List
            List <Transaction> transactions = new List <Transaction>();

            transactions.Add(tran);

            // ###FundingInstrument
            // A resource representing a Payeer's funding instrument.
            // Use a Payer ID (A unique identifier of the payer generated
            // and provided by the facilitator. This is required when
            // creating or using a tokenized funding instrument)
            // and the `CreditCardDetails`
            FundingInstrument fundInstrument = new FundingInstrument();

            fundInstrument.credit_card = crdtCard;

            // The Payment creation API requires a list of
            // FundingInstrument; add the created `FundingInstrument`
            // to a List
            List <FundingInstrument> fundingInstrumentList = new List <FundingInstrument>();

            fundingInstrumentList.Add(fundInstrument);

            // ###Payer
            // A resource representing a Payer that funds a payment
            // Use the List of `FundingInstrument` and the Payment Method
            // as 'credit_card'
            Payer payr = new Payer();

            payr.funding_instruments = fundingInstrumentList;
            payr.payment_method      = "credit_card";

            // ###Payment
            // A Payment Resource; create one using
            // the above types and intent as `sale`
            Payment pymnt = new Payment();

            pymnt.intent       = "authorize";
            pymnt.payer        = payr;
            pymnt.transactions = transactions;

            // Create a payment by posting to the APIService
            // using a valid APIContext
            Payment createdPayment = pymnt.Create(apiContext);

            return(createdPayment.transactions[0].related_resources[0].authorization);
        }
コード例 #27
0
        public Payment CreatePayment(APIContext apiContext, string redirectUrl, PricingPlanDto objInvoiceItem)
        {
            //similar to credit card create itemlist and add item objects to it
            var itemList = new ItemList()
            {
                items = new List <Item>()
            };

            itemList.items.Add(new Item()
            {
                name     = objInvoiceItem.PlanName,
                currency = "USD",
                quantity = "1",
                sku      = "sku",
                price    = objInvoiceItem.PlanPricing.ToString()
            });

            var payer = new Payer()
            {
                payment_method = "paypal"
            };

            // Configure Redirect Urls here with RedirectUrls object
            var redirUrls = new RedirectUrls()
            {
                cancel_url = redirectUrl,
                return_url = redirectUrl
            };

            // similar as we did for credit card, do here and create details object
            var details = new Details()
            {
                subtotal = objInvoiceItem.PlanPricing.ToString()
            };

            // similar as we did for credit card, do here and create amount object
            var amount = new Amount()
            {
                currency = "USD",
                total    = (Convert.ToDouble(objInvoiceItem.PlanPricing)).ToString(),
                details  = details
            };

            var    transactionList = new List <Transaction>();
            Random rnd             = new Random();
            int    invoiceID       = rnd.Next(1, 1300);

            transactionList.Add(new Transaction()
            {
                description    = "Transaction description.",
                invoice_number = invoiceID.ToString(),
                amount         = amount,
                item_list      = itemList
            });

            this.payment = new Payment()
            {
                intent        = "sale",
                payer         = payer,
                transactions  = transactionList,
                redirect_urls = redirUrls
            };

            // Create a payment using a APIContext
            return(this.payment.Create(apiContext));
        }
コード例 #28
0
ファイル: PaymentTest.cs プロジェクト: ruanzx/PayPal-NET-SDK
 public static Payment CreatePaymentOrder(APIContext apiContext)
 {
     return GetPaymentOrder().Create(apiContext);
 }
コード例 #29
0
        public ActionResult Void(string authorizationId)
        {
            var viewData = new PayPalViewData();

            try
            {
                var accessToken = new OAuthTokenCredential(ConfigManager.Instance.GetProperties()["ClientID"], ConfigManager.Instance.GetProperties()["ClientSecret"]).GetAccessToken();
                var apiContext = new APIContext(accessToken);
                var authorization = Authorization.Get(apiContext, authorizationId);

                if (authorization != null)
                {
                    var voidedAuthorization = authorization.Void(apiContext);

                    viewData.JsonResponse = JObject.Parse(voidedAuthorization.ConvertToJson()).ToString(Formatting.Indented);

                    return View(viewData);
                }

                viewData.ErrorMessage = "Could not find previous authorization.";

                return View("Error", viewData);
            }
            catch (PayPalException ex)
            {
                viewData.ErrorMessage = ex.Message;

                return View("Error", viewData);
            }
        }
コード例 #30
0
        public ActionResult Capture(string authorizationId)
        {
            verificarSesion();
            var viewData = new ConfirmedViewData();

            try
            {
                var accessToken   = new OAuthTokenCredential(ConfigManager.Instance.GetProperties()["clientId"], ConfigManager.Instance.GetProperties()["clientSecret"]).GetAccessToken();
                var apiContext    = new APIContext(accessToken);
                var authorization = Authorization.Get(apiContext, authorizationId);

                if (authorization != null)
                {
                    var total = Convert.ToDouble(authorization.amount.total);

                    //Sacando informacion de la reseva
                    var reservaID = ((EntCuenta)Session["cuenta"]).ReservaID;
                    var monto     = ((EntCuenta)Session["cuenta"]).Monto;

                    var capture = authorization.Capture(apiContext, new Capture
                    {
                        is_final_capture = true,
                        amount           = new Amount
                        {
                            currency = "USD",
                            total    = total.ToString("f2")
                        },
                    });


                    viewData.JsonResponse = JObject.Parse(capture.ConvertToJson()).ToString(Formatting.Indented);

                    //Generando comprobante de pago
                    Random rdn = new Random();

                    EntReserva reserva = new EntReserva
                    {
                        ReservaID = reservaID
                    };

                    EntComprobantepagoreserva fact = new EntComprobantepagoreserva
                    {
                        Monto       = monto,
                        NumeroSerie = rdn.Next(10001, int.MaxValue),
                        Reserva     = reserva
                    };

                    Boolean generarCPReserva = LogComprobanteReserva.Instancia.GenerarComprobanteReserva(fact);

                    //Limpiamos la información de la reserva
                    ((EntCuenta)Session["cuenta"]).ReservaID = 0;
                    ((EntCuenta)Session["cuenta"]).Monto     = 0;

                    viewData.ReservaID = fact.Reserva.ReservaID;
                    viewData.Monto     = fact.Monto;
                    viewData.Serie     = fact.NumeroSerie;

                    return(View("Success", viewData));
                }

                viewData.ErrorMessage = "Could not find previous authorization.";

                return(View("Error", viewData));
            }
            catch (PayPalException ex)
            {
                viewData.ErrorMessage = ex.Message;

                return(View("Error", viewData));
            }
        }
コード例 #31
0
ファイル: PaypalController.cs プロジェクト: MarekJJ/MyStore
        public ActionResult PaymentWithPaypal()
        {
            //getting the apiContext as earlier
            APIContext apiContext = Configuration.GetAPIContext();

            try
            {
                string payerId = Request.Params["PayerID"];

                if (string.IsNullOrEmpty(payerId))
                {
                    //this section will be executed first because PayerID doesn't exist

                    //it is returned by the create function call of the payment class

                    // Creating a payment

                    // baseURL is the url on which paypal sendsback the data.

                    // So we have provided URL of this controller only

                    string baseURI = Request.Url.Scheme + "://" + Request.Url.Authority + "/Paypal/PaymentWithPayPal?";

                    //guid we are generating for storing the paymentID received in session

                    //after calling the create function and it is used in the payment execution

                    var guid = Convert.ToString((new Random()).Next(100000));

                    //CreatePayment function gives us the payment approval url

                    //on which payer is redirected for paypal acccount payment

                    var createdPayment = this.CreatePayment(apiContext, baseURI + "guid=" + guid);

                    //get links returned from paypal in response to Create function call

                    var links = createdPayment.links.GetEnumerator();

                    string paypalRedirectUrl = null;

                    while (links.MoveNext())
                    {
                        Links lnk = links.Current;

                        if (lnk.rel.ToLower().Trim().Equals("approval_url"))
                        {
                            //saving the payapalredirect URL to which user will be redirected for payment
                            paypalRedirectUrl = lnk.href;
                        }
                    }

                    // saving the paymentID in the key guid
                    Session.Add(guid, createdPayment.id);

                    return(Redirect(paypalRedirectUrl));
                }
                else
                {
                    // This section is executed when we have received all the payments parameters

                    // from the previous call to the function Create

                    // Executing a payment

                    var guid = Request.Params["guid"];

                    var executedPayment = ExecutePayment(apiContext, payerId, Session[guid] as string);

                    if (executedPayment.state.ToLower() != "approved")
                    {
                        return(View("FailureView"));
                    }
                }
            }
            catch (Exception ex) //Excepion opisuje wiele bledow  rzeszta rodzajow exceptoin dziediczy z tej
            {
                Infastructure.PayPalLooger.Logger.Log("Error" + ex.Message);
                return(View("FailureView"));
            }
            Cart cart = (Cart)HttpContext.Session["Cart"]; // udalo sie tak zapodac tutaj sesje

            return(View("SuccessView", cart));
        }
コード例 #32
0
        public ActionResult CreatePayment(int id, double monto, double tax, double shipping)
        {
            var viewData = new PayPalViewData();
            var guid     = Guid.NewGuid().ToString();

            var paymentInit = new Payment
            {
                intent = "authorize",
                payer  = new Payer
                {
                    payment_method = "paypal"
                },
                transactions = new List <Transaction>
                {
                    new Transaction
                    {
                        amount = new Amount
                        {
                            currency = "USD",
                            total    = (monto + tax + shipping).ToString(),
                            details  = new Details
                            {
                                subtotal = monto.ToString(),
                                tax      = tax.ToString(),
                                shipping = shipping.ToString()
                            }
                        },
                        description = "Reservar una habitación"
                    }
                },
                redirect_urls = new RedirectUrls
                {
                    return_url = Utilities.ToAbsoluteUrl(HttpContext, string.Format("~/paypal/confirmed?id={0}", guid)),
                    cancel_url = Utilities.ToAbsoluteUrl(HttpContext, string.Format("~/paypal/canceled?id={0}", guid)),
                },
            };

            viewData.JsonRequest = JObject.Parse(paymentInit.ConvertToJson()).ToString(Formatting.Indented);

            try
            {
                var accessToken    = new OAuthTokenCredential(ConfigManager.Instance.GetProperties()["clientId"], ConfigManager.Instance.GetProperties()["clientSecret"]).GetAccessToken();
                var apiContext     = new APIContext(accessToken);
                var createdPayment = paymentInit.Create(apiContext);

                var approvalUrl = createdPayment.links.ToArray().FirstOrDefault(f => f.rel.Contains("approval_url"));

                if (approvalUrl != null)
                {
                    Session.Add(guid, createdPayment.id);

                    return(Redirect(approvalUrl.href));
                }

                viewData.JsonResponse = JObject.Parse(createdPayment.ConvertToJson()).ToString(Formatting.Indented);

                return(View("Error", viewData));
            }
            catch (PayPalException ex)
            {
                viewData.ErrorMessage = ex.Message;

                return(View("Error", viewData));
            }
        }
コード例 #33
0
 private PayPal.Api.Payment ExecutePayment(APIContext apiContext, string payerId, string paymentId)
 {
     var paymentExecution = new PaymentExecution() { payer_id = payerId };
     this.payment = new PayPal.Api.Payment() { id = paymentId };
     return this.payment.Execute(apiContext, paymentExecution);
 }
コード例 #34
0
        public bool CreatePayment(string priceStr, string description)
        {
            try
            {
                // Authenticate with PayPal
                var config      = ConfigManager.Instance.GetProperties();
                var accessToken = new OAuthTokenCredential(config).GetAccessToken();
                apiContext = new APIContext(accessToken);

                var itemList = new ItemList()
                {
                    items = new List <Item>()
                    {
                        new Item()
                        {
                            name     = "PrintAhead print",
                            currency = "USD",
                            price    = priceStr,
                            quantity = "1",
                            sku      = "sku"
                        }
                    }
                };

                var payer = new Payer()
                {
                    payment_method = "paypal"
                };
                var redirUrls = new RedirectUrls()
                {
                    cancel_url = "http://www.abalonellc.com/hairshop-10-coming-so10.html",
                    return_url = "http://www.abalonellc.com/"
                };

                var details = new Details()
                {
                    tax      = "0",
                    shipping = "0",
                    subtotal = priceStr
                };

                var amount = new Amount()
                {
                    currency = "USD",
                    total    = priceStr, // Total must be equal to sum of shipping, tax and subtotal.
                    details  = details
                };

                var transactionList = new List <Transaction>
                {
                    new Transaction()
                    {
                        description    = description, // transaction description
                        invoice_number = GetRandomInvoiceNumber(),
                        amount         = amount,
                        item_list      = itemList
                    }
                };



                var payment = new Payment()
                {
                    intent        = "sale",
                    payer         = payer,
                    transactions  = transactionList,
                    redirect_urls = redirUrls
                };


                createdPayment = payment.Create(apiContext);
                var links       = createdPayment.links.GetEnumerator();
                var hasGoodLink = false;
                while (links.MoveNext())
                {
                    var link = links.Current;
                    if (link != null && link.rel.ToLower().Trim().Equals("approval_url"))
                    {
                        chromeBrowser.Load(link.href);
                        hasGoodLink = true;
                        break;
                    }
                }

                if (!hasGoodLink)
                {
                    return(false);
                }
            }
            catch (PaymentsException ex)
            {
                // Get the details of this exception with ex.Details.  If you have logging setup for your project, this information will also be automatically logged to your logfile.
                var sb = new StringBuilder();
                sb.AppendLine("Error:    " + ex.Details.name);
                sb.AppendLine("Message:  " + ex.Details.message);
                sb.AppendLine("URI:      " + ex.Details.information_link);
                sb.AppendLine("Debug ID: " + ex.Details.debug_id);
                MessageBox.Show(sb.ToString());
                return(false);
            }
            return(true);
        }
コード例 #35
0
 public FundosController(APIContext context)
 {
     _context = context;
 }
コード例 #36
0
        protected void btnPurchase_Click(object sender, EventArgs e)
        {
            decimal postagePackagingCost = 3.95m;
            decimal productPrice         = 10.00m;
            string  colorselected        = DropDownList2.SelectedValue;
            int     quantityOfProduct    = int.Parse(DropDownList1.SelectedValue);
            decimal subTotal             = (quantityOfProduct * productPrice);
            decimal total = subTotal + postagePackagingCost;

            var config      = ConfigManager.Instance.GetProperties();
            var accesstoken = new OAuthTokenCredential(config).GetAccessToken();
            var apiContext  = new APIContext(accesstoken);

            var Prod_Item = new Item();

            Prod_Item.name     = "Prod_ID";
            Prod_Item.currency = "BND";
            Prod_Item.price    = productPrice.ToString();
            Prod_Item.sku      = "PRO1";
            Prod_Item.quantity = quantityOfProduct.ToString();

            var detailsoftransaction = new Details();

            detailsoftransaction.tax      = "0";
            detailsoftransaction.shipping = postagePackagingCost.ToString();
            detailsoftransaction.subtotal = subTotal.ToString("0.09");

            var amountoftransaction = new Amount();

            amountoftransaction.currency = "BND";
            amountoftransaction.total    = total.ToString("0.00");
            amountoftransaction.details  = detailsoftransaction;

            var transaction = new Transaction();

            transaction.description    = "Product 1 description";
            transaction.invoice_number = Guid.NewGuid().ToString();
            transaction.amount         = amountoftransaction;
            transaction.item_list      = new ItemList
            {
                items = new List <Item> {
                    Prod_Item
                }
            };
            var buyer = new Payer();

            buyer.payment_method = "paypal";

            var redirectUrls = new RedirectUrls();

            redirectUrls.cancel_url = "http://" + HttpContext.Current.Request.Url.Authority + "Cancel.aspx";
            redirectUrls.return_url = "http://" + HttpContext.Current.Request.Url.Authority + "CompletePurchase.aspx";

            var payment = Payment.Create(apiContext, new Payment
            {
                intent       = "sale",
                payer        = buyer,
                transactions = new List <Transaction> {
                    transaction
                },
                redirect_urls = redirectUrls
            });

            Session["paymentId"] = payment.id;
            foreach (var link in payment.links)
            {
                if (link.rel.ToLower().Trim().Equals("approval_url"))
                {
                    Response.Redirect(link.href);
                }
            }
        }
コード例 #37
0
 public PaymentsController()
 {
     this.apiContext = Common.GetApiContext();
     this.customerId = Common.GetCustomerId();
     this.plans = Plan.List(apiContext, status: "ACTIVE");
 }
コード例 #38
0
        //UserRoleRepository UserRoleRepository { set; get; }
        //RoleAuthorityRepository RoleAuthorityRepository { set; get; }
        //RoleRepository RoleRepository { set; get; }

        /// <summary>
        ///
        /// </summary>
        public AccountService(APIContext apiContext)
        {
            APIContext    = apiContext;
            FMPTDbContext = APIContext?.GetDBContext("FMPT");
            Init(FMPTDbContext);
        }
コード例 #39
0
        /// <summary>
        /// Creates (and processes) a new Refund Transaction added as a related resource.
        /// </summary>
        /// <param name="accessToken">Access Token used for the API call.</param>
        /// <param name="refund">Refund</param>
        /// <returns>Refund</returns>
        public Refund Refund(string accessToken, Refund refund)
        {
            APIContext apiContext = new APIContext(accessToken);

            return(Refund(apiContext, refund));
        }
コード例 #40
0
ファイル: Payment.cs プロジェクト: rick527/PayPal-NET-SDK
        /// <summary>
        /// Creates (and processes) a new Payment Resource.
        /// </summary>
        /// <param name="accessToken">Access Token used for the API call.</param>
        /// <returns>Payment</returns>
        public Payment Create(string accessToken)
        {
            APIContext apiContext = new APIContext(accessToken);

            return(Create(apiContext));
        }
コード例 #41
0
 public DataSeed(APIContext ctx)
 {
     _ctx = ctx;
 }
コード例 #42
0
ファイル: Payment.cs プロジェクト: rick527/PayPal-NET-SDK
        /// <summary>
        /// Obtain the Payment resource for the given identifier.
        /// </summary>
        /// <param name="accessToken">Access Token used for the API call.</param>
        /// <param name="paymentId">string</param>
        /// <returns>Payment</returns>
        public static Payment Get(string accessToken, string paymentId)
        {
            APIContext apiContext = new APIContext(accessToken);

            return(Get(apiContext, paymentId));
        }
コード例 #43
0
ファイル: PaymentTest.cs プロジェクト: ruanzx/PayPal-NET-SDK
 public static Payment CreatePaymentForSale(APIContext apiContext)
 {
     return GetPaymentForSale().Create(apiContext);
 }
コード例 #44
0
ファイル: Payment.cs プロジェクト: rick527/PayPal-NET-SDK
        /// <summary>
        /// Executes the payment (after approved by the Payer) associated with this resource when the payment method is PayPal.
        /// </summary>
        /// <param name="accessToken">Access Token used for the API call.</param>
        /// <param name="paymentExecution">PaymentExecution</param>
        /// <returns>Payment</returns>
        public Payment Execute(string accessToken, PaymentExecution paymentExecution)
        {
            APIContext apiContext = new APIContext(accessToken);

            return(Execute(apiContext, paymentExecution));
        }
コード例 #45
0
        private PayPal.Api.Payment CreatePayment(APIContext apiContext, string redirectUrl)
        {
            List <Product> products = new List <Product>();
            //create itemlist and add item objects to it
            var itemList = new ItemList()
            {
                items = new List <Item>()
            };

            //Adding Item Details like name, currency, price etc
            foreach (var item in products)
            {
                itemList.items.Add(new Item()
                {
                    name     = item.ProductName,
                    currency = "USD",
                    price    = item.Price.ToString(),
                    quantity = item.NumberAvailable.ToString(),
                    sku      = "sku"
                });
            }
            var payer = new Payer()
            {
                payment_method = "paypal"
            };
            // Configure Redirect Urls here with RedirectUrls object
            var redirUrls = new RedirectUrls()
            {
                cancel_url = redirectUrl + "&Cancel=true",
                return_url = redirectUrl
            };
            // Adding Tax, shipping and Subtotal details
            var details = new Details()
            {
                tax      = "1",
                shipping = "1",
                subtotal = "1"
            };
            //Final amount with details
            var amount = new Amount()
            {
                currency = "USD",
                total    = "3", // Total must be equal to sum of tax, shipping and subtotal.
                details  = details
            };
            var transactionList = new List <Transaction>();

            // Adding description about the transaction
            transactionList.Add(new Transaction()
            {
                description    = "Transaction description",
                invoice_number = "your generated invoice number", //Generate an Invoice No
                amount         = amount,
                item_list      = itemList
            });
            this.payment = new PayPal.Api.Payment()
            {
                intent        = "sale",
                payer         = payer,
                transactions  = transactionList,
                redirect_urls = redirUrls
            };
            // Create a payment using a APIContext
            return(this.payment.Create(apiContext));
        }
コード例 #46
0
ファイル: Payment.cs プロジェクト: rick527/PayPal-NET-SDK
        /// <summary>
        /// Retrieves a list of Payment resources.
        /// </summary>
        /// <param name="accessToken">Access Token used for the API call.</param>
        /// <param name="containerDictionary">Dictionary<String, String></param>
        /// <returns>PaymentHistory</returns>
        public static PaymentHistory List(string accessToken, Dictionary <String, String> containerDictionary)
        {
            APIContext apiContext = new APIContext(accessToken);

            return(List(apiContext, containerDictionary));
        }
コード例 #47
0
ファイル: CoA.cs プロジェクト: TheGrandCoding/discord-bot
 public CoA(APIContext c) : base(c, "chess/coa")
 {
     ChesssInstance = Program.Services.GetRequiredService <ChessService>();
     Sidebar        = SidebarType.Local;
     InjectObjects.Add(new PageLink("stylesheet", "text/css", "/_/css/chessCOA.css"));
 }
コード例 #48
0
 public PlanesController(APIContext context)
 {
     _context = context;
 }
コード例 #49
0
        //
        // GET: /Payment/
        public ActionResult CreatePayment(string description, decimal price, decimal tax = 0, decimal shipping = 0)
        {
            var viewData = new PayPalViewData();
            var guid = Guid.NewGuid().ToString();

            var paymentInit = new Payment
            {
                intent = "authorize",
                payer = new Payer
                {
                    payment_method = "paypal"
                },
                transactions = new List<Transaction>
                {
                    new Transaction
                    {
                        amount = new Amount
                        {
                            currency = "USD",
                            total = (price + tax + shipping).ToString(),
                            details = new Details
                            {
                                subtotal = price.ToString(),
                                tax = tax.ToString(),
                                shipping = shipping.ToString()
                            }
                        },
                        description = description
                    }
                },
                redirect_urls = new RedirectUrls
                {
                    return_url = Utilities.ToAbsoluteUrl(HttpContext, String.Format("~/paypal/confirmed?id={0}", guid)),
                    cancel_url = Utilities.ToAbsoluteUrl(HttpContext, String.Format("~/paypal/canceled?id={0}", guid)),
                },
            };

            viewData.JsonRequest = JObject.Parse(paymentInit.ConvertToJson()).ToString(Formatting.Indented);

            try
            {
                var accessToken = new OAuthTokenCredential(ConfigManager.Instance.GetProperties()["ClientID"], ConfigManager.Instance.GetProperties()["ClientSecret"]).GetAccessToken();
                var apiContext = new APIContext(accessToken);
                var createdPayment = paymentInit.Create(apiContext);

                var approvalUrl = createdPayment.links.ToArray().FirstOrDefault(f => f.rel.Contains("approval_url"));

                if (approvalUrl != null)
                {
                    Session.Add(guid, createdPayment.id);

                    return Redirect(approvalUrl.href);
                }

                viewData.JsonResponse = JObject.Parse(createdPayment.ConvertToJson()).ToString(Formatting.Indented);

                return View("Error", viewData);
            }
            catch (PayPalException ex)
            {
                viewData.ErrorMessage = ex.Message;

                return View("Error", viewData);
            }
        }
コード例 #50
0
 public void DomNullConfigMapTest()
 {
     APIContext api = new APIContext();
     Dictionary<string, string> configurationMap = null;
     new DefaultSOAPAPICallHandler(new SampleBody(), api, configurationMap, "DoDirectPayment");
 }
コード例 #51
0
ファイル: HomeController.cs プロジェクト: tzobell/photoweb
 /// <summary>
 /// gets acces token and creates apiContext for Paypal api
 /// </summary>
 /// <returns>ApiContext</returns>
 private APIContext GetAPIContext()
 {
     Dictionary<string, string> sdkConfig = new Dictionary<string, string>();
     sdkConfig.Add("mode", "sandbox");
     string accessToken = new OAuthTokenCredential("Ae2ZWMxCl_ueuNy87vcg52hTjX9aVWfnvLQSMjDuTn2sj0crrWYIWwPseO_6H4nLpXKcHE9_DjtrmDEC", "EEmZr7iiuNCksXtPh5NjcVcguVGic0TwCW-f7GFmgfmrG8wBUhn_UJj53OxraTkKijC4UYQHv-fzlH7z", sdkConfig).GetAccessToken();
     APIContext apiContext = new APIContext(accessToken);
     return apiContext;
 }
コード例 #52
0
    public void DomPayloadTest()
    {
        DefaultSOAPAPICallHandler.XMLNamespaceProvider = new XmlNamespacePrefixProvider();
        APIContext api = new APIContext();
        api.SOAPHeader = new SampleHeader();
        Dictionary<string, string> configurationMap = new Dictionary<string, string>();
        configurationMap.Add("service.EndPoint", "https://api-3t.sandbox.paypal.com/2.0");
        api.Config = configurationMap;

        DefaultSOAPAPICallHandler defHandler = new DefaultSOAPAPICallHandler(new SampleBody(), api, null, "DoDirectPayment");
        string payload = defHandler.GetPayload().Trim();
        string expectedPayload = "<soapenv:Envelope xmlns:xml=\"http://www.w3.org/XML/1998/namespace\" xmlns:ed=\"urn:ebay:apis:EnhancedDataTypes\" xmlns:cc=\"urn:ebay:apis:CoreComponentTypes\" xmlns:ebl=\"urn:ebay:apis:eBLBaseComponents\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:wsdlsoap=\"http://schemas.xmlsoap.org/wsdl/soap/\" xmlns:ns=\"urn:ebay:api:PayPalAPI\" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:wsdl=\"http://schemas.xmlsoap.org/wsdl/\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">"  +
            "<soapenv:Header>" +
            "<ns:RequesterCredentials>" +
            "<ebl:Credentials>" +
            "<ebl:Username>jb-us-seller_api1.paypal.com</ebl:Username>" +
            "</ebl:Credentials>" +
            "</ns:RequesterCredentials>" +
            "</soapenv:Header>" +
            "<soapenv:Body>" +
            "<ns:DoDirectPaymentReq>" +
            "<ns:DoDirectPaymentRequest>" +
            "<ebl:Version>98.0</ebl:Version>" +
            "<ebl:DoDirectPaymentRequestDetails>" +
            "<ebl:CreditCard>" +
            "<ebl:CreditCardType>Visa</ebl:CreditCardType>" +
            "<ebl:CreditCardNumber>4202297003827029</ebl:CreditCardNumber>" +
            "<ebl:CVV2>962</ebl:CVV2>" +
            "</ebl:CreditCard>" +
            "</ebl:DoDirectPaymentRequestDetails>" +
            "</ns:DoDirectPaymentRequest>" +
            "</ns:DoDirectPaymentReq>" +
            "</soapenv:Body>" +
        "</soapenv:Envelope>";
        Assert.AreEqual(expectedPayload, payload);
    }
コード例 #53
0
ファイル: Tokeninfo.cs プロジェクト: PieterScheffers/FotoLab
 /// <summary>
 /// Creates an Access Token from an Refresh Token
 /// <param name="apiContext">APIContext to be used for the call</param>
 /// <param name="createFromRefreshTokenParameters">Query parameters used for API call</param>
 /// </summary>
 public Tokeninfo CreateFromRefreshToken(APIContext apiContext, CreateFromRefreshTokenParameters createFromRefreshTokenParameters)
 {
     string pattern = "v1/identity/openidconnect/tokenservice?grant_type={0}&refresh_token={1}&scope={2}&client_id={3}&client_secret={4}";
     createFromRefreshTokenParameters.SetRefreshToken(HttpUtility.UrlEncode(refresh_token));
     object[] parameters = new object[] { createFromRefreshTokenParameters };
     string resourcePath = SDKUtil.FormatURIPath(pattern, parameters);
     string payLoad = resourcePath.Substring(resourcePath.IndexOf('?') + 1);
     resourcePath = resourcePath.Substring(0, resourcePath.IndexOf("?"));
     Dictionary<string, string> headersMap = new Dictionary<string, string>();
     headersMap.Add(BaseConstants.ContentTypeHeader, "application/x-www-form-urlencoded");
     if (apiContext == null)
     {
         apiContext = new APIContext();
     }
     apiContext.HTTPHeaders = headersMap;
     apiContext.MaskRequestId = true;
     return PayPalResource.ConfigureAndExecute<Tokeninfo>(apiContext, HttpMethod.POST, resourcePath, payLoad);
 }
コード例 #54
0
 // make sure this user is either admin or trying to access something they own
 public static bool ValidateIsUserOrAdmin(IHttpContextAccessor httpContextAccessor, APIContext context, int id, string[] keyAndIV)
 {
     // verify that the user is either admin or is requesting their own data
     if (ValidateIsUser(httpContextAccessor, id) || ValidateIsAdmin(context, id, keyAndIV))
     {
         return(true);
     }
     else
     {
         return(false);
     }
 }
コード例 #55
0
ファイル: Userinfo.cs プロジェクト: ruanzx/PayPal-NET-SDK
 /// <summary>
 /// Returns user details
 /// <param name="apiContext">APIContext to be used for the call.</param>
 /// <param name="userinfoParameters">Query parameters used for API call</param>
 /// </summary>
 public static Userinfo GetUserinfo(APIContext apiContext, UserinfoParameters userinfoParameters)
 {
     string pattern = "v1/identity/openidconnect/userinfo?schema={0}&access_token={1}";
     object[] parameters = new object[] { userinfoParameters };
     string resourcePath = SDKUtil.FormatURIPath(pattern, parameters);
     if (apiContext == null)
     {
         apiContext = new APIContext();
     }
     apiContext.MaskRequestId = true;
     return PayPalResource.ConfigureAndExecute<Userinfo>(apiContext, HttpMethod.GET, resourcePath, setAuthorizationHeader: false);
 }
コード例 #56
0
        /// <summary>
        /// Obtain the Sale transaction resource for the given identifier.
        /// </summary>
        /// <param name="accessToken">Access Token used for the API call.</param>
        /// <param name="saleId">string</param>
        /// <returns>Sale</returns>
        public static Sale Get(string accessToken, string saleId)
        {
            APIContext apiContext = new APIContext(accessToken);

            return(Get(apiContext, saleId));
        }
コード例 #57
0
ファイル: ItemRepository.cs プロジェクト: BKrewer/PortalAPI
 public ItemRepository(APIContext context)
 {
     _context = context;
 }
コード例 #58
0
        /// <summary>
        /// Returns the PayPal URL to which the user must be redirected to start the 
        /// authentication / authorization process.
        /// </summary>
        /// <param name="clientId"></param>
        /// <param name="redirectURI"></param>
        /// <param name="scope"></param>
        /// <param name="apiContext"></param>
        /// <returns></returns>
        public static string GetRedirectURL(string clientId, string redirectURI, List<string> scope,
            APIContext apiContext)
        {
            string redirectURL = null;
            Dictionary<string, string> config = null;
            if (apiContext.Config == null)
            {
                config = ConfigManager.getConfigWithDefaults(ConfigManager.Instance.GetProperties());
            }
            else
            {
                config = ConfigManager.getConfigWithDefaults(apiContext.Config);
            }
            string baseURL = null;
            if (config.ContainsKey(BaseConstants.OPENID_REDIRECT_URI))
            {
                baseURL = config[BaseConstants.OPENID_REDIRECT_URI];
            }
            else if (config.ContainsKey(BaseConstants.APPLICATION_MODE_CONFIG))
            {
                string mode = config[BaseConstants.APPLICATION_MODE_CONFIG];
                if (mode.Equals(BaseConstants.LIVE_MODE))
                {
                    baseURL = BaseConstants.OPENID_LIVE_REDIRECT_URI_CONSTANT;
                }
                else if (mode.Equals(BaseConstants.SANDBOX_MODE))
                {
                    baseURL = BaseConstants.OPENID_SANDBOX_REDIRECT_URI_CONSTANT;
                }
                else
                {
                    throw new ConfigException("You must specify one of mode(live/sandbox) OR Redirect URI in the configuration");
                }
            }
            if (baseURL.EndsWith("/"))
            {
                baseURL = baseURL.Substring(0, baseURL.Length - 1);
            }
            if (scope == null || scope.Count <= 0)
            {
                scope = new List<string>();
                scope.Add("openid");
                scope.Add("profile");
                scope.Add("address");
                scope.Add("email");
                scope.Add("phone");
                scope.Add("https://uri.paypal.com/services/paypalattributes");
                scope.Add("https://uri.paypal.com/services/expresscheckout");
            }
            if (!scope.Contains("openid"))
            {
                scope.Add("openid");
            }
            StringBuilder strBuilder = new StringBuilder();

            if(clientId == null)
            {
                throw new ConfigException("You must set clientId");
            }
            strBuilder.Append("client_id=").Append(HttpUtility.UrlEncode(clientId)).Append("&response_type=").Append("code").Append("&scope=");
            StringBuilder scpBuilder = new StringBuilder();
            foreach (string str in scope)
            {
                scpBuilder.Append(str).Append(" ");
            }
            strBuilder.Append(HttpUtility.UrlEncode(scpBuilder.ToString()));
            strBuilder.Append("&redirect_uri=").Append(
                    HttpUtility.UrlEncode(redirectURI));
            redirectURL = baseURL + "/v1/authorize?" + strBuilder.ToString();
            return redirectURL;
        }
コード例 #59
0
        /// <summary>
        /// Returns the PayPal URL to which the user must be redirected to start the
        /// authentication / authorization process.
        /// </summary>
        /// <param name="clientId"></param>
        /// <param name="redirectURI"></param>
        /// <param name="scope"></param>
        /// <param name="apiContext"></param>
        /// <returns></returns>
        public static string GetRedirectURL(string clientId, string redirectURI, List <string> scope,
                                            APIContext apiContext)
        {
            string redirectURL = null;
            Dictionary <string, string> config = null;

            if (apiContext.Config == null)
            {
                config = ConfigManager.getConfigWithDefaults(ConfigManager.Instance.GetProperties());
            }
            else
            {
                config = ConfigManager.getConfigWithDefaults(apiContext.Config);
            }
            string baseURL = null;

            if (config.ContainsKey(BaseConstants.OPENID_REDIRECT_URI))
            {
                baseURL = config[BaseConstants.OPENID_REDIRECT_URI];
            }
            else if (config.ContainsKey(BaseConstants.APPLICATION_MODE_CONFIG))
            {
                string mode = config[BaseConstants.APPLICATION_MODE_CONFIG];
                if (mode.Equals(BaseConstants.LIVE_MODE))
                {
                    baseURL = BaseConstants.OPENID_LIVE_REDIRECT_URI_CONSTANT;
                }
                else if (mode.Equals(BaseConstants.SANDBOX_MODE))
                {
                    baseURL = BaseConstants.OPENID_SANDBOX_REDIRECT_URI_CONSTANT;
                }
                else
                {
                    throw new ConfigException("You must specify one of mode(live/sandbox) OR Redirect URI in the configuration");
                }
            }
            if (baseURL.EndsWith("/"))
            {
                baseURL = baseURL.Substring(0, baseURL.Length - 1);
            }
            if (scope == null || scope.Count <= 0)
            {
                scope = new List <string>();
                scope.Add("openid");
                scope.Add("profile");
                scope.Add("address");
                scope.Add("email");
                scope.Add("phone");
                scope.Add("https://uri.paypal.com/services/paypalattributes");
                scope.Add("https://uri.paypal.com/services/expresscheckout");
            }
            if (!scope.Contains("openid"))
            {
                scope.Add("openid");
            }
            StringBuilder strBuilder = new StringBuilder();

            if (clientId == null)
            {
                throw new ConfigException("You must set clientId");
            }
            strBuilder.Append("client_id=").Append(HttpUtility.UrlEncode(clientId)).Append("&response_type=").Append("code").Append("&scope=");
            StringBuilder scpBuilder = new StringBuilder();

            foreach (string str in scope)
            {
                scpBuilder.Append(str).Append(" ");
            }
            strBuilder.Append(HttpUtility.UrlEncode(scpBuilder.ToString()));
            strBuilder.Append("&redirect_uri=").Append(
                HttpUtility.UrlEncode(redirectURI));
            redirectURL = baseURL + "/v1/authorize?" + strBuilder.ToString();
            return(redirectURL);
        }
コード例 #60
0
        /* validate that this use is an Admin... here we dont check the token.
         * I think it is better to use the db because if the token is compromised, they still would have to have the id
         * of someone who is forsure an admin to get through this
         */
        public static bool ValidateIsAdmin(APIContext context, int id, string[] keyAndIV)
        {
            string callerRole = DecryptStringFromBytes_Aes(context.Users.Single(a => a.ID == id).Role, keyAndIV);

            return((callerRole == UserRoles.Admin) ? true : false);
        }