Ejemplo n.º 1
0
        /// <summary>
        /// Create the new card of the customer
        /// </summary>
        /// <param name="customerId">Customer ID</param>
        /// <param name="cardRequest">Request parameters to create card of the customer</param>
        /// <returns>Card</returns>
        public Card CreateCustomerCard(string customerId, CreateCustomerCardRequest cardRequest)
        {
            try
            {
                //create customer API
                var configuration = CreateApiConfiguration();
                var customersApi  = new CustomersApi(configuration);

                //create the new card of the customer
                var createCustomerCardResponse = customersApi.CreateCustomerCard(customerId, cardRequest);
                if (createCustomerCardResponse == null)
                {
                    throw new NopException("No service response");
                }

                //check whether there are errors in the service response
                if (createCustomerCardResponse.Errors?.Any() ?? false)
                {
                    var errorsMessage = string.Join(";", createCustomerCardResponse.Errors.Select(error => error.ToString()));
                    throw new NopException($"There are errors in the service response. {errorsMessage}");
                }

                return(createCustomerCardResponse.Card);
            }
            catch (Exception exception)
            {
                //log full error
                _logger.Error($"Square payment error: {exception.Message}.", exception, _workContext.CurrentCustomer);

                return(null);
            }
        }
Ejemplo n.º 2
0
        public override CreateCustomerCardResponse Execute <T>(T transaction)
        {
            base.Execute(transaction); //Needed to inject Authorization headers
            ITrnCreateCustomerCard data = (ITrnCreateCustomerCard)transaction;
            var request = new CreateCustomerCardRequest
            {
                BillingAddress = data.Address.ToNativeSquareAddress(),
                CardholderName = data.CardholderName,
                CardNonce      = data.CardNonce
            };
            var response = customersApi.CreateCustomerCard(data.CustomerId, request);

            return(response);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// CreateCustomerCard Adds a card on file to an existing customer.
        /// </summary>
        /// <exception cref="Square.Connect.Client.ApiException">Thrown when fails to make API call</exception>
        /// <param name="authorization">The value to provide in the Authorization header of your request. This value should follow the format &#x60;Bearer YOUR_ACCESS_TOKEN_HERE&#x60;.</param>
        /// <param name="customerId">The ID of the customer to link the card on file to.</param>
        /// <param name="body">An object containing the fields to POST for the request.  See the corresponding object definition for field details.</param>
        /// <returns>Task of ApiResponse (CreateCustomerCardResponse)</returns>
        public async System.Threading.Tasks.Task <ApiResponse <CreateCustomerCardResponse> > CreateCustomerCardAsyncWithHttpInfo(string authorization, string customerId, CreateCustomerCardRequest body)
        {
            // verify the required parameter 'authorization' is set
            if (authorization == null)
            {
                throw new ApiException(400, "Missing required parameter 'authorization' when calling CustomerCardApi->CreateCustomerCard");
            }
            // verify the required parameter 'customerId' is set
            if (customerId == null)
            {
                throw new ApiException(400, "Missing required parameter 'customerId' when calling CustomerCardApi->CreateCustomerCard");
            }
            // verify the required parameter 'body' is set
            if (body == null)
            {
                throw new ApiException(400, "Missing required parameter 'body' when calling CustomerCardApi->CreateCustomerCard");
            }

            var    localVarPath         = "/v2/customers/{customer_id}/cards";
            var    localVarPathParams   = new Dictionary <String, String>();
            var    localVarQueryParams  = new Dictionary <String, String>();
            var    localVarHeaderParams = new Dictionary <String, String>(Configuration.DefaultHeader);
            var    localVarFormParams   = new Dictionary <String, String>();
            var    localVarFileParams   = new Dictionary <String, FileParameter>();
            Object localVarPostBody     = null;

            // to determine the Content-Type header
            String[] localVarHttpContentTypes = new String[] {
                "application/json"
            };
            String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);

            // to determine the Accept header
            String[] localVarHttpHeaderAccepts = new String[] {
                "application/json"
            };
            String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);

            if (localVarHttpHeaderAccept != null)
            {
                localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
            }

            // set "format" to json by default
            // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
            localVarPathParams.Add("format", "json");
            if (customerId != null)
            {
                localVarPathParams.Add("customer_id", Configuration.ApiClient.ParameterToString(customerId));                     // path parameter
            }
            if (authorization != null)
            {
                localVarHeaderParams.Add("Authorization", Configuration.ApiClient.ParameterToString(authorization));                        // header parameter
            }
            if (body != null && body.GetType() != typeof(byte[]))
            {
                localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter
            }
            else
            {
                localVarPostBody = body; // byte array
            }


            // make the HTTP request
            IRestResponse localVarResponse = (IRestResponse)await Configuration.ApiClient.CallApiAsync(localVarPath,
                                                                                                       Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
                                                                                                       localVarPathParams, localVarHttpContentType);

            int localVarStatusCode = (int)localVarResponse.StatusCode;

            if (ExceptionFactory != null)
            {
                Exception exception = ExceptionFactory("CreateCustomerCard", localVarResponse);
                if (exception != null)
                {
                    throw exception;
                }
            }

            return(new ApiResponse <CreateCustomerCardResponse>(localVarStatusCode,
                                                                localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
                                                                (CreateCustomerCardResponse)Configuration.ApiClient.Deserialize(localVarResponse, typeof(CreateCustomerCardResponse))));
        }
