Get coupons from stripe in parse.com cloud code - javascript

I am trying to connect to stripe and retrieve a coupon, but am not able to. If I run either of these, I get an error.
Stripe.Coupons.retrieve(couponId, {
success: function(coupon) {
logger.log('debug', "coupon found", coupon);
return callback(coupon, null);
},
error: function(error) {
logger.log('debug', "coupon not found", error);
return callback(null, error);
}
});
I get back an error - invalid_request_error
or
Stripe.Coupons.retrieve({
couponId: couponId
}, {
success: function(coupon) {
logger.log('debug', "coupon found", coupon);
return callback(coupon, null);
},
error: function(error) {
logger.log('debug', "coupon not found", error);
return callback(null, error);
}
});
I get back an error - couponId required
There does not seem to be any good documentation out there about how to accomplish this.

why aren't you using parse.com guide? I am not strong with backbone.js but if you have a table called Coupons you can do this:
var Coupons = Parse.Object.extend("Coupons");
var couponsQuery = new Parse.Query(Coupons);
couponsQuery.equalTo(objectId,couponId);
couponsQuery.first.then(
function(coupon)
{
//success, coupon object returned from query callbeck
}
function(error)
{
console.log("error: " + error.message);
}
);
The code above uses promise, but you can use it in the old way like this:
couponsQuery.first.then(
success: function(coupon)
{
//success, coupon object returned from query callbeck
}
error: function(error)
{
console.log("error: " + error.message);
}
);
I hope this will help you.

Related

Authentication Error when trying to retrieve Youtube Chanel Information

I am trying authenticate the user and then retrieve youtube channel list.
Below is the function to authenticate:
function authenticate() {
showNewLoader('show');
return gapi.auth2.getAuthInstance()
.signIn({scope: "https://www.googleapis.com/auth/youtube.readonly"})
.then(function(response) {
console.log( response);
youtubeAuthResponse['token_details'] = response.tc;
youtubeAuthResponse['google_email'] = '';
youtubeAuthResponse['google_id'] = '';
showNewLoader('hide');
},
function(err) { console.error("Error signing in", err); showNewLoader('hide');});
}
Loading client:
function loadClient() {
showNewLoader('show');
gapi.client.setApiKey("XXXXXX");
return gapi.client.load("https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest")
.then(function() { execute();},
function(err) { console.error("Error loading GAPI client for API", err);showNewLoader('hide');});
}
/*Make sure the client is loaded and sign-in is complete before calling this method.*/
function execute() {
return gapi.client.youtube.channels.list({
"part": [
"snippet",
"statistics"
],
"mine": true
})
.then(function(response) {
/*Handle the results here (response.result has the parsed body).*/
youtubeChannelResponse = response.result;
storeYoutubeData();
},
function(err) { console.error("Execute error", err); showNewLoader('hide') }).then(function(){
});
}
User logs in successfully but I am unable to get the channel info:
Any assistance on this issue is greatly appreciated. #DalmTo

Joining a 1-to-1 private group in SendBird

Using the SendBird JavaScript SDK, I am able to correctly create a private group for 1-to-1 messaging:
var params = new sb.GroupChannelParams();
params.isPublic = false;
params.isEphemeral = false;
params.isDistinct = true;
params.addUserIds([1, 2]);
params.operatorIds = [1];
params.name = name;
sb.GroupChannel.createChannel(params, function(groupChannel, error) {
if (error) {
console.log(error);
return false;
}
sb.GroupChannel.getChannel(groupChannel.url, function(groupChannel) {
var userIds = [2];
groupChannel.inviteWithUserIds(userIds, function(response, error) {
if (error) {
console.log(error);
return false;
}
console.log(response);
});
});
});
This all works correctly, and both users are able to see the private chatroom when retrieving the group list. However, when either user attempts to join the private group, an error is encountered:
SendBirdException: Not authorized. "Can't join to non-public
channel.".
To join the group, I'm using the following code:
sb.GroupChannel.getChannel(id, function(openChannel, error) {
if (error) {
console.log(error);
return false;
}
console.log('Channel Found: ' + openChannel.name + '. Current Participants: ' + openChannel.participantCount);
openChannel.join(function(response, error) {
if (error) {
console.log(error);
return false;
}
console.log('Channel Joined: ' + openChannel.name + '. Current Participants: ' + openChannel.participantCount);
// retrieving previous messages.
});
});
The response from the above code is:
{
"message": "Not authorized. \"Can't join to non-public channel.\".",
"code": 400108,
"error": true
}
Any help is much appreciated. Note, I've checked the documentation and it does not mention how to join a private group (only a public one). I don't see how the "creator" of the chatroom is able to join the room, despite being set as the "operator".
It seems like you are trying to join the open channel while it is actually a group channel. You can join the group channel as a member by calling this method call.
if (groupChannel.isPublic) {
groupChannel.join(function(response, error) {
if (error) {
return;
}
});
}
Instead of
openChannel.join(function(response, error) {
if (error) {
console.log(error);
return false;
}
console.log('Channel Joined: ' + openChannel.name + '. Current Participants: ' + openChannel.participantCount);
// retrieving previous messages.
});
https://docs.sendbird.com/javascript/group_channel#3_join_a_channel_as_a_member

