Mojo SDK retrieve all contacts - palm-pre

I'm playing with the Mojo SDK and I want to get all contacts.
this.controller.serviceRequest('palm://com.palm.contacts/crud', {
method: 'listContacts',
parameters: {
limit: 100
},
onSuccess: this.handleListResponse.bind(this),
onFailure: function(errResp){
Mojo.Log.info(errResp.errorText)
}.bind(this),
onerror: function(errResp){
Mojo.Log.info(errResp.errorText)
}.bind(this)
});
This is what I have right now, but I don't get anything back. And Mojo.Log.info doesn't seem to work. Any suggestions?
Thanks

I'm also fairly new at PRE development but here is what I think the issue is.
The error that comes back is "Account Not Found". You need to add accountId: as a parameter to the service request.
That account id, according to the documentation, is a Synergy account and needs to be created for your application. Click here for reference about the accountId and createAccount methods

Related

Shopify order API returns OK but does not update order using JS

I'm trying to create an order using JS. I've authenticated my app and have a function that POST's to orders.json. I see a status code of 200, indicating that the request submitted OK (right?) but the order itself never gets created. I've heard something about disabling cookies in my request, but I don't know how to do that, so if that's what I need to do please let me know.
I'm putting up my entire function, since I'm new to this entire thing and it seems that it's probably the structure of my request, not the API call. I'm seeing the "Error" log in the console, so clearly the error function is running.
function submitShuffle(prodid)
{
console.log(prodid);
var params = {
"order": {
"line_items": [
{
"variant_id": prodid,
"quantity": 1
}
]
}
};
$.ajax({
type: 'POST',
url: 'https://<my-usrnam>:<my-pass>#toyboxshufflesandbox.myshopify.com/admin/orders.json',
dataType: 'application/json',
data: params,
success: function(data){
console.log(data);
},
error: function(data){
console.log("Error");
console.log(data);}
});
}
You cannot retrieve information from Shopify Admin API by AJAX. There is a limitation about this because you have to expose your username/key and password which is not a good idea.
You have to use some service/app or just to create a custom app.
Shopify returns an Object when you make a call. Hence 200 OK status. Inspect the object returned. A failed create POST object will not have an ID. So there is clue number one. Secondly, you'll see that Shopify tells you what the problem was in the Error key of the returned object. If you cannot figure out what you did with the message from Shopify, make the same call to the GraphQL endpoint if you can, as the error messages Shopify returns from those endpoints are currently much better. They are backporting them to the older REST API, but for now, GraphQL is more expressive.

The enduring saga of when to use EWS vs the Rest API in an Outlook Add-in

