Unable to get a Stripe Checkout session object - stripe-payments

Stripe.Net v34.16.0 bounces my code on the creation of the checkout session object responding with:
StripeException: No such plan: plan_myPlanId; a similar object exists in live mode, but a test mode key was used to make this request.
I do not see a means in the Stripe Dashboard to designate a given plan as a test plan .I also do not see
anything resembling a mode property.. my code
public async Task<IActionResult> Index()
{
//var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
//user = await _userManager.FindByIdAsync(userId);
StripeConfiguration.ApiKey = "sk_test_mytestkey";
var options = new Stripe.Checkout.SessionCreateOptions
{
PaymentMethodTypes = new List<string> {
"card",
},
SubscriptionData = new Stripe.Checkout.SessionSubscriptionDataOptions
{
Items = new List<SessionSubscriptionDataItemOptions> {
new SessionSubscriptionDataItemOptions {
Plan = "plan_myplanid",
},
},
},
//to do
SuccessUrl = "localhost://home",
CancelUrl = "localhost://home",
//CancelUrl = "https://example.com/cancel",
};
var service = new Stripe.Checkout.SessionService();
Stripe.Checkout.Session session = service.Create(options); //error out here
StripeCheckoutSessionId stripeCheckoutSessionId = new StripeCheckoutSessionId();
stripeCheckoutSessionId.StripeSessionID = session.Id;
return View(stripeCheckoutSessionId);
}
I am referring to Stripe sample code in the .Net tab here: https://stripe.com/docs/payments/checkout/subscriptions/starting
I appreciate your guidance in correcting my errors.

Related

Recording Bot using Skype.bot.media

We are creating a bot that can join the team meeting and it can start the recording as it joins the team meeting. But we are getting this error(Expected not null
Parameter name: client). I am attaching the code below:
when debugger goes to CreateLocalMediaSession() session method then at that method it gives the error.(Expected not null
Parameter name: client)
public async Task<ICall> JoinCallAsync()
{
// A tracking id for logging purposes. Helps identify this call in logs.
var scenarioId = Guid.NewGuid();
var (chatInfo, meetingInfo) = JoinInfo.ParseJoinURL("https://teams.microsoft.com/l/meetup-join/19:meeting_YTI5NDQ2ODQtMmNlNy00YTBhLTg2NTMtYmZmOGIyMzdhMTgw#thread.v2/0?context=%7B%22Tid%22:%22204d6395-ea6c-4e64-abea-e04cd30845e2%22,%22Oid%22:%225a95f69b-70e2-40d3-8b9a-5810ffcc6ec9%22%7D");
var tenantId = (meetingInfo as OrganizerMeetingInfo).Organizer.GetPrimaryIdentity().GetTenantId();
var mediaSession = this.CreateLocalMediaSession(scenarioId);
var joinParams = new JoinMeetingParameters(chatInfo, meetingInfo, mediaSession)
{
TenantId = tenantId,
};
if (!string.IsNullOrWhiteSpace("bot"))
{
// Teams client does not allow changing of one's display name.
// If the display name is specified, we join as an anonymous (guest) user
// with the specified display name. This will put the bot in lobby
// unless lobby bypass is disabled.
joinParams.GuestIdentity = new Identity
{
Id = Guid.NewGuid().ToString(),
DisplayName = "bot",
};
}
var statefulCall = await this.Client.Calls().AddAsync(joinParams, scenarioId).ConfigureAwait(false);
statefulCall.GraphLogger.Info($"Call creation complete: {statefulCall.Id}");
return statefulCall;
}
Code for creating local media session:
private ILocalMediaSession CreateLocalMediaSession(Guid mediaSessionId = default)
{
try
{
// create media session object, this is needed to establish call connections
return this.Client.CreateMediaSession(
new AudioSocketSettings
{
StreamDirections = StreamDirection.Recvonly,
// Note! Currently, the only audio format supported when receiving unmixed audio is Pcm16K
SupportedAudioFormat = AudioFormat.Pcm16K,
ReceiveUnmixedMeetingAudio = true //get the extra buffers for the speakers
},
new VideoSocketSettings
{
StreamDirections = StreamDirection.Inactive
},
mediaSessionId: mediaSessionId);
}
catch (Exception e)
{
_logger.Log(System.Diagnostics.TraceLevel.Error, e.Message);
throw;
}
}
We are creating a bot that can join the team meeting and it can start the recording as it joins the team meeting. But we are getting this error(Expected not null
Parameter name: client). I am attaching the code below:
error facing:
enter image description here

I'm receiving a Stripe exception "No such payout: 'po_1KJ6pFQ**********YsFVzT4'" when fetching balance transactions