Parse Cloud Code function get deviceToken By username

I am kinda new to the whole cloud code and I am having a bit of trouble fetching some data.
So what I basically want is a function that by giving it a 'username' that is located in the Parse.User database, it will return the user's objectId which I will then use to locate the user's session in the Parse.Session, from there I will get the installationId which I will then use in the Parse.Installation to get the device token.
Note: I have written a function that keeps only 1 session active per user.
My issue:
The Query of Parse.Session has a result which only contains 3 objects, and the installationId is not included,therefor I can not find out what is the installation id and then use it to search the Parse.Installation to get the device token.
input example:
Input:
{"from":"user1",
"msg":"hello",
"title":"Whatever title",
"to":"user2"}
Here is the existing code I currently have which doesn't work.
Parse.Cloud.define('gcm', function(request,response){
var username = request.params.to;
console.log("usr "+username);
var userQuery = new Parse.Query(Parse.User);
userQuery.equalTo('username', username);
userQuery.find({
success: function(results){
var objectId = results[0].id;
console.log("obj id "+objectId);
var user = new Parse.User();
//Set your id to desired user object id
user.id = objectId;
var sessionQuery = new Parse.Query(Parse.Object.extend('Session'));
sessionQuery.include(user);
sessionQuery.find({
success: function(results1){
console.log("result classname type: "+typeof(results1[0]));
var installId = results1[0].installationId ; //here is the value which I want from the result, but the object is type of _Session which does not have installationId.
console.log("inst id "+installId);
var InstallationQuery = new Parse.Query(Parse.Installation);
InstallationQuery.equalTo('installationId',installId);
InstallationQuery.find({
success: function(results2){
var deviceToken = results2[0].get("deviceToken");
console.log("token "+deviceToken);
Parse.Cloud.httpRequest({
method: "POST",
url: " https://gcm-http.googleapis.com/gcm/send",
headers: {'Authorization' : 'key=AIzaSyDj4ISkLW7CzAQEQEhTsq3JYZK5OP8tSzY',
'Content-Type' : 'application/json'},
body: {
"data":
{
"title": request.params.title,
"msg": request.params.msg
},
"to" : deviceToken
},
success: function(httpResponse) {
response.success("Message Sent!");
console.log(httpResponse.text);
},
error: function(httpResponse) {
response.error("Error, Something went wrong.");
console.log("error 4: " + httpResponse.status);
}
});
},
error: function(error) {
//error
console.log("error 3: " + error);
}
});
},
error: function(error) {
//error
console.log("error 2: " + error);
}
});
},
error: function(error) {
//error
console.log("error 1: " + error);
}
});
});

Parse updating a set of objects

