PayPal IPN returns INVALID on Sandbox with Google Script - paypal-ipn

This standalone Google Script web-service always returns INVALID from PayPal (resp = INVALID). The PayPal IPN simulator shows a message that the handshake was successful.
What am I missing?
function doPost(e) {
var isProduction = false;
//if(typeof e == 'undefined')
//return ContentService.createTextOutput(JSON.stringify(e.parameter));
var strSandbox = "https://www.sandbox.paypal.com/cgi-bin/webscr"
var strLive = "https://www.paypal.com/cgi-bin/webscr"
var paypalURL = strSandbox
if (isProduction) paypalURL = strLive;
var payload = "cmd=_notify-validate&" + e.postData.contents;
var options =
{
"method" : "post",
"payload" : payload
};
var resp = UrlFetchApp.fetch(paypalURL, options);
}

After getting everything to work, I'm offering here my working implementation skeleton:
function doPost(e) {
var isProduction = false;
//if(typeof e == 'undefined')
//return ContentService.createTextOutput(JSON.stringify(e.parameter));
var strSimulator = "https://www.sandbox.paypal.com/cgi-bin/webscr"
var strLive = "https://www.paypal.com/cgi-bin/webscr"
var paypalURL = strSimulator
if (isProduction) paypalURL = strLive;
var payload = "cmd=_notify-validate&" + e.postData.contents;
payload = payload.replace("+", "%2B");
var options =
{
"method" : "post",
"payload" : payload,
};
var resp = UrlFetchApp.fetch(paypalURL, options); //Handshake with PayPal - send acknowledgement and get VERIFIED or INVALID response
if (resp == 'VERIFIED') {
if (e.parameter.payment_status == 'Completed') {
if (e.parameter.receiver_email == 'receiver#email.com') {
//Convert to reference currency (USD) if paid in any other currency
var exchangeRate = 1;
if ((e.parameter.exchange_rate)) {
exchangeRate = parseFloat(e.parameter.exchange_rate);
}
var paidUSD = isPaymentValid(parseFloat(e.parameter.mc_gross), e.parameter.mc_currency, exchangeRate); //Convert paid amound to reference currency (USD)
if (paidUSD == 0.0) {
//My function returns 0.0 if product cost not found in my DB. I raise some notification here to check it out
return false;
}
if (paidUSD > 0.0) {
//All validated - can process the payment
var processSuccess = processDownloadRequest(e);
if (!(processSuccess)) {
//Process of payment failed - raise notification to check it out
}
} else {
//Payment does not equal expected purchase value
}
} else {
//Request did not originate from my PayPal account
}
} else {
//Payment status not Completed
}
} else
{
//PayPal response INVALID
}
}

Related

PayPal authentication problem on azure "live store"

I am getting the following error when trying to use paypal API
HttpStatusCode: Unauthorized; AUTHENTICATION_FAILURE; Authentication failed due to invalid authentication credentials or a missing Authorization header.
But problem is only when i publish my code to Azure Api. Live store works if I run it on visual studio.
public async Task<bool> InvoicingCreate(Models.ShopTransaction t)
{
sentJson = null;
if (_accessToken == null) await GetAccessTokenAsync();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "v2/invoicing/invoices");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _accessToken.access_token);
bool addNotes;
if (t.Product.TotalPrice == 0.0) addNotes = false;
else if (t.PaymentMethod == null) addNotes = true;
else if (t.PaymentMethod == "paypal" || t.PaymentMethod == "credit_card") addNotes = false;
else addNotes = true;
string billingEmail;
if (t.Product.IndividualCouponId.HasValue)
{
billingEmail = _configuration["Shop:CouponInvoiceEmail"];
}
else
{
billingEmail = t.BillingAddress.Email;
}
var inv = new Root
{
detail = new Detail
{
.......details the items. ...
},
.......Fill the items. ...
sentJson = JsonConvert.SerializeObject(inv, Formatting.None, new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore });
request.Content = new StringContent(JsonConvert.SerializeObject(inv), Encoding.UTF8, "application/json");
HttpResponseMessage response = await _httpClient.SendAsync(request);
string content = await response.Content.ReadAsStringAsync();
if (response.StatusCode != System.Net.HttpStatusCode.Created)
{
Error error = JsonConvert.DeserializeObject<Error>(content);
throw new Exception(CompactError("Invoicing-create", response.StatusCode, error));
}
CreateResponse invoiceCreated = JsonConvert.DeserializeObject<CreateResponse>(content);
t.InvoiceId = invoiceCreated.href.Split('/').Last();
return true;
}
Auth methode
appsettings.json paypalmodel
Invoicing methode
I found the problem.
It's an domain issue. It has send to many request on paypal server. So classic denial of service.

