I have two same paths in my SOAP project, both of them use the same script
import groovy.json.JsonOutput
import groovy.json.JsonSlurper
class Response {
Integer code
String message
String accountId
}
// Match based on body
try {
def requestBody = mockRequest.getRequestContent()
def requestJson = new JsonSlurper().parseText(requestBody)
def phone = requestJson.phone as String
def email = requestJson.email as String
def accountId = requestJson.accountId as String
def response
if (phone == null || phone == "") {
response = new Response(code: 1011, message: 'Field phone is required')
} else if (phone == "+79777777777") {
response = new Response(code: 1021, message: 'The phone field must be in the format +79991112233')
} else if (email == "testt#testt.com") {
response = new Response(code: 1022, message: 'The email field must be in the format test#test.com')
} else {
response = new Response(code: 0, message: 'Success', accountId: accountId)
}
requestContext.response = JsonOutput.toJson(response).toString()
return "response"
} catch (Exception ex) {
requestContext.response = JsonOutput.toJson(new Response(code: 500, message: 'Emulator error: ' + ex.message)).toString()
return "response"
}
My problem is in sending a request to PUT method with the script. The request is
{
"phone":"+79987654125",
"email":"test#notify1.com",
"accountId":"12345"
}
If I send POST, everything is okay
{
"message": "Success",
"code": 0,
"accountId": "12345"
}
If I send PUT, in a response I will see
{
"message": "Emulator error: Text must not be null or empty",
"code": 500,
"accountId": null
}
From the logs I see that the PUT script got requestContext as 'null'. What can be a problem?
Related
I have a django website with shopping cart hooked up to Stripe. On successful payment, the system emails the customer with their purchased electronic products (links to videos and online meetings).
This works perfectly when Stripe is in test mode, but when live, the webhook that triggers the email fails to complete. I don't think it is a browser cookie problem as it happened with a remote user, not just me on my own computer.
I assume it is something to do with CRSRF_Token but I don't have the knowledge or experience to understand it yet. Any help would be greatly appreciated. Code below.
Views:
#csrf_exempt
def stripe_webhook(request):
payload = request.body
sig_header = request.META['HTTP_STRIPE_SIGNATURE']
event = None
try:
event = stripe.Webhook.construct_event(
payload, sig_header, settings.STRIPE_WEBHOOK_SECRET
)
except ValueError as e:
# Invalid payload
return HttpResponse(status=400)
except stripe.error.SignatureVerificationError as e:
# Invalid signature
return HttpResponse(status=400)
# Handle the checkout.session.completed event
if event['type'] == 'checkout.session.completed':
session = event['data']['object']
# Save an order in your database, marked as 'awaiting payment'
create_order(session)
# Check if the order is already paid (e.g., from a card payment)
#
# A delayed notification payment will have an `unpaid` status, as
# you're still waiting for funds to be transferred from the customer's
# account.
if session.payment_status == "paid":
# Fulfill the purchase
fulfill_order(session)
elif event['type'] == 'checkout.session.async_payment_succeeded':
session = event['data']['object']
# Fulfill the purchase
fulfill_order(session)
elif event['type'] == 'checkout.session.async_payment_failed':
session = event['data']['object']
# Send an email to the customer asking them to retry their order
email_customer_about_failed_payment(session)
# Passed signature verification
return HttpResponse(status=200)
def create_order(session):
print(">>>>>>>>>>>>>>>>create_order")
customer_email = session["customer_details"]["email"]
transaction_id = session["payment_intent"]
customer = Customer.objects.get(
email=customer_email
)
# get or create order
try:
print("tryingg")
order = Order.objects.get(transaction_id=transaction_id)
except Order.DoesNotExist:
print("exception")
order = Order(customer=customer, complete=False,
order_status='W', transaction_id=transaction_id)
order.save()
digital_products_url = []
product_info = []
for key, value in session["metadata"].items():
if "item" in key:
item_list = value.split(",")
product_id = item_list[0]
product_quantity = item_list[1]
product = Product.objects.get(id=product_id)
if product.digital:
digital_products_url.append(product.product_url)
product_info.append({
"name": product.name,
"event_type": product.event_type,
"product_url" : product.product_url,
"meeting_passcode" : product.meeting_passcode,
"subtitle" : product.subtitle,
"intro_text" : product.intro_text,
"short_description" : product.short_description,
"price" : product.price,
"image" : product.image,
"start_time" : product.start_time,
"duration" : product.duration,
"description" : product.description
})
orderItem = OrderItem.objects.create(
product=product,
order=order,
quantity=product_quantity,
)
session["metadata"]["digital_product_url"] = digital_products_url
session["metadata"]["product_info"] = product_info
def fulfill_order(session):
print("fulfill_order")
transaction_id = session["payment_intent"]
order = Order.objects.get(
transaction_id=transaction_id
)
order.complete = True
order.order_status = 'P'
order.save()
digital_products_url = session["metadata"]["digital_product_url"]
customer_email = session["customer_details"]["email"]
customer = Customer.objects.get(
email=customer_email
)
if order.shipping == True:
ShippingAddress.objects.create(
customer=customer,
order=order,
address=session["metadata"]['address'],
city=session["metadata"]['city'],
state=session["metadata"]['state'],
zipcode=session["metadata"]['zipcode'],
)
if digital_products_url:
# send email to user
try:
from_email = settings.EMAIL_HOST_USER
to_email = [customer_email]
# import html message.html file
html_template = 'store/mail.html'
html_message = render_to_string(
html_template, {'context': digital_products_url, "product_info": session["metadata"]["product_info"] })
message = EmailMessage(
'North Wales Early Music Festival', html_message, from_email, to_email)
# this is required because there is no plain text email message
message.content_subtype = 'html'
message.send()
order.email_sent = True
order.save()
except Exception as e:
order.email_sent = False
order.save()
Checkout Utility code which contains alos uses csrf_token:
var form = document.getElementById('form');
form.addEventListener('submit', function (e) {
e.preventDefault();
console.log('Form Submitted...');
payment_btn = document.getElementById('make-payment');
payment_btn.click();
// document.getElementById('form-button').classList.add('hidden');
// document.getElementById('payment-info').classList.remove('hidden');
});
document
.getElementById('make-payment')
.addEventListener('click', function (e) {
submitFormData();
});
function submitFormData() {
console.log('Payment button clicked');
var userFormData = {
name: null,
email: null,
total: total,
};
var shippingInfo = {
address: null,
city: null,
state: null,
zipcode: null,
};
if (shipping != 'False') {
shippingInfo.address = form.address.value;
shippingInfo.city = form.city.value;
shippingInfo.state = form.state.value;
shippingInfo.zipcode = form.zipcode.value;
}
if (user == 'AnonymousUser') {
userFormData.name = form.name.value;
userFormData.email = form.email.value;
}
console.log('Shipping Info:', shippingInfo);
console.log('User Info:', userFormData);
var url = '/create-checkout-session/';
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'applicaiton/json',
'X-CSRFToken': csrftoken,
},
body: JSON.stringify({ form: userFormData, shipping: shippingInfo}),
})
.then(function (response) {
return response.json();
})
.then(function (session) {
if (session.status == "success"){
// delete cookie
cart = {};
document.cookie = 'cart=' + JSON.stringify(cart) + ';domain=;path=/';
console.log("cart deleted")
}
return stripe.redirectToCheckout({ sessionId: session.id });
})
.then(function (result) {
// If redirectToCheckout fails due to a browser or network
// error, you should display the localized error message to your
// customer using error.message.
if (result.error) {
alert(result.error.message);
}
})
.catch(function (error) {
console.error("Error:", error);
});
}
</script>
I am trying to send a push notification via Firebase cloud messaging. I am using Firebase admin sdk to send push notification in fcm . I am using nodejs
When I am trying to send a push msg , ...
I am getting this error
{
code: 'messaging/invalid-payload',
message: 'data must be a non-null object' },
codePrefix: 'messaging'
}
My code :
const admin = require('firebase-admin');
const serviceAccount = require(`${__dirname}/fet_firebase.json`);
function sendPushNot(to, body, sendId, type) {
const registrationToken = to;
const notification = {};
let message = { };
const pbody = { body };
if (type === 'User') {
pbody.userId = sendId;
notification.userId = sendId;
notification.title = 'New user Follwed';
}
if (type === 'Post') {
pbody.postId = sendId;
notification.postId = sendId;
notification.title = 'Post Liked';
}
if (type === 'Room') {
pbody.roomId = sendId;
notification.roomId = sendId;
notification.title = 'New Chat messsage';
}
message = {
data: JSON.stringify(pbody),
token: registrationToken,
notification
};
console.log('messgae',message);
admin.messaging().send(message)
.then((response) => {
// Response is a message ID string.
console.log('Successfully sent cloud message:', response);
})
.catch((error) => {
console.log('Error sending cloud message:', error);
});
}
I thought that body is null
But the console output of console.log('messgae',message); is ::
{
data:
'{"body":"pankaj Liked Your Post","postId":"5ed1055ddf0efd2a42f6a28a"}',
token:
'f2umP-jfQyeM1suN77zz7-:APA91bHKzfqfRnmuBom2PIDB8cCPwZtq28JCWLSi1OMPO55JRzyhFZJpTkkNyDu_StTYID-scu-grejaxxn3d4iR6Xidz9-JCk_h-bRsdGHe8nzMrIVsc8vZDFgayiFgJrJ53DaDzb9b',
notification: { postId: 5ed1055ddf0efd2a42f6a28a, title: 'Post Liked'
}
}
So the body is not null
But I am getting data must be a non-null object' error ..
Why?
I fixed this by wrapping the stringified object with curly braces
data : { data: JSON.stringify(object) } // correct
data : JSON.stringify(object) // will result to the described error.
Data must be a non-null object. Above code sample is passing a string. Just remove the JSON.stringify() part.
the above image shows list of unsettled transaction in authorize.net UI. When I request by the getUnsettledTransactionList API call I am receiving the empty result set, why?
"response": {
"messages": {
"resultCode": "Ok",
"message": [
{
"code": "I00004",
"text": "No records found."
}
]
},
"totalNumInResultSet": 0
}
I am using a sandbox account in Authorize.net and NodeJs for development based on following code
https://developer.authorize.net/api/reference/index.html#transaction-reporting-get-unsettled-transaction-list
here is my code
function getUnsettledTransactionList() {
var merchantAuthenticationType = new ApiContracts.MerchantAuthenticationType();
merchantAuthenticationType.setName( process.env.SERVICE_CREDITCARD_API_APILOGINKEY );
merchantAuthenticationType.setTransactionKey( process.env.SERVICE_CREDITCARD_API_TRANSACTIONKEY );
var getRequest = new ApiContracts.GetUnsettledTransactionListRequest();
getRequest.setMerchantAuthentication(merchantAuthenticationType);
getRequest.setStatus(ApiContracts.TransactionGroupStatusEnum.PENDINGAPPROVAL);
//keeping promise resolve and reject funcs outside the promise scope
var promiseResolve, promiseReject;
var promise = new Promise( (_resolve, _reject)=>{
promiseResolve = _resolve;
promiseReject = _reject;
});
var ctrl = new ApiControllers.GetUnsettledTransactionListController(getRequest.getJSON());
ctrl.execute(function(){
var apiResponse = ctrl.getResponse();
var response = new ApiContracts.GetUnsettledTransactionListResponse(apiResponse);
if(response != null){
if(response.getMessages().getResultCode() == ApiContracts.MessageTypeEnum.OK){
var result = {
message: response.getMessages().getMessage()[0].getText(),
messageCode: response.getMessages().getMessage()[0].getCode(),
transactions: [],
status: true,
response: response
}
if(response.getTransactions() != null)
result.transactions = response.getTransactions().getTransaction();
promiseResolve( result );
}
else{
promiseReject({
resultCode: response.getMessages().getResultCode(),
errorCode: response.getMessages().getMessage()[0].getCode(),
errorMessage: response.getMessages().getMessage()[0].getText(),
status: false,
response: response
});
}
}
else{
promiseReject( { message: 'Null Response.', status: false } );
}
});
return promise;
}
You are not supposed to set the Status for the transactions, remove this line of code.
getRequest.setStatus(ApiContracts.TransactionGroupStatusEnum.PENDINGAPPROVAL);
If you add this field in your request, you get only transaction which are pending for approval, and you might be having no transaction pending for approval thus you are getting an empty list.
I'm trying to PUT in some data to a small node server I've written.
The code on the server side is as follows:
router.route('/returnLockID').put(function(req, res){
mongoOp.findOne({
name: req.body.name
}, function(err, user) { if(err) {
response = {"error" : true,"message" : "Error fetching data"};
} else {
// we got data from Mongo.
// change it accordingly.
if(req.body.LockID !== undefined) {
// case where ID needs to be updated.
user.LockID = req.body.LockID;
}
// save the data
user.save(function(err){
if(err) {
response = {"error" : true,"message" : "Error updating data"};
} else {
response = {"error" : false,"message" : "Data is updated for "+req.body.name};
}
res.json(response);
})
}
});
})
I get the response:
{
"error": false,
"message": "Data is updated for nv942"
}
However, the data isn't updated. Can anyone see where I'm going wrong with the saving?
It all goes through fine when I PUT using postman, i can save, however, when I try PUT from iOS I get:
TypeError: Cannot read property 'save' of null
at /Users/NikhilVedi/Documents/FYP/Server/lockserver/routes/users.js:92:13
at Query.<anonymous> (/Users/NikhilVedi/Documents/FYP/Server/lockserver/node_modules/mongoose/lib/model.js:3407:16)
at /Users/NikhilVedi/Documents/FYP/Server/lockserver/node_modules/kareem/index.js:259:21
at /Users/NikhilVedi/Documents/FYP/Server/lockserver/node_modules/kareem/index.js:127:16
at _combinedTickCallback (internal/process/next_tick.js:67:7)
at process._tickCallback (internal/process/next_tick.js:98:9)
The swift code is:
#IBAction func setup(_ sender: Any) {
if (UserDefaults.standard.value(forKey: "userIP") == nil)
{
//make this a message box and stop the program crashing by assigning user defaults a value
UserDefaults.standard.set("localhost", forKey: "userIP")
print("Local host programatically set");
}
let u = UserDefaults.standard.value(forKey: "userIP")!
let name = UserDefaults.standard.value(forKey: "email")!
var request = URLRequest(url: URL(string: "http://\(u):3000/users/returnLockID")!)
request.httpMethod = "PUT"
let postString = "LockID=\(LockID.text!)name=\(name)"
print(postString)
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data, encoding: .utf8)
// print("responseString = \(responseString)")
if let data = responseString?.data(using: String.Encoding.utf8) {
let resString = JSON(data: data)
if resString["success"].stringValue == "true"
{
print("works");
}
else if resString["success"].stringValue == "false"
{
print("failed")
print(resString["message"].stringValue)
//dismiss window and set bool to true
UserDefaults.standard.set(true, forKey: "LockIDPresent")
self.dismiss(animated: true, completion: nil);
}
}
}
task.resume()
}
Thanks in advance!
One error I see, but not likely the fix to your issue is that you should be doing res.json(response); in the first if statement clause.
Another thing to notice is that you are calling save regardless of whether or not a req.body.LockID value is provided, so in cases where it isn't the user is saved without any modification. You might want to print out the value or req.body.LockID, as that might be the reason that the user email is not being updated.
When i am executing this via curl its working :
curl -u -X DELETE -H 'accept:application/json' http://localhost:13000/test/test_userid"
I made a common function which accept methodtype ( GET, POST, DELETE etc) and content type( JASON, TEXT ) for the httpbuilder.
def public httpRequest(String url, String content, Method requestType, ContentType contentType)
{
try{
def myClient = new HTTPBuilder(url)
myClient.request(requestType,contentType) { req ->
headers.'Content-Type' = 'application/json'
body=content
response.success = { resp, data ->
def reponse=[resp:resp,data:data]
return reponse
}
response.failure = { resp ->
println 'Response Code '+resp.statusLine
}
// called only for a 404 (not found) status code:
response.'404' = { resp ->
println 'Not found'
}
}
}
catch(Exception e)
{
println "error"+e.getProperties()
}
}
Now if i make a POST request , its working.
However if i make a GET or DELETE request using
def response = httpRequest(url,"",DELETE,JSON)
or
def response = httpRequest(url,"",GET,TEXT)
its shows the following error :-
error[message:Cannot set a request body for a DELETE/GET method, class:class java.lang.IllegalArgumentException
Do i need to make a separate function for GET/DELETE?
because
myClient.request(requestType) { req ->
headers.'Content-Type' = 'application/json'
body=content
response.success = { resp, data ->
def reponse=[resp:resp,data:data]
return reponse
}
response.failure = { resp ->
println 'Response Code '+resp.statusLine
}
// called only for a 404 (not found) status code:
response.'404' = { resp ->
println 'Not found'
}
}
}
WORKS
Delete and Get wont accept Body , hence the solution is to make a check and execute accordingly
if(requestType.equals(DELETE)||requestType.equals(GET))
{
try{
def myClient = new HTTPBuilder(url)
myClient.request(requestType) { req ->
headers.'Content-Type' = 'application/json'
headers.Accept = 'application/json'
response.success = { resp, data ->
def reponse=[resp:resp,data:data]
return reponse
}
response.failure = { resp ->
println 'Response Code '+resp.statusLine
}
// called only for a 404 (not found) status code:
response.'404' = { resp ->
println 'Not found'
}
}
}
catch(Exception e)
{
println "error"+e.getProperties()
}
}
else
<---post request -->