This question is based on a previous question I asked but with a bit more detail and experience since.
First some background, I have an Outlook Addin that should forward a users message and then move the message to a specific folder. This needs to work in both OWA, and Outlook 2016 environments for on Prem Exchange. It should also work in both of the former clients, as well as Outlook Mobile App for O365 users.
My specific question comes down to detecting when to use EWS vs the Rest API (or even MS Graph API).
Here is a snippet of of my code:
Office.initialize = function() {
$(document).ready(function() {
$('#forward').click(forwardMessage);
});
};
function forwardMessage() {
if(Office.context.mailbox.restUrl) { // The problem child
forwardEWS(); // Works like a charm
} else {
forwardRest(); // Works fine for O365 users
}
}
function forwardRest() {
var restHost = Office.context.mailbox.restUrl;
var restId = getItemRestId();
Office.context.mailbox.getCallbackTokenAsync({isRest: true}, function(result){
if (result.status === "succeeded") {
var accessToken = result.value;
$.ajax({
url: restHost + '/v2.0/me/messages/' + restId + '/forward',
type: 'post',
headers: {'Authorization': 'Bearer ' + accessToken},
contentType: 'application/json',
data: JSON.stringify({
'ToRecipients': [
{'EmailAddress': { 'Address': 'user#outlook.com' }}
]
})
}).done(function (response) {
sidepane_status('success', 'Message forwarded.');
moveRest(restHost, accessToken, restId);
}).fail(function(err) {
sidepane_status('error', 'Could not forward message');
});
} else {
sidepane_status('error', 'Could not get token');
}
});
}
function moveRest(restHost, accessToken, restId) {
var folder = $('#ews_folder').val();
$.ajax({
url: restHost + '/v2.0/me/messages/' + restId + '/move',
type: 'post',
headers: {'Authorization': 'Bearer ' + accessToken},
contentType: 'application/json',
data: JSON.stringify({ 'DestinationId': folder })
}).fail(function(err) {
sidepane_status('error', 'Could not move message to ' + folder);
});
}
function getItemRestId() {
if (Office.context.mailbox.diagnostics.hostName === 'OutlookIOS') {
return Office.context.mailbox.item.itemId;
} else {
return Office.context.mailbox.convertToRestId(
Office.context.mailbox.item.itemId,
Office.MailboxEnums.RestVersion.v2_0
);
}
}
In my previous question, I was told to check the return of Office.context.mailbox.restUrl. If it returned a URL the Rest API could be used and if not use EWS. The issue here is with my on Prem Exchange user, in OWA Office.context.mailbox.restUrl returns nothing, great then I just use EWS. However on Outlook 2016 Office.context.mailbox.restUrl returns https://exch1.mailhost.com/api. This leads to some issues.
The first being in the case of when the On Prem Exchange user in Outlook 2016 returning a Rest URL. Following this article for interacting with the Rest API with the help of OfficeJS, it is not possible with an with an On Prem User to get an access token through OfficeJS with Office.context.mailbox.getCallbackTokenAsync({isRest: true}, function(result){ ... }); and in turn the Rest API cannot be used then.
I would, as a comment in my original question suggested, just use EWS. However, this brings up another problem with mobile. From this article, EWS is not supported in mobile, and Rest must be used. I do understand an on Prem user would not be able to use the Outlook mobile app tho.
The problem arises that I cannot find a way to determine what API to use and in what context. If I key off of Office.context.mailbox.restUrl then both On Prem and O365 users in OWA will correctly use their respective API's and everything is unicorns and rainbows. However, for an On Prem user in Outlook 2016, it will attempt to use the Rest API when it should be using EWS. And finally, if I solely rely on EWS then Addin will not work for O365 users in the Outlook mobile clients.
I'm kinda at a loss after a good month of trial, error, and swimming in the sea that is known as Microsoft documentation. Any help would be greatly appreciated
Yes, this is a known issue with restUrl, from the docs:
Note: Outlook clients connected to on-premises installations of Exchange 2016 with a custom REST URL configured will return an invalid value for restUrl.
I understand that makes it a bit more complicated. I would say in the current state of affairs, here's how I would make the call:
First check restUrl. If undefined, then EWS is the way to go.
If restUrl has a value, then try getCallbackTokenAsync with isRest: true. If that doesn't get a token, then fallback to EWS.
I would then save this is a setting in the user's mailbox (via Office.context.roamingSettings) so on future runs the add-in could skip this "discovery" phase and just use the right API from the start.
On a self-serving side note, I'm working on an ongoing side project to revamp the Outlook add-in docs at https://learn.microsoft.com/en-us/outlook/add-ins/, so hopefully that will help with the whole "swimming in the sea" feeling. I'd love to get your feedback on what specifically is casting you adrift though, if you could contact me on Twitter that would be much appreciated.

Is possible to use Stripe.com managed accounts with Parse.com Stripe module?