opcua session was closed by client

I have written the attached OpcUaConnector class for opc-ua connection related activities.
But it is not handling session. For example:
In opc ua configuration disabled the endpoint
In kepserver configuration did runtime > reinitializing
The windows service is throwing:
Source : system.Reactive.Core
InnerException : The session was closed by client
and stopping the windows service, as this error goes unhandled.
Can some one suggest how to handle session in opc-ua?
public class OpcUaConnector
{
private static SimplerAES simplerAES = new SimplerAES();
private DataContainer dataCointainer = null;
private UaTcpSessionChannel channel;
private string opcServerName = string.Empty;
private string opcUserId = string.Empty;
private string opcPassword = string.Empty;
private static ILog LogOpcStore;
private static System.IDisposable token;
private static uint id;
public OpcConnector(ILog Log)
{
IntializeLogOpcStore(Log);
}
private static void IntializeLogOpcStore(ILog Log)
{
LogOpcStore = Log;
}
public async Task OpenOpcConnection()
{
try
{
if ((!string.IsNullOrEmpty(this.opcServerName) & (this.opcServerName != AppMain.MyAppSettings.OpcServer)) ||
(!string.IsNullOrEmpty(this.opcUserId) & (this.opcUserId != AppMain.MyAppSettings.OpcUserId)) ||
(!string.IsNullOrEmpty(this.opcPassword) & (this.opcPassword != AppMain.MyAppSettings.OpcPassword)))
{
await channel.CloseAsync();
this.opcServerName = AppMain.MyAppSettings.OpcServer;
this.opcUserId = AppMain.MyAppSettings.OpcUserId;
this.opcPassword = AppMain.MyAppSettings.OpcPassword;
}
if (channel==null || (channel != null && (channel.State == CommunicationState.Closed || channel.State == CommunicationState.Faulted)))
{
var appDescription = new ApplicationDescription()
{
ApplicationName = "MyAppName",
ApplicationUri = $"urn:{System.Net.Dns.GetHostName()}:MyAppName",
ApplicationType = ApplicationType.Client,
};
//application data won't be deleted when uninstall
var certificateStore = new DirectoryStore(
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), MyAppName", "pki"),
true, true
);
//if the Ethernet cable unplugs or the Wifi drops out,
//you have some timeouts that can keep the session open for a while.
//There is a SessionTimeout (default of 2 min).
this.channel = new UaTcpSessionChannel(
appDescription,
certificateStore,
SignInOpc,
AppMain.MyAppSettings.OpcServer,
null,
options: new UaTcpSessionChannelOptions { SessionTimeout = 120000 });
await channel.OpenAsync();
//LogOpcStore.Info(String.Format("Opc connection sucessful"));
}
this.opcServerName = AppMain.MyAppSettings.OpcServer;
this.opcUserId = AppMain.MyAppSettings.OpcUserId;
this.opcPassword = AppMain.MyAppSettings.OpcPassword;
}
catch (Exception ex)
{
ServiceException serviceException = new ServiceException(ex.HResult + " " + ex.Message, "C052");
throw serviceException;
}
}
private static async Task RecursivelyFindNode(UaTcpSessionChannel channel, NodeId nodeid)
{
BrowseRequest browseRequest = new BrowseRequest
{
NodesToBrowse = new BrowseDescription[] { new BrowseDescription { NodeId = nodeid, BrowseDirection = BrowseDirection.Forward, ReferenceTypeId = NodeId.Parse(ReferenceTypeIds.HierarchicalReferences), NodeClassMask = (uint)NodeClass.Variable | (uint)NodeClass.Object, IncludeSubtypes = true, ResultMask = (uint)BrowseResultMask.All } },
};
BrowseResponse browseResponse = await channel.BrowseAsync(browseRequest);
foreach (var rd1 in browseResponse.Results[0].References ?? new ReferenceDescription[0])
{
uint chid = AppMain.MyTagDatabase.GetClientHandleByTag(rd1.DisplayName.ToString());
if (chid > 0)
{
AppMain.MyTagDatabase.UpdateNodeByClientHandle(chid, rd1.NodeId.ToString());
}
await RecursivelyFindNode(channel, ExpandedNodeId.ToNodeId(rd1.NodeId, channel.NamespaceUris));
}
}
public async Task CreateSubscription(DataContainer dc)
{
double curReadingValue;
try
{
dataCointainer = dc;
await RecursivelyFindNode(channel, NodeId.Parse(ObjectIds.RootFolder));
if (AppMain.MyTagDatabase.GetCntTagsNotInOpcServer() == AppMain.MyTagDatabase.GetTagCount())
{
//no need to create subscription
return;
}
//subscription timeout that is the product of PublishingInterval * LifetimeCount:
var subscriptionRequest = new CreateSubscriptionRequest
{
RequestedPublishingInterval = 1000f,
RequestedMaxKeepAliveCount = 30,
RequestedLifetimeCount = 30 * 3,
PublishingEnabled = true,
};
var subscriptionResponse = await channel.CreateSubscriptionAsync(subscriptionRequest);
id = subscriptionResponse.SubscriptionId;
var itemsToCreate = new MonitoredItemCreateRequest[AppMain.MyTagDatabase.GetTagHavingNodeCount()];
int i = 0;
foreach (var item in AppMain.MyTagDatabase.GetMyTagDatabase())
{
var itemKey = item.Key;
var itemValue = item.Value;
itemsToCreate[i] = new MonitoredItemCreateRequest { ItemToMonitor = new ReadValueId { NodeId = NodeId.Parse(itemValue.NodeId), AttributeId = AttributeIds.Value }, MonitoringMode = MonitoringMode.Reporting, RequestedParameters = new MonitoringParameters { ClientHandle = itemKey, SamplingInterval = -1, QueueSize = 0, DiscardOldest = true } };
i++;
}
var itemsRequest = new CreateMonitoredItemsRequest
{
SubscriptionId = id,
ItemsToCreate = itemsToCreate,
};
var itemsResponse = await channel.CreateMonitoredItemsAsync(itemsRequest);
token = channel.Where(pr => pr.SubscriptionId == id).Subscribe(pr =>
{
// loop thru all the data change notifications
// receiving data change notifications here
var dcns = pr.NotificationMessage.NotificationData.OfType<DataChangeNotification>();
foreach (var dcn in dcns)
{
foreach (var min in dcn.MonitoredItems)
{
MyTag MyTag = new MyTag();
bool hasValue = AppMain.MyTagDatabase.GetMyTag(min.ClientHandle, out MyTag);
if (hasValue)
{
if (double.TryParse(min.Value.Value.ToString(), out curReadingValue))
{
//LogOpcStore.Info(String.Format("ClientHandle : {0} TagName : {1} SourceTimestamp : {2} ServerTimeStamp : {3} curReadingValue : {4}", min.ClientHandle, MyTag.TagName, min.Value.SourceTimestamp, min.Value.ServerTimestamp, curReadingValue));
AddDataPointToContainer(1, MyTag.TagName, min.Value.SourceTimestamp, curReadingValue);
}
}
}
}
});
}
catch (Exception ex)
{
//If the interruption lasts longer than these timeouts then the SessionChannel and Subscriptions will need to be recreated.
channel = null;
FatalServiceException fatalserviceException = new FatalServiceException(ex.Message, "C052");
throw fatalserviceException;
}
}
public async Task DeleteSubscription()
{
try
{
var request = new DeleteSubscriptionsRequest
{
SubscriptionIds = new uint[] { id }
};
await channel.DeleteSubscriptionsAsync(request);
token.Dispose();
}
catch (Exception ex)
{
ServiceException serviceException = new ServiceException(ex.Message, "C052");
throw serviceException;
}
}
private static async Task<IUserIdentity> SignInOpc(EndpointDescription endpoint)
{
IUserIdentity userIdentity = null;
if (endpoint.UserIdentityTokens.Any(p => p.TokenType == UserTokenType.Anonymous))
{
userIdentity = new AnonymousIdentity();
}
else if (endpoint.UserIdentityTokens.Any(p => p.TokenType == UserTokenType.UserName))
{
var userName = AppMain.MyAppSettings.OpcUserId;
var password = simplerAES.Decrypt(AppMain.MyAppSettings.OpcPassword);
userIdentity = new UserNameIdentity(userName, password);
}
return userIdentity;
}
private void AddDataPointToContainer(int dataType, string source, DateTime SourceTimestampUTC, double value)
{
ConditionValue conditionValue = new ConditionValue();
long timestamp = AppMain.ServerSyncTimeStore.ConvertDateTimeToTimeStampUTC(SourceTimestampUTC);
conditionValue.dataType = dataType;
conditionValue.source = source;
conditionValue.timestamp = timestamp;
conditionValue.SourceTimestampUTC = SourceTimestampUTC;
conditionValue.LocalTime = SourceTimestampUTC.ToLocalTime();
conditionValue.value = value;
//LogOpcStore.Info(String.Format("TagName : {0} SourceTimestampUTC : {1} timestamp : {2} LocalTime : {3} curReadingValue : {4}", source, SourceTimestampUTC, timestamp, SourceTimestampUTC.ToLocalTime(), value));
dataCointainer.AddDataPoint(conditionValue);
}
}
I see you are using the project https://github.com/convertersystems/opc-ua-client.
When a server closes the session and socket (as happens when you reinitialize Kepware) the client receives immediate notification that causes the client channel to fault. A faulted channel cannot be reopened, it should be aborted and a new channel should be created.
I made this standalone test, to show that you may have to catch an exception and recreate the channel and subscription. The point of this test is to subscribe to the CurrentTime node and collect 60 datachanges. The test should last a minute. If you re-init the Kepware server in the middle of the test, the code catches the exception and recreates the channel and subscription.
[TestMethod]
public async Task OpcConnectorTest()
{
var count = 0;
UaTcpSessionChannel channel = null;
while (count < 60)
{
try
{
channel = new UaTcpSessionChannel(
this.localDescription,
this.certificateStore,
new AnonymousIdentity(),
EndpointUrl,
SecurityPolicyUris.None,
loggerFactory: this.loggerFactory);
await channel.OpenAsync();
// create the keep alive subscription.
var subscriptionRequest = new CreateSubscriptionRequest
{
RequestedPublishingInterval = 1000f,
RequestedMaxKeepAliveCount = 30,
RequestedLifetimeCount = 30 * 3,
PublishingEnabled = true,
};
var subscriptionResponse = await channel.CreateSubscriptionAsync(subscriptionRequest).ConfigureAwait(false);
var id = subscriptionResponse.SubscriptionId;
var token = channel.Where(pr => pr.SubscriptionId == id).Subscribe(pr =>
{
// loop thru all the data change notifications
var dcns = pr.NotificationMessage.NotificationData.OfType<DataChangeNotification>();
foreach (var dcn in dcns)
{
foreach (var min in dcn.MonitoredItems)
{
Console.WriteLine($"sub: {pr.SubscriptionId}; handle: {min.ClientHandle}; value: {min.Value}");
count++;
}
}
});
var itemsRequest = new CreateMonitoredItemsRequest
{
SubscriptionId = id,
ItemsToCreate = new MonitoredItemCreateRequest[]
{
new MonitoredItemCreateRequest { ItemToMonitor = new ReadValueId { NodeId = NodeId.Parse("i=2258"), AttributeId = AttributeIds.Value }, MonitoringMode = MonitoringMode.Reporting, RequestedParameters = new MonitoringParameters { ClientHandle = 12345, SamplingInterval = -1, QueueSize = 0, DiscardOldest = true } }
},
};
var itemsResponse = await channel.CreateMonitoredItemsAsync(itemsRequest);
while (channel.State == CommunicationState.Opened && count < 60)
{
await Task.Delay(1000);
}
}
catch (Exception ex)
{
Console.WriteLine($"Exception: {ex.GetType()}. {ex.Message}");
}
}
if (channel != null)
{
Console.WriteLine($"Closing session '{channel.SessionId}'.");
await channel.CloseAsync();
}
}
I know this is an old post, but I stumbled upon this problem as well. For those interested:
The problem is related to the subscription(s).
When the following code is run:
token = channel.Where(pr => pr.SubscriptionId == id).Subscribe(pr =>
{
// loop thru all the data change notifications
// receiving data change notifications here
var dcns = pr.NotificationMessage.NotificationData.OfType<DataChangeNotification>();
foreach (var dcn in dcns)
{
foreach (var min in dcn.MonitoredItems)
{
MyTag MyTag = new MyTag();
bool hasValue = AppMain.MyTagDatabase.GetMyTag(min.ClientHandle, out MyTag);
if (hasValue)
{
if (double.TryParse(min.Value.Value.ToString(), out curReadingValue))
{
//LogOpcStore.Info(String.Format("ClientHandle : {0} TagName : {1} SourceTimestamp : {2} ServerTimeStamp : {3} curReadingValue : {4}", min.ClientHandle, MyTag.TagName, min.Value.SourceTimestamp, min.Value.ServerTimestamp, curReadingValue));
AddDataPointToContainer(1, MyTag.TagName, min.Value.SourceTimestamp, curReadingValue);
}
}
}
}
});
Observable.subscribe() takes multiple arguments. You should include what to do in case of an error. For example:
token = channel.Where(pr => pr.SubscriptionId == id).Subscribe(
pr => { code to run normally... },
ex => { Log.Info(ex.Message); },
() => { }
);
See http://reactivex.io/documentation/operators/subscribe.html for more information.