I have trouble updating a set of values in my cloud code. I have tried .save() seperately and .saveAll() but the class doesn't get updated in Parse and I get errors returned.
What I am trying to do is to get all messages from class ChatMessages which has a pointer to the Parse user and Chat class. When the method is called, the class column readAt needs to be updated to the current date. I call my method from an iOS (objective-C) app.
This is the latest version of my method:
Parse.Cloud.define("markChatAsReadForRoomAndUser", function(request, response) {
var errorMsg;
var roomName;
var _ = require('underscore.js');
var userPointer = new Parse.User.current();
if (!request.params.roomName) {
errorMsg = "Chat room needs to be identified";
} else {
roomName = request.params.roomName;
}
console.log("Checking chats for userID: " + userPointer.id);
if (!userPointer.id) {
var emptyUserMsg = "User has to be provided";
if (errorMsg) {
errorMsg = errorMsg + emptyUserMsg;
} else {
errorMsg = emptyUserMsg;
};
}
if (errorMsg) {
response.error(errorMsg);
}
var chatQuery = new Parse.Query("Chat");
chatQuery.equalTo("roomName", roomName);
chatQuery.find({
success: function(results) {
if (results.length > 0) {
var chat = results[0];
console.log("Found chat with ID: "+chat.id);
var chatMessagesQuery = new Parse.Query("ChatMessage");
chatMessagesQuery.equalTo("chat", chat);
chatMessagesQuery.notEqualTo("fromUser", userPointer);
chatMessagesQuery.equalTo("readAt", undefined);
chatMessagesQuery.find().then(function(chatMessagesQueryResults) {
_.each(chatMessagesQueryResults, function(result) {
result.set("readAt", new Date());
console.log("Setting readAt for chat message " + result.id + " which has toUser " + result.get("toUser"));
});
return Parse.Object.saveAll(chatMessagesQueryResults,{
success: function(list) {
console.log("Success updating objects");
},
error: function(error) {
console.log("Error updating objects: " + error);
},});
}).then(function(results) {
response.success(results);
console.log("Update for reatAt for chat is successfull");
}, function(error) {
response.error(error);
console.log(error);
});
} else {
response.error("No rooms found");
console.log("No rooms found");
}
},
error: function(error) {
response.error("Room name not found");
console.log(error);
}
});
});
Log output:
E2015-07-19T09:13:48.483Z]v337 Ran cloud function markChatAsReadForRoomAndUser for user CZwQL4y751 with:
Input: {"roomName":"room_czwql4y751_uoc7rjxwpo"}
Result: {"code":101,"message":"object not found for update"}
I2015-07-19T09:13:48.540Z]Checking chats for userID: CZwQL4y751
I2015-07-19T09:13:48.593Z]Found chat with ID: gfvAkirqTs
I2015-07-19T09:13:48.647Z]Setting readAt for chat message ZiWUIdUtUm which has toUser undefined
I2015-07-19T09:13:48.648Z]Setting readAt for chat message YHEBLpR04U which has toUser undefined
I2015-07-19T09:13:48.649Z]Setting readAt for chat message 0wZ4LQd8ZC which has toUser undefined
I2015-07-19T09:13:48.650Z]Setting readAt for chat message MYsYGyXI0k which has toUser undefined
I2015-07-19T09:13:48.751Z]Error updating objects: [object Object]
I2015-07-19T09:13:48.752Z]{"code":101,"message":"object not found for update"}
E2015-07-19T09:13:49.042Z]v337 Ran cloud function markChatAsReadForRoomAndUser for user CZwQL4y751 with:
Input: {"roomName":"room_czwql4y751_uoc7rjxwpo"}
Result: {"code":101,"message":"object not found for update"}
Class:
The query can be vastly simplified by making a chatMessages query relational to chats matching the user and room criteria. The code structure can be improved by not mixing callback and promise styles, and by separating logical chunks into small, promise-returning functions.
Stripping away some of the debug instrumentation you added, we get (untested, of course)...
function unreadChatMessagesInRoom(roomName, excludeUser) {
var query = new Parse.Query("ChatMessage");
query.notEqualTo("fromUser", excludeUser);
query.doesNotExist("readAt");
var chatQuery = new Parse.Query("Chat");
chatQuery.equalTo("roomName", roomName);
query.matchesQuery("chat", chatQuery);
return query.find();
}
Parse.Cloud.define("markChatAsReadForRoomAndUser", function(request, response) {
var _ = require('underscore.js');
var user = request.user;
unreadChatMessagesInRoom(request.params.roomName, user).then(function(chatMessages) {
console.log(chatMessages.length + " chat messages found");
_.each(chatMessages, function(chatMessage) {
chatMessage.set("readAt", new Date());
});
return Parse.Object.saveAll(chatMessages);
}).then(function(results) {
response.success(results);
}, function(error) {
response.error(error);
});
});

Find objects with field value (this is a pointer)

I have class say 'inspection' and there is a field name property (this is a pointer) . I am trying to retrieve a record by field value but getting nothing as a result. I am using following code
getInspectionByProperty = function(req) {
console.log(req.body.propertyId)
var query = new Parse.Query("Inspection");
query.include('property');
query.equalTo('property', req.body.propertyId);
query.find({
success: function(data) {
console.log('in success');
console.log(data);
// Successfully retrieved the object.
},
error: function(error) {
console.log('in error')
console.log("Error: " + error.code + " " + error.message);
}
});
};
I am getting this error in parse log
Error: 102 pointer field property needs a pointer value
How can i get the record .Thanks in advance
Here what i try and thats work for me.
getInspectionByProperty = function(req) {
console.log(req.body.propertyId)
var query = new Parse.Query("Inspection");
query.include('property');
query.equalTo("property", {
"__type": "Pointer",
"className": "Property",
"objectId": propertyId
});
query.find({
success: function(data) {
console.log('in success');
console.log(data);
// Successfully retrieved the object.
},
error: function(error) {
console.log('in error')
console.log("Error: " + error.code + " " + error.message);
}
});
};

Categories

Resources