I try to add a new credit card to an existing customer but I get this error:
Received unknown parameter: card
I figure out how to verify if a card already exists using StripeTokenService to retrieve the card fingerprint, but I'm stuck trying to add that card to the customer.
My code look like this:
var sourceService = new Stripe.StripeSourceService();
// Get customer with current payment source.
var stripeCustomer = customerService.Get(stripeCustomerWithAccount.Id, new Stripe.StripeRequestOptions { ApiKey = ConfigurationManager.AppSettings["StripeSecretKey"] });
// Set Stripe Customer Id and Stripe Token options.
var tokenService = new Stripe.StripeTokenService();
var stripeToken = tokenService.Get(tokenId, new Stripe.StripeRequestOptions { ApiKey = ConfigurationManager.AppSettings["StripeSecretKey"] });
// Check if credit card already exists.
if (!CreditCardExists(stripeCustomer, stripeToken))
{
// Create new credit card.
var sourceOptions = new StripeNet.StripeSourceCreateOptions()
{
Customer = stripeCustomer.Id,
Card = new StripeNet.StripeCreditCardOptions
{
TokenId = stripeToken.StripeCard.Id
}
};
var source = sourceService.Create(sourceOptions, new Stripe.StripeRequestOptions { ApiKey = ConfigurationManager.AppSettings["StripeSecretKey"] });
}
Ok, I figured out how and I will share my answer:
if (!CreditCardExists(stripeCustomer, stripeToken))
{
var creditCardService = new StripeNet.StripeCardService();
var creditCardOptions = new StripeNet.StripeCardCreateOptions { SourceToken = tokenId };
var creditCard = creditCardService.Create(stripeCustomer.Id, creditCardOptions, new StripeNet.StripeRequestOptions { ApiKey = ConfigurationManager.AppSettings["StripeSecretKey"] });
// The only way I found to get customer with all sources...
stripeCustomer = customerService.Get(stripeCustomerWithAccount.Id, new StripeNet.StripeRequestOptions { ApiKey = ConfigurationManager.AppSettings["StripeSecretKey"] });
}
Related
I am using Google.Apis.AnalyticsReporting.v4 library for old google analytics views. How do I convert this code to GA4? I can't find a line about switching View Id to something else in code.
I have checked this post "How do I get view id in GA4", but my properties already exist and I don't see option to modify them after creation.
using (var svc = new AnalyticsReportingService(authInitializer.CreateInitializer()))
{
var dateRange = new DateRange
{
StartDate = analyticsParams.From.ToString("yyyy-MM-dd"),
EndDate = analyticsParams.To.ToString("yyyy-MM-dd")
};
var sessions = new Metric
{
Expression = "ga:sessions",
Alias = "Sessions"
};
var date = new Dimension { Name = "ga:date" };
var reportRequest = new ReportRequest
{
DateRanges = new List<DateRange> { dateRange },
Dimensions = new List<Dimension> { date },
Metrics = new List<Metric> { sessions },
ViewId = analyticsParams.ViewId, // <------------------------- My view id
};
var getReportsRequest = new GetReportsRequest
{
ReportRequests = new List<ReportRequest> { reportRequest }
};
var batchRequest = svc.Reports.BatchGet(getReportsRequest);
var response = batchRequest.Execute();
var reports = response.Reports.First();
return reports.Data.Rows.Select(x => new DataEntry()
{
Date = DateTime.ParseExact(x.Dimensions[0], "yyyyMMdd", CultureInfo.InvariantCulture),
Value = int.Parse(x.Metrics[0].Values[0]),
}).ToList();
}
You need to use the Google Analytics Data API V1 (currently in alpha) in order to access your GA4 properties. Here is a quick start sample for .NET which seems similar to what you are trying to do.
using Google.Analytics.Data.V1Alpha;
using System;
namespace AnalyticsSamples
{
class QuickStart
{
static void SampleRunReport(string propertyId)
{
// Using a default constructor instructs the client to use the credentials
// specified in GOOGLE_APPLICATION_CREDENTIALS environment variable.
AlphaAnalyticsDataClient client = AlphaAnalyticsDataClient.Create();
// Initialize request argument(s)
RunReportRequest request = new RunReportRequest
{
Entity = new Entity{ PropertyId = propertyId },
Dimensions = { new Dimension{ Name="city"}, },
Metrics = { new Metric{ Name="activeUsers"}, },
DateRanges = { new DateRange{ StartDate="2020-03-31", EndDate="today"}, },
};
// Make the request
RunReportResponse response = client.RunReport(request);
Console.WriteLine("Report result:");
foreach( Row row in response.Rows )
{
Console.WriteLine("{0}, {1}", row.DimensionValues[0].Value, row.MetricValues[0].Value);
}
}
static int Main(string[] args)
{
if (args.Length == 0 || args.Length > 2)
{
Console.WriteLine("Arguments: <GA4 property ID>");
Console.WriteLine("A GA4 property id parameter is required to make a query to the Google Analytics Data API.");
return 1;
}
string propertyId = args[0];
SampleRunReport(propertyId);
return 0;
}
}
}
Currently there aren't API available for GA4 Property. Furthermore GA4 does not provide Views, you have to use BigQuery to get data programmatically.
I'm trying to use Stripe on my web following this Stripe doc: https://stripe.com/docs/legacy-checkout/webforms but when i debug the code throws a TypeInitializationException on both create(), the customer and charge.
if (Request.Form["stripeToken"] != null)
{
var optionsCustomer = new CustomerCreateOptions
{
Email = Request.Form["stripeEmail"].ToString(),
Source = Request.Form["stripeToken"].ToString(),
};
var serviceCustomer = new CustomerService();
Customer customer = serviceCustomer.Create(optionsCustomer);
var optionsCharge = new ChargeCreateOptions
{
Amount = 1099,
Currency = "eur",
};
var serviceCharge = new ChargeService();
serviceCharge.Create(optionsCharge);
}
I'm following the example provided in the Stripe documentation on Previewing Proration using the Stripe.NET library to try to find the amount that will be charged when a customer upgrades from Plan A to Plan B.
However, when I use the code sample in the documentation, I get an error:
UpcomingInvoiceOptions options = new UpcomingInvoiceOptions()
{
CustomerId = "cus_XXXXXXXXXXXXX",
SubscriptionProrationDate = DateTime.UtcNow,
SubscriptionItems = new List<InvoiceSubscriptionItemOptions>()
{
new InvoiceSubscriptionItemOptions()
{
Id = "si_XXXXXXXXXXXXXX", // Current Sub Item
PlanId = "plan_XXXXXXXXXXXX" // New plan
}
}
};
InvoiceService service = new InvoiceService();
var result = service.Upcoming(options);
The last line throws a Stripe.StripeException: You cannot update a subscription item without a subscription.
Turns out options.SubscriptionId is a required field for this action if you don't call service.Get first.
The following code produces the correct results:
UpcomingInvoiceOptions options = new UpcomingInvoiceOptions()
{
CustomerId = "cus_XXXXXXXXXXXXX",
SubscriptionId = "sub_XXXXXXXXXXXX",
SubscriptionProrationDate = DateTime.UtcNow,
SubscriptionItems = new List<InvoiceSubscriptionItemOptions>()
{
new InvoiceSubscriptionItemOptions()
{
Id = "si_XXXXXXXXXXXXXX", // Current Sub Item
PlanId = "plan_XXXXXXXXXXXX" // New plan
}
}
};
InvoiceService service = new InvoiceService();
var result = service.Upcoming(options);
Is there any options for sending OTP while Credit/Debit card payment in authorize.net.
if there is no option how to achieve this
This is the code for getting response from the Authorized.Net
public static ANetApiResponse Run(CustomerDetail cd,decimal amount)
{
ApiOperationBase<ANetApiRequest, ANetApiResponse>.RunEnvironment = AuthorizeNet.Environment.SANDBOX;
ApiOperationBase<ANetApiRequest, ANetApiResponse>.MerchantAuthentication = new merchantAuthenticationType()
{
name = ConfigurationManager.AppSettings["AuthorizeNetLogin"],
ItemElementName = ItemChoiceType.transactionKey,
Item = ConfigurationManager.AppSettings["AuthorizeNetTransactionKey"],
};
var creditCard = new creditCardType
{
cardNumber = Convert.ToString(cd.cardnumber),
expirationDate = cd.expirationdate,
};
var paymentType = new paymentType { Item = creditCard };
var transactionRequest = new transactionRequestType
{
transactionType = transactionTypeEnum.authOnlyTransaction.ToString(), // authorize only
amount = amount,
payment = paymentType
};
var request = new createTransactionRequest { transactionRequest = transactionRequest };
var controller = new createTransactionController(request);
controller.Execute();
var response = controller.GetApiResponse();
return response;
}
Authorize.Net does not support One Time Password as Authorize.Net does not support money transfers.
For customer with existing payment profile id(Saved credit card) we are using "createCustomerProfileTransactionController" as follow for authorization.
public createCustomerProfileTransactionResponse AuthorizePaymentProfile(int customerProfileId, int customerPaymentProfileId, decimal amount)
{
createCustomerProfileTransactionResponse response = null;
ApiOperationBase<ANetApiRequest, ANetApiResponse>.RunEnvironment = environment;
// define the merchant information (authentication / transaction id)
ApiOperationBase<ANetApiRequest, ANetApiResponse>.MerchantAuthentication = new merchantAuthenticationType()
{
name = apiLoginID,
ItemElementName = ItemChoiceType.transactionKey,
Item = apiTransactionKey,
};
//construct request
var request = new createCustomerProfileTransactionRequest
{
merchantAuthentication = new merchantAuthenticationType
{
name = apiLoginID,
ItemElementName = ItemChoiceType.transactionKey,
Item = apiTransactionKey
},
transaction = new profileTransactionType
{
Item = new profileTransAuthOnlyType
{
customerProfileId = customerProfileId.ToString(),
customerPaymentProfileId = customerPaymentProfileId.ToString(),
amount = amount
}
},
extraOptions = "x_duplicate_window=1"
};
//Prepare Request
var controller = new createCustomerProfileTransactionController(request);
controller.Execute();
//Send Request to EndPoint
response = controller.GetApiResponse();
return response;
}
And for customer without existing payment profile id we using "createTransactionRequest" as follow for authorization.
public createTransactionResponse AuthorizeOneTimePayment(Card cardInfo, decimal amount)
{
createTransactionResponse response = null;
ApiOperationBase<ANetApiRequest, ANetApiResponse>.RunEnvironment = environment;
//define the merchant information (authentication / transaction id)
ApiOperationBase<ANetApiRequest, ANetApiResponse>.MerchantAuthentication = new merchantAuthenticationType()
{
name = apiLoginID,
ItemElementName = ItemChoiceType.transactionKey,
Item = apiTransactionKey,
};
var creditCard = new creditCardType
{
cardNumber = cardInfo.CardNumber,// "4111111111111111",
expirationDate = cardInfo.ExpirationDate// "0718"
//cardCode=cardInfo.VerificationCode
};
//standard api call to retrieve response
var paymentType = new paymentType { Item = creditCard };
string firstName = string.Empty;
string lastName = string.Empty;
if (!string.IsNullOrWhiteSpace(cardInfo.BillingName))
{
string[] name = GetBillName(cardInfo.BillingName);
firstName = name[0];
lastName = name[1];
}
var transactionRequest = new transactionRequestType
{
transactionType = transactionTypeEnum.authOnlyTransaction.ToString(), // authorize only
amount = amount,
payment = paymentType,
billTo = new customerAddressType
{
firstName = firstName,
lastName = lastName,
address = cardInfo.BillingAddress,
city = cardInfo.BillingCity,
state = cardInfo.BillingState,
zip = cardInfo.BillingZipCode
}
};
var request = new createTransactionRequest { transactionRequest = transactionRequest };
// instantiate the controller that will call the service
var controller = new createTransactionController(request);
controller.Execute();
// get the response from the service (errors contained if any)
response = controller.GetApiResponse();
return response;
}
And following same technique for capture and void a transaction.
My question is can we use "createTransactionRequest" for all transaction like authorize, capture and void a transaction for both customer having payment profile id and one time customer.
I could find any clue in authorize.net on line documentation. Please guide us how to do that.
Yes, you can use createTransactionRequest for Auth/Capture, Auth Only, Prior Auth and Capture, Void and Refund by changing the transactionRequestType and paymentType.
For anyone with the same question, like me, here is the answer.
Note that Order is optional, and obviously profile is optional.
...
var transactionRequest = new transactionRequestType {
transactionType = transactionTypeEnum.authOnlyTransaction.ToString(),
amount = amount,
order = new orderType { invoiceNumber = OrderID, description = desc },
profile = getCustomerPaymentProfile(CustomerProfileId, creditProfileID)
};
...
private customerProfilePaymentType getCustomerPaymentProfile(string CustomerProfileId, string creditProfileID) {
return new customerProfilePaymentType {
customerProfileId = CustomerProfileId,
paymentProfile = new paymentProfile { paymentProfileId = creditProfileID }
};
}