how to collect data from user with the facebook messenger bot api in node js

I am building a messenger bot in node. I want it to collect user input data and have a conversation or ask questions, but the code I have doesn't work. the part that does not work is it only continues to the next else if block if i type the same code. and second the array is not capturing the text after the first if statement. Is there a better way to do it? Could someone provide code?
My code is below. what i want is like in this iimage:
var currentbot = 0;
var awnswers = [];
app.post('/webhook', function(req, res) {
var events = req.body.entry[0].messaging;
for (i = 0; i < events.length; i++) {
var event = events[i];
if (event.message && event.message.text) {
var text = event.message.text;
if (text == "hi") {
start(event.message.text, event.sender.id);
}
}
}
res.sendStatus(200);
});
var awnswers = [];
function start(text, id) {
if (count == 0) {
sendTextMessage('hello lets order!', id);
arr.push(text);
console.log(awnswers);
count = 1;
} else if (count == 1) {
sendTextMessage('what size do you want?', id);
arr.push(text);
console.log(awnswers);
count = 2;
} else if (count == 2) {
sendTextMessage('its on its way!', id);
arr.push(text);
console.log(awnswers);
count = 0;
}
}
function sendTextMessage(messageText, recipientId) {
var messageData = {
recipient: {
id: recipientId
},
message: {
text: messageText
}
};
callSendAPI(messageData);
}
function callSendAPI(messageData) {
request({
uri: 'https://graph.facebook.com/v2.6/me/messages',
qs: {
access_token: process.env.access_token
},
method: 'POST',
json: messageData
}, function(error, response, body) {
if (!error && response.statusCode == 200) {
var recipientId = body.recipient_id;
var messageId = body.message_id;
console.log("Successfully sent generic message with id %s to recipient %s", messageId, recipientId);
} else {
console.error("Unable to send message.");
console.error(response);
console.error(error);
}
});
}
The main issues I think I see are:
Start() is only called when text == hi
Count is not defined
You're pushing to the array 'arr' not, awnswers
You can fix these by:
Calling start() on every message
Defining count like var count = 0; at the top of your file, next to var currentbot
awnswers.push(text);