I saw that Parse.com has module for Stripe payments, but I am not sure do they support Stripe.com managed accounts, since I am creating mobile apps for marketplaces and Stripe support told me that I should use managed accounts for marketplaces.
Parse.com Stripe module: https://parse.com/docs/js/guide#cloud-code-modules-stripe
Stripe.com managed accounts: https://stripe.com/docs/connect/managed-accounts
Anyone with experience with Parse.com Stripe module?
Parse unfortunately hasn't updated their Stripe API library in a long time and have stated they don't have plans to update it. Their API library is built against the 2012-07-09version of the Stripe API which is a few years before Connect and Managed Accounts entered the Stripe API. Thus the Parse API library does not support managed accounts.
You need to make sure that your account with Stripe has been set up to allow for connected accounts. By adding var Buffer = require('buffer').Buffer; to you stripe cloud code outside the scope of the request, you can create an account using this code:
var Buffer = require('buffer').Buffer;
var bankAccountNumber = request.params['bankAccountNumber']
Parse.Cloud.httpRequest({
method:"POST",
url: "https://" +"api.stripe.com/v1" + "/accounts",
headers: {
'Authorization': 'Basic ' + new Buffer('YOUR_STRIPE_SECRET_KEY' + ':' + '').toString('base64')
},
body:{
"managed": false,
"country": "US",
"email": "example#mailinator.com"
},
success: function(httpResponse) {
response.success(httpResponse.text);
},
error: function(httpResponse) {
response.error('Request failed with response code: ' + httpResponse.status);
}
If you create a standalone account, you will receive an email upon creation. Mailinator is a service that allows you create working email addresses with any name, but there is no privacy.
Edit: I am working with connected accounts. I've noticed that when testing this, if you successfully create an account that subsequent attempts to create an account with the same email will fail. To transfer funds, Stripe requires certain properties that you can view under the connected account in the platform's dashboard. I've found the syntax for several of these (all except bank account).
Edit2: To complete the required fields for Stripe to verify your account you need to include a bank account field. My project is running in Swift and the parameter passed into my cloud code was a token created in my app using STPAPIClient.sharedClient().createTokenWithBankAccount and the test account information given at https://stripe.com/docs/testing#how-do-i-test-sending-transfers.
body:{
"managed": true,
"country": "US",
"email": "yourUniqueemail#mailinator.com",
"legal_entity[first_name]": "AnyName",
"legal_entity[last_name]": "AnyName",
"legal_entity[dob[day]]": "20",
"legal_entity[dob[month]]": "11",
"legal_entity[dob[year]]": "1993",
"legal_entity[type]": "individual",
"tos_acceptance[date]": "1438198036",
"tos_acceptance[ip]": "123.34.56.789",
"bank_account": bankAccountNumber,
},
Edit 3:
The way my code works is that customers are created and are charged. The charge amount is sent to the platform with an application fee. Then the connected account is payed out from the platform.(I am not completely sure this is the proper way to use Stripe; however, this method seems to work in test mode and allows us to store information about customers and the people we pay out.) Fortunately, the charge method exists in Parse's api, so we do not have to make a POST request. Here is the charge method that does this functionality.
Parse.Cloud.define("chargeAccount", function(request, response) {
var amount2 = request.params['amount']*100;
Stripe.Charges.create({
amount: amount2,
currency: request.params["currency"],
customer: request.params['customerId'],
description: request.params['description'],
application_fee: amount2/5,
destination: request.params['destinationAccountId']
},{
success: function(charge) {
response.success("There was a charge of $" + amount2/100 + " The application fee is: $" +amount2/500 +".");
},
error: function(error) {
response.error("\nThis is the error:\n" +error);
}
})
});
I found this question on the parse questions section. I believe you should be able to change this code around to meet your needs. I haven't tested it, but by looking at the stripe api, I came up with this:
here is the what the curl request looks like:
curl https://api.stripe.com/v1/accounts \
-u sk_test_BQokikJOvBiI2HlWgH4olfQ2: \
-d managed=false \
-d country=US \
-d email="bob#example.com"
So your javascript would be something like this I believe:
Parse.Cloud.httpRequest({
//STRIPE_SECRET_KEY will be your stripe secret key obviously, this is different from the public key that you will use in your iOS/Android side.
// STRIPE_API_BASE_URL = 'api.stripe.com/v1'
method:"POST",
url: "https://" + STRIPE_API_BASE_URL + "/accounts/",
headers: {
"keys[secret]" : STRIPE_SECRET_KEY
},
body:{
"managed="+true,
"country="+"US",
"email="+"bob#example.com"
},
success: function(httpResponse) {
response.success(httpResponse.text);
},
error: function(httpResponse) {
response.error('Request failed with response code ' + httpResponse.status);
}
});
This may not be 100% because I haven't been able to test it, but look at the following questions for some more resources:
https://parse.com/questions/cloud-httprequest-unable-to-take-dictionary-object-as-parameter-cant-form-encode-an-object-error
https://www.parse.com/questions/stripe-store-multiple-cards-on-a-customer

How can I get the user first name from facebook in cloud code?

How can I get the user first name from facebook in cloud code?
I can do it using objC and in the app, but I want from the server, cloud code.
How can I send a facebook request from cloud code? do I have to use the access token saved in authData in any way? Thanks
It seems that you can use a graph search
FB.api('/me', function(response) {
alert('Your name is ' + response.name);
});
But they donĀ“t recommend you to get Facebook data of a user using the Parse Cloud
Check it out
https://www.parse.com/questions/get-user-info-from-facebook-javascript-sdk-after-login
For those browsing this now that docs are getting out of synch after FB drop this was not officially supported as per https://groups.google.com/forum/#!topic/parse-developers/mw7qhHGIsOc
IMHO best bet ATM is to use the graph API directly. Within a Parse.Cloud function:
let access_token = request.user.get('authData').facebook.access_token
Parse.Cloud.httpRequest({
url: 'https://graph.facebook.com/v2.8/' + path + '&access_token=' + access_token
})
.then(function(result) {
console.log(result)
}, function(error) {
console.log(error)
})
for the original question let path='me?fields=first_name' or FB_ID if not me

Parse.User.save() doesn't work with Facebook API

I'm using the Facebook SDK to auth a user, and trying to save the user's email to the record after authenticating. However, I keep getting an error on the save call.
The code in question:
Parse.FacebookUtils.logIn({
access_token: authResponse.access_token,
expiration_date: expire_date.toISOString(),
id: response.id
},
{
success: function(user) {
console.log("success!");
user.set({"email":response.email});
user.save();
window.App.navigate("#myplaces", {trigger:true});
},
...
That user.save() call returns error occurred: http://www.parsecdn.com/js/parse-1.1.14.min.js:1: TypeError: 'undefined' is not an object.
According to the docs, I have to be in an authentication call (".logIn", etc.) to perform save(), so I'm wondering if this still works with Parse.FacebookUtils.logIn. Seems like it should.
Ideas as to why this isn't working? The ideal behavior is to log the user in, retrieve information from the FB response, and save that back to the user record on Parse.
Thanks!
Justin
Not sure about this but I had the same problem in Cloud Code and I used success/error callbacks when calling save(...):
user.save(null, {
success: function(){
// Code
},
error: function(){
// Code
}
});
See also here: https://parse.com/questions/saving-a-relation-on-the-current-user

Resources