I'd like to fetch all the Stripe Transfers that make up a Payout. I'm following this Stackoverflow post here that says fetch the balance transactions and pass in a payout ID and set the type to "transfer".
In my Stripe dashboard I can see multiple payouts and I'm just copying/pasting different ID's to test this call.
Problem - I keep getting the same error message from Stripe saying "No such payout: 'po_1KJ6pFQ**********YsFVzT4'"
Here's how I'm calling the balance transactions.
var options = new BalanceTransactionListOptions
{
Payout = "po_1KJ6pFQ**********YsFVzT4",
// Type = "transfer",
// Limit = 100,
};
var service = new BalanceTransactionService();
try {
StripeList<BalanceTransaction> balanceTransactions = service.List(options);
foreach(BalanceTransaction balTransaction in balanceTransactions) { // do something }
}
} catch(StripeException ex) {
var e = ex;
}
No such (object) error messages occurs when the object you're attempting to access does not exist on the Stripe account.
By default, the request would be made on the Stripe account whose API key you're using. If you're using Connect and you need to access an object on a connected account, you should use your platform's API key and the Stripe-Account header.
var requestOptions = new RequestOptions();
requestOptions.StripeAccount = "{{CONNECTED_ACCOUNT_ID}}";
var options = new BalanceTransactionListOptions
{
Payout = "po_1KJ6pFQ**********YsFVzT4",
// Type = "transfer",
// Limit = 100,
};
var service = new BalanceTransactionService();
try {
StripeList<BalanceTransaction> balanceTransactions = service.List(options, requestOptions);
foreach(BalanceTransaction balTransaction in balanceTransactions) { // do something }
}
} catch(StripeException ex) {
var e = ex;
}

Stripe expanding the Account object in BankAccountListOptions is not working while data.account is set

I'm using Stripe.Net to fetch a customer's bank accounts. However, the account object is null despite data.account is passed to the Expand property as follows.
var serviceb = new BankAccountService();
var opts = new BankAccountListOptions {
Expand = new List<string> {
"data.account"
}
};
var lst = await serviceb.ListAsync(customerId, opts);
var firstBankAccount = lst.First();
firstBankAccount.Account and firstBankAccount.AccountId are null, which I'm unable to figure out what's wrong.
Note: I've linked the customer's bank account through Plaid Link, stripe_bank_access_token, in Sandbox mode. Also, I'm using Stripe on test mode.
var options = new CustomerCreateOptions
{
Description = "User",
Source = Source, // a tok_* which provided by Plaid through `PLAID/processor/stripe/bank_account_token/create` API
Email = "a#a.com"
};
var service = new CustomerService();
await service.CreateAsync(options);
Here is the bank account and the customer that was created on Stripe using the above code.

Application breaks while View Redirect to Azure login