ConfirmEmailAsync() method is not working

I am having issue in confirming new user email. the Confirm email link works for first 20 minutes , but after 50 minutes the link expires. I have set the token expiration time to 24 hours. Please help me in resolving this issue. I am stuck on it for last 2 days:(.My code is as follows:
I am setting the token lifetime in Create() method in ApplicationUserManager as following:
var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
userManager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"))
{
TokenLifespan = _settings.ConfirmationAndResetTokenExpirationTimeSpan
};
}
And then In AccountsController, the Create method for new user is geiven below. The SendEmailAsync method consist of email subject, email body, generated password and the callback uri.
[Authorize(Roles = Roles.Bam.Name.Admin)]
[HttpPost]
[Route(Routes.Accounts.Template.Create, Name = Routes.Accounts.Name.Create)]
public async Task<IHttpActionResult> Create(CreateUserBindingModel createUserBindingModel)
{
IHttpActionResult result;
var memberNameExists = UserManager.Users.Any(x => x.MemberName.ToLower() == createUserBindingModel.MemberName.ToLower());
if (!memberNameExists)
{
var applicationUser = new ApplicationUser
{
UserName = createUserBindingModel.Email,
Email = createUserBindingModel.Email,
FirstName = createUserBindingModel.FirstName,
LastName = createUserBindingModel.LastName,
Company = createUserBindingModel.Company,
Location = createUserBindingModel.Location,
PhoneNumber = createUserBindingModel.PhoneNumber,
MemberName = createUserBindingModel.MemberName,
LastLoginDate = SqlDateTime.MinValue.Value,
CreateDate = DateTime.Now,
CreatedBy = User.Identity.GetUserId(),
UpdateDate = DateTime.Now,
UpdatedBy = User.Identity.GetUserId(),
TwoFactorEnabled = createUserBindingModel.TwoFactorEnabled,
SecurityResetRequired = true,
PasswordExpirationDate = DateTime.Now.AddDays(Convert.ToDouble(ConfigurationManager.AppSettings["PasswordExpirationDays"]))
};
if (!string.IsNullOrEmpty(createUserBindingModel.AvatarBase64))
{
var avatarBytes = Convert.FromBase64String(createUserBindingModel.AvatarBase64);
var resizedAvatarBytes = ImageResizer.ResizeImage(avatarBytes, _avatarWidth, _avatarHeight);
applicationUser.UserAvatar = new ApplicationUserAvatar
{
Avatar = resizedAvatarBytes
};
}
var generatedPassword = PasswordGenerator.GenerateStrongPassword(10, 10);
var identityResult = await UserManager.CreateAsync(applicationUser, generatedPassword);
if (identityResult.Succeeded)
{
await UserManager.AddToRolesAsync(applicationUser.Id, createUserBindingModel.Roles.ToArray());
var token = await UserManager.GenerateEmailConfirmationTokenAsync(applicationUser.Id);
var callbackUri = string.Format("{0}?userId={1}&token={2}", createUserBindingModel.EmailConfirmationCallbackUri, applicationUser.Id, HttpUtility.UrlEncode(token));
await UserManager.SendEmailAsync(applicationUser.Id, Email.Confirmation.Subject, string.Format(Email.Confirmation.Body, string.Format("{0} {1}", applicationUser.FirstName, applicationUser.LastName), callbackUri, generatedPassword, _settings.AccessTokenExpirationTimeSpan.TotalHours));
var userUrl = new Uri(Url.Link(Routes.Accounts.Name.Get, new { id = applicationUser.Id }));
var roles = await UserManager.GetRolesAsync(applicationUser.Id);
var contract = _accountsMapper.ToContract(applicationUser, roles);
result = Created(userUrl, contract);
}
else
{
result = GetErrorResult(identityResult);
}
}
else
{
ModelState.AddModelError(string.Empty, "Member Name already exists!");
result = BadRequest(ModelState);
}
return result;
}
Once the email is generated the UI has following JS angular code which gets executed and the provide the userid and token to service.
Angular JS code:
angular.module('confirmEmailModule').factory('confirmEmailFactory', function ($http) {
var factory = {};
factory.confirmEmail = function(userId, token) {
var encodedToken = encodeURIComponent(token);
var uri = '/identity/api/accounts/confirmemail?userId=' + userId + '&token=' + token;
return $http.post(uri);
}
return factory;
});
and the Service is :
[AllowAnonymous]
[HttpPost]
[Route(Routes.Accounts.Template.ConfirmEmail, Name = Routes.Accounts.Name.ConfirmEmail)]
public async Task<IHttpActionResult> ConfirmEmail([FromUri] string userId, [FromUri] string token)
{
//var decodedToken = HttpUtility.UrlDecode(token);
var identityResult = await UserManager.ConfirmEmailAsync(userId, token);
var result = identityResult.Succeeded ? StatusCode(HttpStatusCode.NoContent) : GetErrorResult(identityResult);
return result;
}
Please advice.
I found the solution to this issue. I am posting it if somebody faced the same issue. In my case the services and web API were on different servers. Different machine keys caused this issue. So I generated the machine key for my Web application and posted the same machine key in web.config file of Identity service. After that it worked. For more information on generating machine key, following link is helpful.
http://gunaatita.com/Blog/How-to-Generate-Machine-Key-using-IIS/1058
This is what worked for me. Hope it helps out;
public async Task<IActionResult> ConfirmEmail(string userId, string token)
{
if (userId == null || token == null)
{
return RedirectToAction("employees", "home");
}
var user = await userManager.FindByIdAsync(userId);
if (user == null)
{
ViewBag.ErrorMessage = $"The User ID {userId} is invalid";
return View("NotFound");
}
var result = await userManager.ConfirmEmailAsync(user, Uri.EscapeDataString(token));
if (result != null)
{
user.EmailConfirmed = true;
await userManager.UpdateAsync(user);
return View();
}
}

