I've tried SOAP SSL with different module, and it's working like a charm (code is here)
// var request = require('request');
// var auth = "Basic " + new Buffer("user" + ":" + "pwd").toString("base64")
// var options = {
// 'method': 'GET',
// 'url': 'https://put_correct_soap_url?wsdl',
// 'headers': {
// 'Authorization': auth
// }
// };
// process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = '0';
// request(options, function (error, response) {
// if (error) throw new Error(error);
// console.log(response.body);
// });
here comes my original requirement to manage the connectivity using existing code (module name is soap).
create client is working with older wsdl but it isn't working with the recently upgraded version of wsdl, it always returns the error "ECONNREFUSED IP:80". I've tried with multiple scenarios like wsdl_headers, wsdl_options, blank etc ... still no luck ... any help would highly be appreciated ... thanks!
// var auth = "Basic " + new Buffer("user" + ":" + "pwd").toString("base64")
/wsdl'
//reqeust : req
// forceSoap12Headers: true,
// rejectUnauthorized: false,
// strictSSL: false,
// wsdl_headers: {
// 'Authorization': auth ,
// Connection : 'keep-alive'
// }
// ,
// wsdl_options : {
// gzip : true,
// secureProtocol : 'TLSv1_2_method'
// }
};
process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = '0';
soap.createClient( url_new
, options
, function(err, client) {
console.log(err)
client.describe();
});
Error: connect ECONNREFUSED [IP]:80\n at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1145:16)\n at TCPConnectWrap.callbackTrampoline (internal/async_hooks.js:126:14
Related
I am using Paytm payment gateway for transaction. My front-end is in reactjs and backend is in nodejs and expressjs. I wanted that after successful payment next page is redirected.
Backend Code-
for checking checksum and transaction.
PaytmChecksum.generateSignature(JSON.stringify(paytmParams.body), paytmconfig.merchantkey).then(function(checksum){
paytmParams.head = {
"signature" : checksum
};
var post_data = JSON.stringify(paytmParams);
var options = {
/* for Staging */
hostname: 'securegw-stage.paytm.in',
/* for Production */
// hostname: 'securegw.paytm.in',
port: 443,
path: '/v3/order/status',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': post_data.length
}
};
// Set up the request
var response = "";
var post_req = https.request(options, function(post_res) {
post_res.on('data', function (chunk) {
response += chunk;
});
post_res.on('end', function(){
console.log('Response: ', response);
res.write(response)
});
});
// post the data
post_req.write(post_data);
post_req.end();
});
Front-end code:
will call onPayment function for making the payments
onPayment= async(e)=>{
e.preventDefault();
try {
var amount="1.00";
var mobile_number="+919999999999";
var email="abcd#gmail.com";
var orderId="ORDER_ID"+(new Date().getTime());
let params={
orderId:orderId,
email:email,
amount:amount,
mobile_number:mobile_number
}
var url="http://localhost:4000/payment/paynow";
var request={
url:url,
params:params,
method:"get"
}
const response = await Axios(request);
const processParams=await response.data;
console.log(processParams);
var details={
action : "https://securegw-stage.paytm.in/order/process",
// params : params
params : processParams
}
this.post(details);
} catch (error) {
}
}
You can use react-router-dom
import {useHistory} from 'react-router-dom'
const history = useHistory()
history.push('yourNextPage', {details:detail})
either history.replace should work:
history.replace('yourNextPage', {details:detail})
EDIT
{details:detail} is in case you want to pass your next page a state from the previous page
if you dont want to pass any state
it would be enough
history.push('yourNextPage')
Please refer the code available on the below repository for checksum in node.js.
https://github.com/paytm/Paytm_Node_Checksum
You can also refer the below repository for react (front-end)
https://github.com/paytm/paytm-blink-checkout-react
I've created an app which works for Spotify Premium users only (PUT methods don't work for non-premium users according to Spotify's documentation). It's a ten-question interactive quiz where a playlist generates in your Spotify account, plays it and you have to guess the name of each song. It's generated with a NodeJS Backend and displayed via ReactJS. The game can be demoed here: https://am-spotify-quiz.herokuapp.com/
Code can be reviewed below:
server.js
const express = require('express');
const request = require('request');
const cors = require('cors');
const querystring = require('querystring');
const cookieParser = require('cookie-parser');
const client_id = ''; // Hiding for now
const client_secret = ''; // Hiding
const redirect_uri = 'https://am-spotify-quiz-api.herokuapp.com/callback/';
const appUrl = 'https://am-spotify-quiz.herokuapp.com/#';
/**
* Generates a random string containing numbers and letters
* #param {number} length The length of the string
* #return {string} The generated string
*/
var generateRandomString = function(length) {
var text = '';
var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (var i = 0; i < length; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
};
var stateKey = 'spotify_auth_state';
var app = express();
app.use(express.static(__dirname + '/public'))
.use(cors())
.use(cookieParser());
app.get('/login', function(req, res) {
var state = generateRandomString(16);
res.cookie(stateKey, state);
// scopes needed to make required functions work
var scope = 'user-read-private ' +
'user-read-email ' +
'user-read-playback-state ' +
'user-top-read ' +
'playlist-modify-public ' +
'playlist-modify-private ' +
'user-modify-playback-state ' +
'user-read-playback-state';
res.redirect('https://accounts.spotify.com/authorize?' +
querystring.stringify({
response_type: 'code',
client_id: client_id,
scope: scope,
redirect_uri: redirect_uri,
state: state
}));
});
app.get('/callback/', function(req, res) {
// your application requests refresh and access tokens
// after checking the state parameter
var code = req.query.code || null;
var state = req.query.state || null;
var storedState = req.cookies ? req.cookies[stateKey] : null;
if (state === null || state !== storedState) {
res.redirect(appUrl +
querystring.stringify({
access_token: access_token,
refresh_token: refresh_token
}));
} else {
res.clearCookie(stateKey);
var authOptions = {
url: 'https://accounts.spotify.com/api/token',
form: {
code: code,
redirect_uri: redirect_uri,
grant_type: 'authorization_code'
},
headers: {
'Authorization': 'Basic ' + (new Buffer(client_id + ':' + client_secret).toString('base64')),
},
json: true
};
request.post(authOptions, function(error, response, body) {
if (!error && response.statusCode === 200) {
var access_token = body.access_token,
refresh_token = body.refresh_token;
var options = {
url: 'https://api.spotify.com/v1/me',
headers: {
'Authorization': 'Bearer ' + access_token,
'Content-Type': 'application/json' // May not need
},
body: { // Likely don't need this anymore!
'name': 'Test Playlist',
'public': false
},
json: true
};
// use the access token to access the Spotify Web API
request.get(options, function(error, response, body) {
console.log(body);
});
// we can also pass the token to the browser to make requests from there
res.redirect(appUrl +
querystring.stringify({
access_token: access_token,
refresh_token: refresh_token
}));
} else {
res.redirect(appUrl +
querystring.stringify({
error: 'invalid_token'
}));
}
});
}
});
// AM - May not even need this anymore!
app.get('/refresh_token', function(req, res) {
// requesting access token from refresh token
var refresh_token = req.query.refresh_token;
var authOptions = {
url: 'https://accounts.spotify.com/api/token',
headers: { 'Authorization': 'Basic ' + (new Buffer(client_id + ':' + client_secret).toString('base64')) },
form: {
grant_type: 'refresh_token',
refresh_token: refresh_token
},
json: true
};
request.post(authOptions, function(error, response, body) {
if (!error && response.statusCode === 200) {
var access_token = body.access_token;
res.send({
'access_token': access_token
});
}
});
});
console.log('Listening on 8888');
app.listen(process.env.PORT || 8888);
I have a react component which displays as soon as the user is logged in, called premium.js. If you need all the code, you can see it here. Below are the two PUT methods that I need for my game; one to turn off the shuffle feature and the other one used to play the playlist:
removeShuffle() {
axios({
url: 'https://api.spotify.com/v1/me/player/shuffle?state=false',
method: "PUT",
headers: {
'Authorization': 'Bearer ' + this.state.accesstoken
}
})
.then((response) => {
console.log(response)
})
.catch((error) => {
console.log(error)
})
}
// Then... play the playlist to get started
playPlaylist(contextUri) {
axios({
url: 'https://api.spotify.com/v1/me/player/play',
method: "PUT",
data: {
context_uri: contextUri
},
headers: {
'Authorization': 'Bearer ' + this.state.accesstoken
}
})
.then((response) => {
console.log(response)
})
.catch((error) => {
console.log(error)
})
}
These work perfectly fine when I, the creator of the game, try it; however, I had another premium user try it and found this error:
This doesn't seem to make much sense as I've discovered this error happens with another user, regardless of whether they are using Windows or Mac. Does anyone know what this means, and how can I solve? Thanks in advance!
I've also been using Spotify's API and I eventually got the same error when trying to PUT https://api.spotify.com/v1/me/player/play after an inactivity period, where no device was marked as active (I don't know exactly how long, but no more than a couple of hours).
Apparently one device must be set as active so that you can invoke the play endpoint successfully.
If you want to change the status of a device as active, according to their documentation, you can first try to GET https://api.spotify.com/v1/me/player/devices in order to obtain the list of available devices:
// Example response
{
"devices" : [ {
"id" : "5fbb3ba6aa454b5534c4ba43a8c7e8e45a63ad0e",
"is_active" : false,
"is_private_session": true,
"is_restricted" : false,
"name" : "My fridge",
"type" : "Computer",
"volume_percent" : 100
} ]
}
and then select one of the available devices by invoking the player endpoint PUT https://api.spotify.com/v1/me/player, including:
device_ids Required. A JSON array containing the ID of the device on which playback should be started/transferred.
For example: {device_ids:["74ASZWbe4lXaubB36ztrGX"]}
Note: Although an array is accepted, only a single device_id is currently supported. Supplying more than one will return 400 Bad Request
play with value true if you want to start playing right away.
Most likely you didn't get that error yourself because one of your devices was already active when you tested it. If you have no activity during a couple of hours on your own account and then try to invoke the v1/me/player/play endpoint, I'd expect you to get the same error.
An easy workaround to make sure that this was in fact your problem would be to ask your test user to please start playing a song on the Spotify app (no matter which), then pause it, and then trigger the function on your app that invokes the v1/me/player/play endpoint. That shouldn't return the No active device found error anymore.
The way I understand it is you are trying to play a playlist that does not belong to the current user (/me) Which could be the cause of the error.
I am trying to do the following on a high level, using node (express, https modules):
listen for POST requests (say R1) on /example endpoint (express app)
read the post payload from the request, process it repackage it and make an https POST request (say R11) to an external REST API.
read the post payload from the response to R11, process it repackage it and send as a response to R1.
Problem is, how to send response from within callbackExternalApi ? Please see code below and question in comments.
const callbackExternalApi =
function (response) {
response.on('data',
function(data) {
// do some processing on data
var processedData = ...
**// I want response_R1 over here
// so that I can do the following
response_R1.send(processedData)
// how do I get response_R1 over here??**
})
}
const requestHandlerExample =
function (request_R1, response_R1) {
// payload
var postBodyJson = '' // some payload here
// headers
var postHeaders = {
'content-type' : 'application/json',
'accept' : 'application/json'
}
// options
var postOptions = {
'host' : 'localhost',
'port' : '9000',
'path' : '/external/rest/api',
'method' : 'POST',
'headers' : postHeaders
}
// do the post call
var postRequest = _httpsModule.request(postOptions, callbackExternalApi)
postRequest.write(postBodyJson);
postRequest.end();
postRequest.on('error', function(error) {
console.error('an error occured'+error)
})
}
_app.post('/example', requestHandlerExample)
Thanks,
Jatin
I just defined global variables for response_R1 and set those in the requestHandlerExample callback. Not sure if that's the best approach, but it works.
var _response_R1
const callbackExternalApi =
function (response) {
response.on('data',
function(data) {
// do some processing on data
var processedData = ...
_response_R1.send(processedData)
})
}
const requestHandlerExample =
function (request, response) {
_response_R1 = response // set this for use in callbackExternalApi
// payload
var postBodyJson = '' // some payload here
// headers
var postHeaders = {
'content-type' : 'application/json',
'accept' : 'application/json'
}
// options
var postOptions = {
'host' : 'localhost',
'port' : '9000',
'path' : '/external/rest/api',
'method' : 'POST',
'headers' : postHeaders
}
// do the post call
var postRequest = _httpsModule.request(postOptions, callbackExternalApi)
postRequest.write(postBodyJson);
postRequest.end();
postRequest.on('error', function(error) {
console.error('an error occured'+error)
})
}
_app.post('/example', requestHandlerExample)
I am trying to automatically post some assets on a Github release I programmatically create.
Here is my upload function:
function uploadFile(fileName, uploadUrl, callback){
var uploadEndPoint = url.parse(uploadUrl.substring(0,uploadUrl.indexOf('{')));
options.host = uploadEndPoint.hostname;
options.path = uploadEndPoint.pathname+'?name=' + fileName;
options.method = 'POST';
options.headers['content-type'] = 'application/zip';
var uploadRequest = https.request(options, callback);
uploadRequest.on('error', function(e) {
console.log('release.js - problem with uploadRequest request: ' + e.message);
});
var readStream = fs.ReadStream(path.resolve(__dirname,'builds',fileName));
readStream.pipe(uploadRequest);
readStream.on('close', function () {
req.end();
console.log('release.js - ' + fileName + ' sent to the server');
});
}
At the end of this I get a 404 not found
I tried auth from token and user/password
I checked the url
I though it might be because of SNI, but I don't know how to check that.
Any clue ? Thanks !
I found a solution to that problem by NOT using the low level node.js modules and using instead restler which is a library that handles SNI.
Here is how is used it:
rest = require('restler'),
path = require('path'),
fs = require('fs');
fs.stat(path.resolve(__dirname,'builds',fileName), function(err, stats){
rest.post(uploadEndPoint.href+'?name=' + fileName, {
multipart: true,
username: GITHUB_OAUTH_TOKEN,
password: '',
data: rest.file(path.resolve(__dirname,'builds',fileName), null, stats.size, null, 'application/zip')
}).on('complete', callback);
});
Hope that will help someone :)
EDIT on 27/02/2015: We recently switched from restler to request.
var
request = require('request'),
fs = require('fs');
var stats = fs.statSync(filePath);
var options = {
url: upload_url.replace('{?name}', ''),
port: 443,
auth: {
pass: 'x-oauth-basic',
user: GITHUB_OAUTH_TOKEN
},
json:true,
headers: {
'User-Agent': 'Release-Agent',
'Accept': 'application/vnd.github.v3+json',
'Content-Type': 'application/zip',
'Content-Length': stats.size
},
qs: {
name: assetName
}
};
// Better as a stream
fs.createReadStream(filePath).pipe(request.post(options, function(err, res){
// Do whatever you will like with the result
}));
The upload_uri can be retrieved through a get request on an existing release or in the response directly after the release creation.
I must confess I'm stuck. I need a nodejs app to download a file from a SharePoint library. Simple, huh? No. Not the simple OOTB SharePoint. The only-ssl allowed, with specific mandatory header added and surely only domain-based NTLM authentication method.
I've tried httpntlm (https://www.npmjs.org/package/httpntlm) that seemed to just might work in advance, but no. The SP responses with something went wrong message.
I've tried node-sharepoint, but it doesn't support NTLM yet. The app gets ETIMEDOUT response.
Any ideas, please welcome.
I am able to download the file using httpntlm module.you need to change the few lines of code.Replace the waterfall logic with below code in httpntlm.js.
async.waterfall([
function ($){
var type1msg = ntlm.createType1Message(options);
httpreq.get(options.url, {
headers:{
'Connection' : 'keep-alive',
'Authorization': type1msg
},
agent: keepaliveAgent
}, $);
},
function (res, $){
if(!res.headers['www-authenticate'])
return $(new Error('www-authenticate not found on response of second request'));
var type2msg = ntlm.parseType2Message(res.headers['www-authenticate']);
var type3msg = ntlm.createType3Message(type2msg, options);
if(method!=='download'){
httpreq[method](options.url, {
headers:{
'Connection' : 'Close',
'Authorization': type3msg
},
allowRedirects: false,
agent: keepaliveAgent
}, $);
}else{
//By Dheeraj for file download
httpreq.download(
url,
{
headers:{
'Connection' : 'Close',
'Authorization': type3msg
},
//allowRedirects: false,
agent: keepaliveAgent
},
__dirname + 'your_filename',
function (err, progress){
if (err) return console.log(err);
console.log(progress);
}, function (err, res){
if (err) return console.log(err);
console.log(res);
});
}
}
], callback);
};
['get', 'put', 'post', 'delete', 'head','download'].forEach(function(method){
exports[method] = exports.method.bind(exports, method);
});
and replace download method of httpreq.js(httpntm_module/node_modules/httpreq_module/httpreq.js) You can find it at Line number 79 approx.
exports.download = function (url,options, downloadlocation, progressCallback, callback) {
//var options = {};
options.url = url;
options.method = 'GET';
options.downloadlocation = downloadlocation;
options.allowRedirects = true;
// if only 3 args are provided, so no progressCallback
if(callback === undefined && progressCallback && typeof(progressCallback)==="function")
callback = progressCallback;
else
options.progressCallback = progressCallback;
doRequest(options, callback);
}
Please let me know if you are still getting issues.