Ejemplo n.º 4
0
        /// <summary>
        /// CreateCustomerCard Adds a card on file to an existing customer.
        /// </summary>
        /// <exception cref="Square.Connect.Client.ApiException">Thrown when fails to make API call</exception>
        /// <param name="authorization">The value to provide in the Authorization header of your request. This value should follow the format &#x60;Bearer YOUR_ACCESS_TOKEN_HERE&#x60;.</param>
        /// <param name="customerId">The ID of the customer to link the card on file to.</param>
        /// <param name="body">An object containing the fields to POST for the request.  See the corresponding object definition for field details.</param>
        /// <returns>Task of CreateCustomerCardResponse</returns>
        public async System.Threading.Tasks.Task <CreateCustomerCardResponse> CreateCustomerCardAsync(string authorization, string customerId, CreateCustomerCardRequest body)
        {
            ApiResponse <CreateCustomerCardResponse> localVarResponse = await CreateCustomerCardAsyncWithHttpInfo(authorization, customerId, body);

            return(localVarResponse.Data);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// CreateCustomerCard Adds a card on file to an existing customer.
        /// </summary>
        /// <exception cref="Square.Connect.Client.ApiException">Thrown when fails to make API call</exception>
        /// <param name="authorization">The value to provide in the Authorization header of your request. This value should follow the format &#x60;Bearer YOUR_ACCESS_TOKEN_HERE&#x60;.</param>
        /// <param name="customerId">The ID of the customer to link the card on file to.</param>
        /// <param name="body">An object containing the fields to POST for the request.  See the corresponding object definition for field details.</param>
        /// <returns>CreateCustomerCardResponse</returns>
        public CreateCustomerCardResponse CreateCustomerCard(string authorization, string customerId, CreateCustomerCardRequest body)
        {
            ApiResponse <CreateCustomerCardResponse> localVarResponse = CreateCustomerCardWithHttpInfo(authorization, customerId, body);

            return(localVarResponse.Data);
        }
Ejemplo n.º 6
0
        public async Task <PurchaseResponseModel> Purchase(PurchaseModel purchaseModel, User user)
        {
            var purchaseResponse = new PurchaseResponseModel
            {
                Success = false,
                Nanrs   = 0
            };

            try
            {
                if (purchaseModel.SaveBilling)
                {
                    CustomersApi customerApi = new CustomersApi(configuration);
                    if (string.IsNullOrWhiteSpace(user.BillingId))
                    {
                        CreateCustomerRequest createCustomer = new CreateCustomerRequest(Guid.NewGuid().ToString(), Nickname: user.Username, EmailAddress: user.Email, ReferenceId: user.Id.ToString());
                        var customerResponse = await customerApi.CreateCustomerAsync(createCustomer);

                        if (customerResponse.Errors != null && customerResponse.Errors.Any())
                        {
                            return(purchaseResponse);
                        }
                        user.BillingId = customerResponse.Customer.Id;
                    }
                    CreateCustomerCardRequest cardRequest = new CreateCustomerCardRequest(purchaseModel.Token);
                    var cardResponse = await customerApi.CreateCustomerCardAsync(user.BillingId, cardRequest);

                    if (cardResponse.Errors != null && cardResponse.Errors.Any())
                    {
                        return(purchaseResponse);
                    }
                    user.CardId = cardResponse.Card.Id;
                }
                (int price, int amount) = GetPricing(purchaseModel.Amount !);
                string idempotencyKey = Guid.NewGuid().ToString();
                Money  money          = new Money(price, "USD");
                CreatePaymentRequest body;
                if (purchaseModel.UseSaved || purchaseModel.SaveBilling)
                {
                    body = new CreatePaymentRequest(SourceId: user.CardId, CustomerId: user.BillingId, IdempotencyKey: idempotencyKey, AmountMoney: money, Note: $"{user.Id} {purchaseModel.Amount}");
                }
                else
                {
                    body = new CreatePaymentRequest(SourceId: purchaseModel.Token, IdempotencyKey: idempotencyKey, AmountMoney: money, Note: $"{user.Id} {purchaseModel.Amount}");
                }
                PaymentsApi paymentsApi = new PaymentsApi(configuration);
                var         response    = await paymentsApi.CreatePaymentAsync(body);

                if (response.Payment.Status == "COMPLETED")
                {
                    user.Balance   += amount;
                    user.Repurchase = purchaseModel.Refill;
                    if (user.Repurchase)
                    {
                        user.RepurchaseAmount = purchaseModel.Amount;
                    }
                    else
                    {
                        user.RepurchaseAmount = null;
                    }
                    var purchase = new Purchase
                    {
                        Id         = Guid.NewGuid(),
                        NanrAmount = amount,
                        UsdAmount  = price,
                        Timestamp  = DateTime.UtcNow
                    };
                    context.Purchases.Add(purchase);
                    await emailManager.SendPurchase(user, purchase);
                }
                else
                {
                    return(purchaseResponse);
                }
                await context.SaveChangesAsync();

                purchaseResponse.Success = true;
                purchaseResponse.Nanrs   = amount;
                return(purchaseResponse);
            } catch (Exception ex)
            {
                Console.WriteLine(ex);
                return(purchaseResponse);
            }
        }