jQuery/Ajax form success message

I have a couple of forms on a site I'm working on and the script that controls them doesn't include a success message, so when they're submitted the input data just disappears and the user doesn't know if it's been actually sent or not. I've looked around a bit for answers, but because this file controls an email submission form, a contact form, and a twitter feed, it's a bit much for me to see what's what.
Here's the code, I'd just like to let users know that their message has been sent for both the email input form and the contact form. I appreciate any help that's out there!
$(document).ready(function() {
//Set default hint if nothing is entered
setHints();
//Bind JavaScript event on SignUp Button
$('#signUp').click(function(){
signUp($('#subscribe').val());
});
//Bind JavaScript event on Send Message Button
$('#sendMessage').click(function(){
if(validateInput()){
sendMail();
}else
{
alert('Please fill all fields to send us message.');
}
});
//Load initial site state (countdown, twitts)
initialize();
});
var setHints = function()
{
$('#subscribe').attachHint('Enter your email to be notified when more info is available');
$('[name=contact_name]').attachHint('Name');
$('[name=contact_email]').attachHint('Email');
$('[name=contact_subject]').attachHint('Subject');
$('[name=contact_message]').attachHint('Message');
};
var signUp = function(inputEmail)
{
var isValid = true;
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if(!emailReg.test(inputEmail)){
isValid = false;
alert('Your email is not in valid format');
}
if(isValid){
var params = {
'action' : 'SingUp',
'email' : inputEmail
};
$.ajax({
type: "POST",
url: "php/mainHandler.php",
data: params,
success: function(response){
if(response){
var responseObj = jQuery.parseJSON(response);
if(responseObj.ResponseData)
{
$('#subscribe').val('');
}
}
}
});
}
};
var initialize = function()
{
var params = {
'action' : 'Initialize'
};
$.ajax({
type: "POST",
url: "php/mainHandler.php",
data: params,
success: function(response){
if(response){
var responseObj = jQuery.parseJSON(response);
if(responseObj.ResponseData)
{
$('ul.twitts').empty();
if(responseObj.ResponseData.Twitts){
$('a.followUsURL').attr('href','http://twitter.com/#!/'+responseObj.ResponseData.Twitts[0].Name);
$.each(responseObj.ResponseData.Twitts, function(index, twitt){
var twitterTemplate = '<li>'
+ '#{0}'
+ '{2}'
+ '<span class="time">{3}</span>'
+ '</li>';
$('ul.twitts').append(StringFormat(twitterTemplate, twitt.Name, twitt.StatusID, twitt.Text, twitt.Date));
});
}
if(responseObj.ResponseData.Start_Date)
{
setInterval(function(){
var countDownObj = calculateTimeDifference(responseObj.ResponseData.Start_Date);
if(countDownObj){
$('#days').text(countDownObj.Days);
$('#hours').text(countDownObj.Hours);
$('#minutes').text(countDownObj.Minutes);
$('#seconds').text(countDownObj.Seconds);
}
}, 1000);
}
}
}
}
});
};
var validateInput = function(){
var isValid = true;
$('input, textarea').each(function(){
if($(this).hasClass('required'))
{
if($(this).val()!=''){
if($(this).hasClass('email'))
{
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if(!emailReg.test($(this).val())){
isValid = false;
alert('Your email is not in valid format');
}
}
}else
{
isValid = false;
}
}
});
return isValid;
};
var resetInput = function(){
$('input, textarea').each(function() {
$(this).val('').text('');
});
};
var sendMail = function(){
var params = {
'action' : 'SendMessage',
'name' : $('[name=contact_name]').val(),
'email' : $('[name=contact_email]').val(),
'subject' : $('[name=contact_subject]').val(),
'message' : $('[name=contact_message]').val()
};
$.ajax({
type: "POST",
url: "php/mainHandler.php",
data: params,
success: function(response){
if(response){
var responseObj = jQuery.parseJSON(response);
if(responseObj.ResponseData)
$('label.sendingStatus').text(responseObj.ResponseData);
}
resetInput();
$('#sendMail').removeAttr('disabled');
},
error: function (xhr, ajaxOptions, thrownError){
//xhr.status : 404, 303, 501...
var error = null;
switch(xhr.status)
{
case "301":
error = "Redirection Error!";
break;
case "307":
error = "Error, temporary server redirection!";
break;
case "400":
error = "Bad request!";
break;
case "404":
error = "Page not found!";
break;
case "500":
error = "Server is currently unavailable!";
break;
default:
error ="Unespected error, please try again later.";
}
if(error){
$('label.sendingStatus').text(error);
}
}
});
};
var calculateTimeDifference = function(startDate) {
var second = 1000;
var minute = second * 60;
var hour = minute * 60;
var day = hour * 24;
var seconds = 0;
var minutes = 0;
var hours = 0;
var days = 0;
var currentDate = new Date();
startDate = new Date(startDate);
var timeCounter = startDate - currentDate;
if (isNaN(timeCounter))
{
return NaN;
}
else
{
days = Math.floor(timeCounter / day);
timeCounter = timeCounter % day;
hours = Math.floor(timeCounter / hour);
timeCounter = timeCounter % hour;
minutes = Math.floor(timeCounter / minute);
timeCounter = timeCounter % minute;
seconds = Math.floor(timeCounter / second);
}
var tDiffObj = {
"Days" : days,
"Hours" : hours,
"Minutes" : minutes,
"Seconds" : seconds
};
return tDiffObj;
};
var StringFormat = function() {
var s = arguments[0];
for (var i = 0; i < arguments.length - 1; i++) {
var regExpression = new RegExp("\\{" + i + "\\}", "gm");
s = s.replace(regExpression, arguments[i + 1]);
}
return s;
}
You need to hook into the success callbacks of each of the $.ajax calls. You can create a method that will show a message for those:
For example, your signUp function's success callback could look like:
success: function(response){
if(response){
var responseObj = jQuery.parseJSON(response);
if(responseObj.ResponseData)
{
$('#subscribe').val('');
showMessage('Your subscription was received. Thank you!');
}
}
}
And you just create a method that will show the message to the user
var showMessage = function (msg) {
// of course, you wouldn't use alert,
// but would inject the message into the dom somewhere
alert(msg);
}
You would call showMessage anywhere the success callback was fired.
You can add your success notifing code in each of the $.ajax success handlers.