I am developing web application on ASP.NET. In application users can purchase article for money.
For work with PayPal I using PayPal Merchant SDK for .NET package. Application work good with sandbox but with live display error: "This transaction is invalid". Please return to the recipient's website to complete your transaction using their regular checkout flow."
When user click on purchase button I execute code:
// only for live
var paypalConfig = new Dictionary<string, string> {
{"account1.applicationId", "<APP-LIVEID>"},
{"account1.apiUsername", "<username>"},
{"account1.apiPassword", "<pass>"},
{"account1.apiSignature", "<signature>"},
{"mode", "live"}};
try
{
var currency = CurrencyCodeType.USD;
var paymentItem = new PaymentDetailsItemType
{
Name = "item",
Amount = new BasicAmountType(currency, amount.ToString()),
ItemCategory = ItemCategoryType.DIGITAL,
};
var paymentItems = new List<PaymentDetailsItemType>();
paymentItems.Add(paymentItem);
var paymentDetail = new PaymentDetailsType();
paymentDetail.PaymentDetailsItem = paymentItems;
paymentDetail.PaymentAction = PaymentActionCodeType.SALE;
paymentDetail.OrderTotal = new BasicAmountType(currency, amount.ToString());
paymentDetail.SellerDetails = new SellerDetailsType {
PayPalAccountID= sellerEmail
};
var paymentDetails = new List<PaymentDetailsType>();
paymentDetails.Add(paymentDetail);
var ecDetails = new SetExpressCheckoutRequestDetailsType {
ReturnURL = returnUrl,
CancelURL = cancelUrl,
PaymentDetails = paymentDetails,
};
var request = new SetExpressCheckoutRequestType
{
Version = "104.0",
SetExpressCheckoutRequestDetails = ecDetails,
};
var wrapper = new SetExpressCheckoutReq
{
SetExpressCheckoutRequest = request
};
var service = new PayPalAPIInterfaceServiceService(paypalConfig);
var setECResponse = service.SetExpressCheckout(wrapper);
if (sandbox)
return "https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token={0}".FormatWith(setECResponse.Token);
return "https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&TOKEN={0}".FormatWith(setECResponse.Token);
}
// # Exception log
catch (System.Exception ex)
{
// Log the exception message
Console.WriteLine("Error Message : " + ex.Message);
}
After all I redirect user to url with received TOKEN.
For my application, registered on PayPal, I set in options only "Adaptive Payments > Basic Payments > Checkout, Send Money or Parallel Payments"
Why live paypal payments can not work? What is the reason?
Removed
ItemCategory = ItemCategoryType.DIGITAL,
and all work
From previous experiences this problem usually comes from having a "null" token because of some mistake in the "setExpressCheckout" request (where, in the express checkout flow, you ask paypal for a transaction token).
Basically, you ask paypal for a token so you can build the redirect URL, but you make some mistake and paypal gives you an error but no token, so you build the URL with no token (or a wrong one).
If you try to redirect the user to the checkout URL ( https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token={...}&useraction={...}) with an empty token you will get this error.
Actually I'm trying to know of there can be other causes...
Related
I have to get the contacts from Exchange server from any account, so we have used the code from below link.
https://learn.microsoft.com/en-us/exchange/client-developer/exchange-web-services/how-to-authenticate-an-ews-application-by-using-oauth
But it is not working for personal accounts, which is working fine for our organization account. So I have used AadAuthorityAudience property instead of TenantId and changed the scope from EWS.AccessAsUser.All to others. Now authentication got success but getting "The given token is invalid" error while using the token in ExchangeService.
var pcaOptions = new PublicClientApplicationOptions {
ClientId = "77xxxxxxxxxxx92324",
//TenantId = "7887xxxxxxxxxxxxx14",
RedirectUri = "https://login.live.com/oauth20_desktop.srf",
AadAuthorityAudience = AadAuthorityAudience.AzureAdAndPersonalMicrosoftAccount};
var pca = PublicClientApplicationBuilder.CreateWithApplicationOptions(pcaOptions).Build();
//var ewsScopes = new string[] { "https://outlook.office365.com/EWS.AccessAsUser.All" };
var ewsScopes = new string[] { "User.Read", "Contacts.ReadWrite.Shared" };
var authResult = await pca.AcquireTokenInteractive(ewsScopes).ExecuteAsync();
var ewsClient = new ExchangeService();
ewsClient.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
//ewsClient.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, "araj#concord.net");
ewsClient.Credentials = new OAuthCredentials(authResult.AccessToken);
// Make an EWS call
var folders = ewsClient.FindFolders(WellKnownFolderName.MsgFolderRoot, new FolderView(10));
What am doing wrong here?
https://outlook.office365.com/EWS.AccessAsUser.All is the right scope to use. The scope is invalid for personal accounts since they're not supported by EWS.
I've been using Stripe. When checkout X will create a Payment Intent every time a customer arrives on the checkout. This will result into an "Incomplete" payment.
I integrete STRIPE in my .Net Core application. Here the code below :
public void Pay(CardInfo cardInfo, double amount)
{
StripeConfiguration.ApiKey = _paramList["secretKey"];
State = PaymentState.Pending;
try
{
var options = new SessionCreateOptions
{
Mode = "payment",
SuccessUrl = "https://example.com/success",
CancelUrl = "https://example.com/cancel",
Customer = cardInfo.Owner,
CustomerEmail = cardInfo.ParamList["email"],
PaymentMethodTypes = new List<string>
{
"card",
},
LineItems = new List<SessionLineItemOptions>
{
new SessionLineItemOptions
{
Amount = Convert.ToInt64(amount.ToString().Replace(",","")),
Currency = "eur",
Quantity = 1,
Name = _paramList["account"]
},
},
};
var service = new SessionService();
service.Create(options);
State = PaymentState.Accepted;
}
catch (StripeException error)
{
State = PaymentState.Error;
PaymentReturn = error.Message;
Logger.Write(string.Format("Error STRIPE payment status {0} : ",PaymentReturn));
}
}
In my form payment, I'm not using stripe form but I've created one and I retrieve all information that I need (Card Number, CVV, Expiration, Email and Amount)
When using Stripe Checkout, a PaymentIntent is created under the hood to support the SCA compliant payment. If the session is not completed, the PaymentIntent will remain in state incomplete. This. part is entirely normal.
Integrating with Stripe using a checkout session, but not redirecting to the Stripe hosted Checkout is not a supported integration. If you would like to support handling the card fields yourself, then an integration using Stripe.js and Elements is the best way forward [1]. If you would like to continue using Stripe Checkout as it offers so much functionality out of the box, then once the session is created, you should use redirectToCheckout() from Stripe.js [2] to send the user to Stripe Checkout.
[1] https://stripe.com/docs/payments/accept-a-payment?integration=elements
[2] https://stripe.com/docs/payments/accept-a-payment#redirect-customers
I want to customize nopCommerce eWayHosted plugin for other payment gateway(Easy Pay). I change the payment URL and the parameters.
public void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
{
var strPost = "storeId=" + _eWayHostedPaymentSettings.CustomerId;
strPost += Format("amount", postProcessPaymentRequest.Order.OrderTotal.ToString("0.00", CultureInfo.InvariantCulture));
strPost += Format("orderRefNum", postProcessPaymentRequest.Order.Id.ToString());
strPost += Format("postBackURL", "http://www.smmotors.org/onepagecheckout");
var url = _eWayHostedPaymentSettings.PaymentPage + "?" + strPost;
var objRequest = (HttpWebRequest)WebRequest.Create(url);
objRequest.Method = WebRequestMethods.Http.Get;
var objRequest1 = (HttpWebRequest)WebRequest.Create(url);
objRequest1.Method = WebRequestMethods.Http.Post;
var objResponse = (HttpWebResponse)objRequest.GetResponse();
At this point
The Easypay server sends back a parameter named auth_token to the postbackURL which is sent as a GET parameter.
But Var objResponse cannot get auth_token & postBackURL. Whats The Reason & solution
//get the response from the transaction generate page
string resultXml;
using (var sr = new StreamReader(objResponse.GetResponseStream()))
{
resultXml = sr.ReadToEnd();
// Close and clean up the StreamReader
sr.Close();
}
//parse the result message
var resultObj = ParseRequestResults(resultXml);
if (resultObj.Result)
{
//redirect the user to the payment page
HttpContext.Current.Response.Redirect(resultObj.Uri);
}
else
{
throw new NopException(resultObj.Error);
}
}
Below Is The Plug-in Integration Steps:
Following process will be followed by merchants to embed the Easypay Plug-in in their stores:
• Merchant acquires an account through Easypay agents. A Welcome email containing unique Store ID and URL is sent to the Merchant after successful registration.
• Merchant logins the Easy Pay portal and access ‘Guide to Integration’ menu where Merchant is presented with step by step instructions to integrate the Easypay plug- in to their shopping cart/online retail shop.
Following is the sample of flow merchant should find after logging into the Easypay portal.
Merchants having unique store ID embed Easypay plug-in on checkout page of their online stores/ websites. This will integrate “Pay through Easypay as a payment solution in their websites. The integration of Easypay plug-in is a simple two-step process:
The merchant needs to POST following parameter to the Easypay on the f o l l owi n g URL:
Production (Live) Environment:
https://easypay.easypaisa.com.pk/easypay/Index.jsf
Sandbox Environment:
https://easypaystg.easypaisa.com.pk/easypay/Index.jsf
• amount
• storeId
• postBackURL
• orderRefNum
After successful redirection the customer would land on the Easypay Checkout Screen where there is a form to be filled regarding the transaction information.
After completing the form in Step 1 the customer will be pressing the Proceed Button and lands back on the merchant website on the same URL given in postbackURL variable in the first step. This will be a confirmation screen on merchant’s website to perform a handshake between Easypay and merchant’s website. The Easypay sends back a parameter named auth_token to the postbackURL which is sent as a GET parameter. Now the merchant needs to post back following two parameters again to the following URL:
Production (Live) Environment:
https://easypay.easypaisa.com.pk/easypay/Confirm.jsf
Sandbox Environment:
https://easypaystg.easypaisa.com.pk/easypay/Confirm.jsf
• auth_token
• postBackURL
After this redirection the Easypay authenticates the auth_token sent by merchant with the one it has in the previous step, and upon successful authentication it will make customer land on the successful checkout screen sending back following two variables to the second postBackURL:
• status
• desc
• orderRefNumber
Sample Code Snippet for .NET
For the first redirection:
using (var client = new HttpClient())
{
var values = new List<KeyValuePair<string, string>>();
values.Add(new KeyValuePair<string, string>("storeId", "43"));
values.Add(new KeyValuePair<string, string>("amount", "10"));
values.Add(new KeyValuePair<string, string>("postBackURL", "http://www.my.onlinestore.com/transaction/MessageHandler"));
values.Add(new KeyValuePair<string, string>("orderRefNum", "1101"));
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("https://easypay.easypaisa.com.pk/easypay/Index.jsf", content); var responseString = await response.Content.ReadAsStringAsync();
}
For the second redirection:
using (var client = new HttpClient())
{
var values = new List<KeyValuePair<string, string>>();
values.Add(new KeyValuePair<string, string>("auth_token", Request.Querystring["auth_token"])); values.Add(new KeyValuePair<string, string>("postBackURL", "http://www.my.online-
store.com/transaction/MessageHandler1"));
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("https://easypay.easypaisa.com.pk/easypay/Confirm.jsf", content); var responseString = await response.Content.ReadAsStringAsync();
}
I have been trying to insert a Google calendar event via Google service account that was created for an app in my dev console, but I am continually getting a helpless 404 response back on the Execute method. In the overview of the dev console I can see that the app is getting requests because there are instances of errors on the calendar.events.insert method. There is no information on what is failing. I need this process to use the Service account process instead of OAuth2 so as to not require authentication each time a calendar event needs to be created.
I have set up the service account, given the app a name, have the p12 file referenced in the project. I've also, gone into a personal calendar and have shared with the service account email address. Also, beyond the scope of this ticket, I have created a secondary app, through an administration account and have granted domain wide access to the service account only to receive the same helpless 404 error that this is now giving.
Error Message: Google.Apis.Requests.RequestError
Not Found [404]
Errors [Message[Not Found] Location[ - ] Reason[notFound] Domain[global]
Any help identifying a disconnect or error would be greatly appreciated.
var URL = #"https://www.googleapis.com/calendar/v3/calendars/testcalendarID.com/events";
string serviceAccountEmail = "createdserviceaccountemailaq#developer.gserviceaccount.com";
var path = Path.Combine(HttpRuntime.AppDomainAppPath, "Files/myFile.p12");
var certificate = new X509Certificate2(path, "notasecret",
X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[] { Google.Apis.Calendar.v3.CalendarService.Scope.Calendar },
}.FromCertificate(certificate));
BaseClientService.Initializer initializer = new
BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Test App"
};
Google.Apis.Calendar.v3.CalendarService calservice = new Google.Apis.Calendar.v3.CalendarService(initializer);
string timezone = System.TimeZone.CurrentTimeZone.StandardName;
var calendarEvent = new Event()
{
Reminders = new Event.RemindersData()
{
UseDefault = true
},
Summary = title,
Description = description,
Location = location,
Start = new EventDateTime()
{
//DateTimeRaw = "2014-12-24T10:00:00.000-07:00",
DateTime = startDateTime,
TimeZone = "America/Phoenix"
},
End = new EventDateTime()
{
//DateTimeRaw = "2014-12-24T11:00:00.000-08:00",
DateTime = endDateTime,
TimeZone = "America/Phoenix"
},
Attendees = new List<EventAttendee>()
{
new EventAttendee()
{
DisplayName = "Joe Shmo",
Email = "joeshmoemail#email.com",
Organizer = false,
Resource = false
}
}
};
var insertevent = calservice.Events.Insert(calendarEvent, URL);
var requestedInsert = insertevent.Execute();
I had the same problem. The solution was to add an email client, whose calendar event you want to send.
Credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = Scopes,
User = "example_client_email#gmail.com"
}.FromCertificate(certificate));
So I found out that for this to work, You need to make sure that you access the google.Admin account for referencing the service account Client ID of the app you created.
Another thing that helps is making sure the timezone is in the following format "America/Phoenix"
I have now successfully created events through the service account WITHOUT authentication.
The Stripe is configured with mvc application. but need to send email receipt to customer after successful payment done. If not wrong this can do after webhook event gathered. but couldn't find exact code or api for email payment receipt in c#. any guidelines please.
Edited:
Sorry, I thought someone knew about stripe...
my code is
var myCustomer = new StripeCustomerCreateOptions();
// set these properties if it makes you happy
myCustomer.Email = "email#me.com";
myCustomer.Description = "test: email#me.com";
myCustomer.CardNumber = "4242424242424242";
myCustomer.CardExpirationYear = "2016";
myCustomer.CardExpirationMonth = "10";
myCustomer.CardName = "Red Swan";
myCustomer.CardCvc = "223";
myCustomer.PlanId = "testPremium";
myCustomer.Quantity = 1;
var customerService = new StripeCustomerService();
StripeCustomer stripeCustomer = customerService.Create(myCustomer);
var chargeService = new StripeChargeService();
var stripeCharge = chargeService.Create(myCharge);
This code creates the customer on Stripe as well as performs the payment aganist the plan id that provided... but for sending the mail (generated payment receipt by stripe) to this customer, I need guidelines for code.
I tried for code :
var myCharge = new StripeChargeCreateOptions
{
CustomerId = stripeCustomer.Id,
Currency = "gbp",
Amount=1000,
ReceiptEmail="customer#email.com"
};
var chargeService = new StripeChargeService();
var stripeCharge = chargeService.Create(myCharge);
but not working.