I am making a post request to add a subscription to a user, but I get this error Result: Request failed with response code 400 https://stripe.com/docs/api/curl#create_subscription
Parse.Cloud.define("Subscription", function(request, response){
Parse.Cloud.httpRequest({
method:"POST",
url: "https://" + 'sk_test_***' + ':#' + 'api.stripe.com/v1' + "/subscriptions/" + 'plan=' + request.params.customerId + 'customer=' + request.params.plan,
success: function(httpResponse){
response.success(httpResponse.data);
},
error: function(httpResponse){
response.error('Request failed with response code ' + httpResponse.status);
}
});
});
First, I'd suggest you go to your Stripe dashboard and review the logs to see what the actual error was - that might help clear this up for you.
I'm not very familiar with Parse Cloud, but just wandering around the code I see that's based on the request module so based on how that library handles POSTing forms, I think it should probably look like this:
Parse.Cloud.define("Subscription", function(request, response) {
Parse.Cloud.httpRequest({
method: "POST",
url: "https://" + 'sk_test_***' + ':#' + 'api.stripe.com/v1/subscriptions/',
form: {
plan: request.params.customerId,
customer: request.params.plan
},
success: function(httpResponse) {
response.success(httpResponse.data);
},
error: function(httpResponse) {
response.error('Request failed with response code ' + httpResponse.status);
}
});
});
You can do something like this just to check. Furthermore your url is wrong
Parse.Cloud.define("Subscription", function(request, response) {
Parse.Cloud.httpRequest({
method: "GET",
url: "https://api.stripe.com/v1/subscriptions -u sk_test_"+ 'User_id'+ '-d plan=' + request.params.customerId+ '-d customer='request.params.plan",
success: function(httpResponse) {
response.success(httpResponse.data);
},
error: function(httpResponse) {
response.error('Request failed with response code ' + httpResponse.status);
}
});
});
Replace your url in the correct format. I hope it helps.
Related
I am writing Chrome Extension for Vtiger CRM.
I need to create ability to add value for "Proposal text" field in the CRM on project page.
Here is the docs: https://www.vtiger.com/docs/rest-api-for-vtiger#/Update
How I do it:
Get the project from Vtiger API.
Change value "cf_potentials_proposaltext" in the project object.
Make POST (as required by docs) request to update Vtiger API endpoint, send updated project object
Get "duplicate alert" response..
I am absolutely sure, since I checked that I am sending the modified project object - using the console.log 'Temprorary_1' (in vtigerAddProposal) and 'Temprorary_2'(in vtigerUpdatePotential), also checked changed value in Chrome dev console in Network tab..
Here is my code:
function vtigerAddProposal() {
var temprorary_potential;
var dialog = $('#dialog');
chrome.storage.sync.get(['proposal'], function(result) {
$.ajax( {
url: 'https://roonyx.od2.vtiger.com/restapi/v1/vtiger/default/retrieve',
type: 'GET',
data: {
'id': localStorage.getItem('vtiger_last_opportunity_id')
},
success: function( response ) {
temprorary_potential = response['result'];
console.log("Temprorary_1: " + JSON.stringify(temprorary_potential, null, 2));
temprorary_potential['cf_potentials_proposaltext'] = result.proposal;
vtigerUpdatePotential(temprorary_potential);
},
error: function (response) {
console.log("Failed to get opportunity from Vtiger.");
$('#dialog-inner-text').text("Vtiger: " + response.status + " " + response.statusText);
dialog.show(800);
console.log(response);
}
});
});
}
function vtigerUpdatePotential(data) {
var dialog = $('#dialog');
console.log("Temprorary_2: " + JSON.stringify(data, null, 2));
// Second Part
$.ajax( {
url: 'https://roonyx.od2.vtiger.com/restapi/v1/vtiger/default/update',
type: 'POST',
data: {
element: JSON.stringify(data)
},
success: function( response ) {
console.log("Successfully updated Vtiger potential.")
console.log(response);
localStorage.removeItem('vtiger_last_opportunity_id'); // в случае успеха удаляем oppId
},
error: function (response) {
console.log("Failed to update potential in Vtiger.")
$('#dialog-inner-text').text("Vtiger potential wasn't update: " + response.status + " " + response.statusText);
dialog.show(800);
console.log(response);
}
});
}
Thank you in advance.
Problem solved by using revise https://www.vtiger.com/docs/rest-api-for-vtiger#/Revise once instead of update. Thanks to #pinaki
I'm using this part of the Outlook API. It says that you should be able to do a post request, however when I try I get the following error:
Failed to load https://login.microsoftonline.com/common/oauth2/v2.0/token: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3003' is therefore not allowed access. The response had HTTP status code 400.
How do I fix this though? I obviously don't have access to Outlook's servers, but surely they would let me do a post request considering that's what it says to do in the documentation!.
Here is my code by the way if that helps:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
let url = new URL(window.location);
let code = url.searchParams.get('code');
let redirect = 'http%3A%2F%2Flocalhost%3A3003%2Fauth-process-token.html';
let clientId = '<MY ID>';
let clientSecret = '<MY KEY>';
var req_string = 'grant_type=authorization_code&code=' + code + '&redirect_uri=' + redirect + '&client_id=' + clientId + '&client_secret=' + clientSecret;
$.ajax({
type: 'POST',
url: 'https://login.microsoftonline.com/common/oauth2/v2.0/token',
crossDomain: true,
data: req_string,
dataType: 'application/x-www-form-urlencoded',
success: function (responseData, textStatus, jqXHR) {
var value = responseData.someKey;
},
error: function (responseData, textStatus, errorThrown) {
console.log('POST failed.', errorThrown);
}
});
</script>
EDIT: I fixed the "bad request" error, but it still gives me the other one.
One workaround for this is by using cors.io
http://cors.io/?http://your_link
so it would be
http://cors.io/?https://login.microsoftonline.com/common/oauth2/v2.0/token
I would like to get multiple tweets of some hashtag, for example "iPhone".
Use the following code, but this will result in an error that sends the URL in red.
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "http://search.twitter.com/search.json?q=iPhone&count=100",
success: function(response) {
console.log(response);
},
error: function(data) {
console.log('We have a problem!');
}
});
Is your error
{"errors":[{"code":215,"message":"Bad Authentication data."}]}
Please refer https://dev.twitter.com/rest/public/search:- Please note that now API v1.1 requires that the request must be authenticated, check Authentication & Authorization documentation for more details on how to do it.
use titter4j library and following code
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey("your key")
.setOAuthConsumerSecret(
"your key")
.setOAuthAccessToken(
"your key")
.setOAuthAccessTokenSecret(
"your key");
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();
Query query = new Query("#iphone7");
query.setCount(100);
try {
result = twitter.search(query);
tweets.addAll(result.getTweets());
System.out.println("Gathered " + tweets.size() + " tweets");
} catch (TwitterException te) {
System.out.println("Couldn't connect: " + te.toString());
}
I really appreciated if somebody could tell me what is wrong in that authentication? I take the authentication off from the server to test without it, but javascript is broken.
$('#btnSignIn').click(function() {
var username = $("#username").val();
var password = $("#password").val();
function make_base_auth(user, password) {
var tok = user + ':' + password;
var final = "Basic " + $.base64.encode(tok);
console.log("FINAL---->" +final);
alert("FINAL---->" +final);
return final;
}
$.ajax({
type: "GET",
contentType: "application/json",
url: "http://localhost:8080/SesameService/webresources/users/secured/login",
crossDomain: true,
dataType: "text",
async: false,
data: {},
beforeSend: function (xhr){
xhr.setRequestHeader('authorization', make_base_auth(username, password));
},
success: function() {
alert('Thanks for your signin in! ');
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
alert(' Error in signIn-process!! ' +textStatus);
}
});
});
ERROR: If I take the
beforeSend: function (xhr){
xhr.setRequestHeader('authorization', make_base_auth(username, password));
-part off from the function, I can get into REST-service. I haven't got authentication on at the moment. Could this be the reason or shoud I have the authentication on in the server when using that header?
contentType: "application/json",
#GET
#Path("/secured/login")
#Produces({"text/plain"})
public String login() {
return "Is it working or not?";
}
When using beforeSend-part in JS, I got an error:
[Exception... "Failure" nsresult: "0x80004005 (NS_ERROR_FAILURE)" location: "JS frame :: http://localhost:8383/Sesame/assets/js/jquery.min.js :: .send :: line 3" data: no] { message="Failure"
, result=2147500037
, name="NS_ERROR_FAILURE"
,
If I have understood correctly, "authorization + Basic " in header tells the Glassfish-server, that basic-authentication will be done. After authentication it goes to REST-service and in my case returns json-object to HTML5-client. HTML5-client is running in localhost:8383 and the rest services are running in localhost:8080.
If I run secured rest-services straight in localhost:8080, it is working, so that is not the problem. The problem is that when I am using or trying to use rest-services from different domain localhost:8383, I get get the JS-error console.log('----ERROR IN ------Siging IN----------'); I am not 100 % sure, but I think that the problem is 401 unauthorized, so cross domain authentication is not working.
Shoud I insert crossDomain: true? I have seen it somewhere, maybe that can be the case?
In serverside I've got the filter:
<init-param>
<param-name>com.sun.jersey.spi.container.ContainerResponseFilters</param-name>
<param-value>util.CrossOriginResourceSharingFilter</param-value>
</init-param>
public ContainerResponse filter(ContainerRequest request, ContainerResponse response) {
response.getHttpHeaders().putSingle("Access-Control-Allow-Origin", "*");
response.getHttpHeaders().putSingle("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
response.getHttpHeaders().putSingle("Access-Control-Allow-Headers", "content-type");
return response;
}
QUESTIONS
1) is it possbile that if server is not configured for authentication and I still use the authorization-header breaks the app and cause the error?
2) What that JS-error means?
Cheers,
Sami
I just can't get the ajax service to work. A simple class to $.get("http://google.com") does not work. Also, this code does not work, too:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<script>
$.ajax({
url: "http://google.com",
dataType: "html",
success: function(data, status) {
console.log("Success:");
console.log(" Data: " + data);
console.log(" Status: " + status);
},
error: function(request, status, error) {
console.log("Error:");
console.log(" Request: " + request);
console.log(" Status: " + status);
console.log(" Error: " + error);
},
});
</script>
</body>
</html>
saved in test.html.
This is the output on the console:
Error:
Request: [object Object]
Status: error
Error:
And these are the, I guess, important values of the returned object:
readyState 0
responseText ""
status 0
statusText "error"
Why does the request not work?
Thank you,
You can't use AJAX to access cross-domain scripts like that. This is because of the Same Origin Policy -- something which has been implemented for security reasons:
This mechanism bears a particular significance for modern web
applications that extensively depend on HTTP cookies to maintain
authenticated user sessions, as servers act based on the HTTP cookie
information to reveal sensitive information or take state-changing
actions. A strict separation between content provided by unrelated
sites must be maintained on client side to prevent the loss of data
confidentiality or integrity.
So you have a few options:
Just call scripts on your own server
Call scripts on your server which can communicate with third-party sites/apps/scripts
Use either JSONP or XML as a callback format.
You cannot make a request to another domain due to the same-origin-policy. See http://api.jquery.com/jQuery.ajax/ for more information.
You could use JSONP to achieve cross domain communication.
http://en.wikipedia.org/wiki/JSON#JSONP
But for plain html you have yo be on the same domain.
$.ajax({
url: "http://google.com",
dataType: "jsonp",
success: function(data, status) {
console.log("Success:");
console.log(" Data: " + data);
console.log(" Status: " + status);
},
error: function(request, status, error) {
console.log("Error:");
console.log(" Request: " + request);
console.log(" Status: " + status);
console.log(" Error: " + error);
},
});
EDIT:
But if your URL doesn't return a valid formatted json, your request will fail.
For a working example check:
http://jsfiddle.net/S3tAR/1/