I have a mvc application , Which have a Home view , in the Home View I have Button to see the report , Which is loading two partial view one is get the ajax call and load the external api data from table ,another one partial view is for load powerbi.
while click the button, i have load different api and get the datas in 1 partial view and while loading the second partial view for PowerBi , which redirect to azure login and breaks the application.
public ActionResult Index(){
var #params = new NameValueCollection
{
{"response_type", "code"},
{"client_id", Properties.Settings.Default.ClientID},
{"resource", "https://analysis.windows.net/powerbi/api"},
{"redirect_uri", "http://localhost:13526/Redirect"}
};
var queryString = HttpUtility.ParseQueryString(string.Empty);
queryString.Add(#params);
string authorityUri = "https://login.windows.net/common/oauth2/authorize/";
var authUri = String.Format("{0}?{1}", authorityUri, queryString);
Response.Redirect(authUri);
}
After Authentication ,Azure issues the token and load the powerbi.
EmbedPowerBi
public async Task<ActionResult> EmbedPowerBi ()
{
AuthenticationResult authResult;
authResult = (AuthenticationResult)Session["authResult"];
var token = authResult.AccessToken;
ViewBag.Token = token;
var tokenCredentials = new TokenCredentials(token, "Bearer");
// Create a Power BI Client object. It will be used to call Power BI APIs.
using (var client = new PowerBIClient(new Uri(ApiUrl), tokenCredentials))
{
// Get a list of dashboards.
var dashboards = await client.Dashboards.GetDashboardsInGroupAsync(GroupId);
// Get the first report in the group.
var dashboard = dashboards.Value.FirstOrDefault();
//var dashboard = dashboards.Value.Where(w => w.Id == "DashboardId");
// Generate Embed Token.
var generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view");
var tokenResponse = await client.Dashboards.GenerateTokenInGroupAsync(GroupId, dashboard.Id, generateTokenRequestParameters);
if (tokenResponse == null)
{
return View(new EmbedConfig()
{
ErrorMessage = "Failed to generate embed token."
});
}
// Generate Embed Configuration.
var embedConfig = new EmbedConfig()
{
EmbedToken = tokenResponse,
EmbedUrl = dashboard.EmbedUrl,
Id = dashboard.Id
};
return View(embedConfig);
}
}
Problem I have faced beacuse of redirection other partial view gets affected the current application.
In the Home View i am loading partial view.
#Html.Partial("loadProduct");
#Html.Partial("_EmbedPowerBi");
Have you tried referring to the existing 'Developer Samples'?
https://github.com/Microsoft/PowerBI-Developer-Samples
https://github.com/Microsoft/PowerBI-Developer-Samples/blob/master/App%20Owns%20Data/PowerBIEmbedded_AppOwnsData/Controllers/HomeController.cs#L133
It seems the redirection problem is causing a ViewModel binding to you EmbedConfig

Getting the email from external providers Google and Facebook during account association step in a default MVC5 app

Apparently you can do this with the Facebook provider by adding scopes to the FacebookAuthenticationOptions object in Startup.Auth.cs:
http://blogs.msdn.com/b/webdev/archive/2013/10/16/get-more-information-from-social-providers-used-in-the-vs-2013-project-templates.aspx
List<string> scope = new List<string>() { "email" };
var x = new FacebookAuthenticationOptions();
x.Scope.Add("email");
...
app.UseFacebookAuthentication(x);
How to do the same with Google provider? There isn't a x.Scope property for the GoogleAuthenticationOptions class/object!
PLEASE SEE UPDATES AT THE BOTTOM OF THIS POST!
The following works for me for Facebook:
StartupAuth.cs:
var facebookAuthenticationOptions = new FacebookAuthenticationOptions()
{
AppId = "x",
AppSecret = "y"
};
facebookAuthenticationOptions.Scope.Add("email");
app.UseFacebookAuthentication(facebookAuthenticationOptions);
ExternalLoginCallback method:
var externalIdentity = HttpContext.GetOwinContext().Authentication.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie);
var emailClaim = externalIdentity.Result.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Email);
var email = emailClaim.Value;
And for Google:
StartupAuth.cs
app.UseGoogleAuthentication();
ExternalLoginCallback method (same as for facebook):
var externalIdentity = HttpContext.GetOwinContext().Authentication.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie);
var emailClaim = externalIdentity.Result.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Email);
var email = emailClaim.Value;
If I set a breakpoint here:
var email = emailClaim.Value;
I see the email address for both Facebook and Google in the debugger.
Update 1: The old answer had me confused so I updated it with the code I have in my own project that I just debugged and I know works.
Update 2: With the new ASP.NET Identity 2.0 RTM version you no longer need any of the code in this post. The proper way to get the email is by simply doing the following:
Startup.Auth.cs
app.UseFacebookAuthentication(
appId: "x",
appSecret: "y");
app.UseGoogleAuthentication();
AccountController.cs
//
// GET: /Account/ExternalLoginCallback
[AllowAnonymous]
public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
{
var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
if (loginInfo == null)
{
return RedirectToAction("Login");
}
// Sign in the user with this external login provider if the user already has a login
var result = await SignInHelper.ExternalSignIn(loginInfo, isPersistent: false);
switch (result)
{
case SignInStatus.Success:
return RedirectToLocal(returnUrl);
case SignInStatus.LockedOut:
return View("Lockout");
case SignInStatus.RequiresTwoFactorAuthentication:
return RedirectToAction("SendCode", new { ReturnUrl = returnUrl });
case SignInStatus.Failure:
default:
// If the user does not have an account, then prompt the user to create an account
ViewBag.ReturnUrl = returnUrl;
ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = loginInfo.Email });
}
}
You need to explicitly configure the FacebookAuthenticationOptions to get the email address from the authenticated user.
In your MVC5 project, add these lines in the Startup.Auth.cs
var options = new FacebookAuthenticationOptions() {
AppId = "xxxxxxxx",
AppSecret = "xxxxxxxxx"
};
options.Scope.Add("email");
app.UseFacebookAuthentication(options);
Update
Reduced my sample code to the absolute minimum. Your updated code works fine by the way, I have also tried it with both Facebook and Google.
In ASP.NET Core Facebook authentication the Facebook middleware seems to no longer pass in the email, even if you add it to the scope. You can work around it by using Facebook's Graph Api to request the email.
You can use any Facebook Graph Api client or roll your own, and use it to invoke the Graph api as follows:
app.UseFacebookAuthentication(options =>
{
options.AppId = Configuration["Authentication:Facebook:AppId"];
options.AppSecret = Configuration["Authentication:Facebook:AppSecret"];
options.Scope.Add("public_profile");
options.Scope.Add("email");
options.Events = new OAuthEvents
{
OnCreatingTicket = context => {
// Use the Facebook Graph Api to get the user's email address
// and add it to the email claim
var client = new FacebookClient(context.AccessToken);
dynamic info = client.Get("me", new { fields = "name,id,email" });
context.Identity.AddClaim(new Claim(ClaimTypes.Email, info.email));
return Task.FromResult(0);
}
};
});
You can find a more detailed example about how to use it here: http://zainrizvi.io/2016/03/24/create-site-with-facebook-login-using-asp.net-core/#getting-the-email-address-from-facebook

Resources