I'm trying to get a request signed with twitter so I can get a request token and got stuck. I have used the info that twitter use in their documentation to be sure that I have formated t correctly etc. I have identical Basestring and Key but still I'm not getting the same Signature. I have looked at several other examples and I seem to have done the same thing.
Would love some help to sort this out!
Here is the code:
private function sign_request($http_method, $url, $params, $oath)
{
// SET BASE STRING
$sign_params = $this->set_sign_params($params, $oath);
$sign_url = $this->set_sign_url($url);
$base_string = $this->set_sign_basestring($http_method, $sign_params, $sign_url);
print $base_string; // Output the same as the twitter example: POST&https%3A%2F%2Fapi.twitter.com%2Foauth%2Frequest_token&oauth_callback%3Dhttp%3A%2F%2Flocalhost%3A3005%2Fthe_dance%2Fprocess_callback%3Fservice_provider_id%3D11%26oauth_consumer_key%3DGDdmIQH6jhtmLUypg82g%26oauth_nonce%3DQP70eNmVz8jvdPevU3oJD2AfF7R7odC2XJcn4XlZJqk%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1272323042%26oauth_version%3D1.0
// GET HMAC-SHA1 SIGNATURE
if($this->signature_method == 'HMAC-SHA1')
{
// SET KEY
$key = $this->set_sign_key();
print $key; // Output the same as the twitter example: MCD8BKwGdgPHvAuvgvz4EQpqDAtx89grbuNMRd7Eh98&
//SIGN
$signature = base64_encode(hash_hmac('sha1', $base_string, $key, true));
print $signature; // DO NOT output the same as the twitter example. Twitteroutput: 8wUi7m5HFQy76nowoCThusfgB+Q= and my outout: Ewqbgi+AMRZGMcqwQTjhE5/ZD80=
}
return $signature;
}
What have I missed? Anyone got any Idea?
Also a "fun" thing is that if I set the signture to the one in the twitter example I still can't get a request token...
Thanks in advanced!
Your base string is not the same as Twitter's. That is why you are getting different signatures.
Twitter's:
POST&https%3A%2F%2Fapi.twitter.com%2Foauth%2Frequest_token&oauth_callback%3Dhttp%253A%252F%252Flocalhost%253A3005%252Fthe_dance%252Fprocess_callback%253Fservice_provider_id%253D11%26oauth_consumer_key%3DGDdmIQH6jhtmLUypg82g%26oauth_nonce%3DQP70eNmVz8jvdPevU3oJD2AfF7R7odC2XJcn4XlZJqk%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1272323042%26oauth_version%3D1.0
Your's:
POST&https%3A%2F%2Fapi.twitter.com%2Foauth%2Frequest_token&oauth_callback%3Dhttp%3A%2F%2Flocalhost%3A3005%2Fthe_dance%2Fprocess_callback%3Fservice_provider_id%3D11%26oauth_consumer_key%3DGDdmIQH6jhtmLUypg82g%26oauth_nonce%3DQP70eNmVz8jvdPevU3oJD2AfF7R7odC2XJcn4XlZJqk%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1272323042%26oauth_version%3D1.0
The difference is in the oauth_callback variable.
Twitter's:
oauth_callback%3Dhttp%253A%252F%252Flocalhost%253A3005%252Fthe_dance%252Fprocess_callback%253Fservice_provider_id%253D11%26
Your's:
oauth_callback%3Dhttp%3A%2F%2Flocalhost%3A3005%2Fthe_dance%2Fprocess_callback%3Fservice_provider_id%3D11%26
Related
I am working on a telegram bot which sends telephone numbers to my telegram account. The problem is, that a '+' is converted to a ' ' blank. So every telephone number is wrong.
E.g. '+4915733000000' turns into '4915733000000'. I've tried to use the HTML code + the unicode version \u002B and the url encoding caracter %2B and none of them work.
https://api.telegram.org/botTOKEN/sendMessage?chat_id=MYID&text=Test:\u2031 Unicode:\u002B HTML:+ URL:%2B
Result: Test:‱ Unicode: HTML:
Do you know any possiblility to send a plus sign?
Thanks!
In case someone is using VBA to send Telegram messages with + in them you can replace your string like that:
Dim URL as String
Dim reURL as String
URL = "https://www.webpage.com/product+name/specifics+number" 'etc....
reURL = replace(URL, "+, "%2B")
'send message to telegram code here
For more Encoding info you can visit: https://www.w3schools.com/tags/ref_urlencode.ASP
It is possible to send the plus sign using POST method.
Here's the sample Google App Script code (can be easily adapted to JavaScript).
var options = {
method : "post",
payload: {
method: "sendMessage",
chat_id: "<chat_id_here>",
text: "+something",
parse_mode: "HTML"
}
};
var response = UrlFetchApp.fetch("https://api.telegram.org/bot<YOUR_TOKEN>/", options);
Plus sign can also be easily sent with parse_mode="Markdown".
Just checked (this time on Python using telebot library) that both options work:
bot.send_message(CHAT_ID, "Phone number: +1234567890", parse_mode='Markdown')
bot.send_message(CHAT_ID, "Phone number: +1234567890", parse_mode='HTML')
I had the same problem. I was using Java and Spring's WebClient. The only way to make it work is building WebClient using DefaultUriBuilderFactory and set encoding mode to NONE.
DefaultUriBuilderFactory factory = new DefaultUriBuilderFactory(url);
factory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.NONE);
WebClient webClient = WebClient.builder().uriBuilderFactory(factory).filter(logRequest()).build();
Default is EncodingMode.TEMPLATE_AND_VALUES so if you replace + with %2B the resulting URL is %252B. Setting the encoding mode to NONE doesn't replace any especial characters so I had to replace them manually.
private String replaceUrlSpecialCharacters(String message) {
return message.replace("%", "%25").replace("+", "%2B").replace(" ", "%20").replace("|", "%7C").replace(System.lineSeparator(), "%0A");
}
And now the + sign is shown in my messages.
I'am using PHP and this case was solved with rawurlencode. Below is the code:
public function send_message($tg_msg)
{
$tg_token = ''; // Bot Token
$chat_id = ''; // Chat ID
$url = 'https://api.telegram.org/bot' . $tg_token . '/sendMessage?parse_mode=markdown&chat_id=' . $chat_id;
$curlopt_url = $url . '&text=' . rawurlencode($tg_msg);
$ch = curl_init();
$optArray = array(
CURLOPT_URL => $curlopt_url,
CURLOPT_RETURNTRANSFER => true
);
curl_setopt_array($ch, $optArray);
curl_exec($ch);
curl_close($ch);
}
$msg = 'The message';
send_message($msg);
And now the + sign is shown in my messages.
I got that solved by just using this php function:
utf8_encode(text_to_send)
I am trying to do use the post method for a simple suitescript program, i am very new to this.
In Netsuite i have written a suitescript as follows.
function restPost()
{
var i = nlapiLoadRecord('department', 115);
var memo = nlapisetfieldvalue('custrecord225', ' ');// this is a customfield, which i want to populate the memo field, using rest client in firefox
var recordId = nlapiSubmitRecord(i);
}
i have created a script record and uploaded this suitescript and even copied the external URL to paste it in restclient.
In Restclient(firefox plugin), pasted the external URL, i have given the method as post, header authorization given, content-type: application/json, and in body i put in {"memo":"mynamehere"};
In this the error i get is
message": "missing ) after argument list
I even tried it by writting other suitescript programs the errors i get is as follows:
Unexpected token in object literal (null$lib#3) Empty JSON string
Invalid data format. You should return TEXT.
I am kinda new to the programming world, so any help would be really good.
I think you are trying to create a RESTlet for POST method. Following is the sample code for POST method -
function createRecord(datain)
{
var err = new Object();
// Validate if mandatory record type is set in the request
if (!datain.recordtype)
{
err.status = "failed";
err.message= "missing recordtype";
return err;
}
var record = nlapiCreateRecord(datain.recordtype);
for (var fieldname in datain)
{
if (datain.hasOwnProperty(fieldname))
{
if (fieldname != 'recordtype' && fieldname != 'id')
{
var value = datain[fieldname];
if (value && typeof value != 'object') // ignore other type of parameters
{
record.setFieldValue(fieldname, value);
}
}
}
}
var recordId = nlapiSubmitRecord(record);
nlapiLogExecution('DEBUG','id='+recordId);
var nlobj = nlapiLoadRecord(datain.recordtype,recordId);
return nlobj;
}
So after deploying this RESTlet you can call this POST method by passing following sample JSON payload -
{"recordtype":"customer","entityid":"John Doe","companyname":"ABCTools Inc","subsidiary":"1","email":"jdoe#email.com"}
For Authorization you have to pass request headers as follows -
var headers = {
"Authorization": "NLAuth nlauth_account=" + cred.account + ", nlauth_email=" + cred.email +
", nlauth_signature= " + cred.password + ", nlauth_role=" + cred.role,
"Content-Type": "application/json"};
I can understand your requirement and the answer posted by Parsun & NetSuite-Expert is good. You can follow that code. That is a generic code that can accept any master record without child records. For Example Customer Without Contact or Addressbook.
I would like to suggest a small change in the code and i have given it in my solution.
Changes Below
var isExistRec = isExistingRecord(objDataIn);
var record = (isExistRec) ? nlapiLoadRecord(objDataIn.recordtype, objDataIn.internalid, {
recordmode: 'dynamic'
}) : nlapiCreateRecord(objDataIn.recordtype);
//Check for Record is Existing in Netsuite or Not using a custom function
function isExistingRecord(objDataIn) {
if (objDataIn.internalid != null && objDataIn.internalid != '' && objDataIn.internalid.trim().length > 0)
return true;
else
return false;
}
So whenever you pass JSON data to the REStlet, keep in mind you have
to pass the internalid, recordtype as mandatory values.
Thanks
Frederick
I believe you will want to return something from your function. An empty object should do fine, or something like {success : true}.
Welcome to Netsuite Suitescripting #Vin :)
I strongly recommend to go through SuiteScript API Overview & SuiteScript API - Alphabetized Index in NS help Center, which is the only and most obvious place to learn the basics of Suitescripting.
nlapiLoadRecord(type, id, initializeValues)
Loads an existing record from the system and returns an nlobjRecord object containing all the field data for that record. You can then extract the desired information from the loaded record using the methods available on the returned record object. This API is a core API. It is available in both client and server contexts.
function restPost(dataIn) {
var record = nlapiLoadRecord('department', 115); // returns nlobjRecord
record.setFieldValue('custrecord225', dataIn.memo); // set the value in custom field
var recordId = nlapiSubmitRecord(record);
return recordId;
}
I have a google script that sends an email with a Word doc as an attachment. It used to work until google deprecated OAuth 1.0
This is the line that's failing:
var doc = UrlFetchApp.fetch(url+'download/documents/Export?exportFormat=doc&format=doc&id='+ copyId, googleOAuth_('docs',url)).getBlob();
If I remove the second parameter, i.e. function call to OAuth, it should work? Why do I need to authenticate? It should be able to fetch the document using an ID from google drive. It appears to work (because I don't see any errors), however, when I get an email there is a corrupt word doc attachment.
So, I tried implementing OAuth 2.0. But I'm not getting anywhere. Here's my code:
function getDriveService() {
return OAuth2.createService('drive')
.setAuthorizationBaseUrl('https://accounts.google.com/o/oauth2/auth')
.setTokenUrl('https://accounts.google.com/o/oauth2/token')
.setClientId(CLIENT_ID)
.setClientSecret(CLIENT_SECRET)
.setCallbackFunction('authCallback')
.setPropertyStore(PropertiesService.getUserProperties())
.setScope('https://www.googleapis.com/auth/drive')
.setParam('login_hint', Session.getActiveUser().getEmail())
.setParam('access_type', 'offline');
//.setParam('approval_prompt', 'force');
}
function authCallback(request) {
var driveService = getDriveService();
var isAuthorized = driveService.handleCallback(request);
if (isAuthorized) {
return HtmlService.createHtmlOutput('Success! You can close this tab.');
} else {
return HtmlService.createHtmlOutput('Denied. You can close this tab');
}
}
var oauth2Service = getDriveService();
var token = oauth2Service.getAccessToken();
var parameters = { method : 'get',
headers : {'Authorization': 'Bearer '+ token}};
var options =
{
"method" : "get"
};
var resp = UrlFetchApp.fetch('https://docs.google.com/feeds/download/documents/Export?exportFormat=doc&format=doc&id='+ copyId, parameters);
doc = resp.getBlob();
I'm getting a generic error [Access not granted or expired]. All I want is to be able to send an email with an attachment that is a document (format doc or docx) stored from my Google drive. Seems impossible! I'm able to attach this doc as a pdf but NOT a Microsoft document.
Any help will be greatly appreciated!
https://github.com/googlesamples/apps-script-oauth2 - look at setup
...
Have you added OAuth 2.0 in the libraries?
Resources -> Libraries -> then add 'MswhXl8fVhTFUH_Q3UOJbXvxhMjh3Sh48'
I am making a web-application in ASP.NET. I have used oauth to get profile fields of a user. I need the names of the companies followed by the user, but the problem is that the default value is set to 20. so, if the user is following more than 20 companies i am not able to get it. Please tell me how can i modify the start and count values. Iv used this url to make the call http://api.linkedin.com/v1/people/~:(following:(people,companies,industries,news-sources),educations).. Please help asap..
var requestHeader = GetUserProfileAuthorizationHeader();
var queryString = CreateQueryString();
var request = WebRequest.Create(RequestProfileUrl + queryString);
request.Headers.Add("Authorization", requestHeader.ToString());
request.Method = HttpMethod.Get;
try
{
var response = request.GetResponse();
using (var responseStream = response.GetResponseStream())
{
var reader = new StreamReader(responseStream);
var responseText = reader.ReadToEnd();
reader.Close();
return responseText;
}
}
Here public static string RequestProfileUrl = "http://api.linkedin.com/v1/people/~:(following:(companies:(id,name,size,industry),industries))"; And the method CreateQueryString() does this queryString = "?format=xml"; whenever i try to add something like queryString = "?format=xml&start=0&count=40"; it gives error dispite the number of companies followed being more than 60.. maybe i need to pass the query parameters in between the RequestProfileUrl i.e near the company somehow..
Did you tried adding ?start=x&count=y to the url?
Probably if you're getting an error when you add query parameters to the URL, you're not adding those parameters in the way that your OAuth library expects them to be added. You need to figure out how to add the parameters so they're added to the signature generation process or your signature will be invalid and you'll get a 401 error back from the server.
I'm storing the oauth info from Twitter in a Flash Cookie after the user goes though the oauth process. Twitter says that this token should only expire if Twitter or the user revokes the app's access.
Is there a call I can make to Twitter to verify that my stored token has not been revoked?
All API methods that require authentication will fail if the access token expires. However the specific method to verify who the user is and that the access token is still valid is GET account/verify_credentials
This question may be old, but this one is for the googlers (like myself).
Here is the call to twitter using Hammock:
RestClient rc = new RestClient {Method = WebMethod.Get};
RestRequest rr = new RestRequest();
rr.Path = "https://api.twitter.com/1/account/verify_credentials.json";
rc.Credentials = new OAuthCredentials
{
ConsumerKey = /* put your key here */,
ConsumerSecret = /* put your secret here */,
Token = /* user access token */,
TokenSecret = /* user access secret */,
Type = OAuthType.AccessToken
};
rc.BeginRequest(rr, IsTokenValid);
Here is the response:
public void IsTokenValid(RestRequest request, RestResponse response, object userState)
{
if(response.StatusCode == HttpStatusCode.OK)
{
var user = userState;
Helper.SaveSetting(Constants.TwitterAccess, user);
}
else
{
Dispatcher.BeginInvoke(() => MessageBox.Show("This application is no longer authenticated "))
}
}
I always borrow solutions from SO, this is my first attempt at giving back, albeit quite late to the question.
When debugging manually:
curl \
--insecure https://api.twitter.com/1/account/verify_credentials.json?oauth_access_token=YOUR_TOKEN
I am using TwitterOAuth API and here is the code based on the accepted answer.
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $twitter_oauth_token, $twitter_oauth_secret);
$content = $connection->get("account/verify_credentials");
if($connection->getLastHttpCode() == 200):
// Connection works fine.
else:
// Not working
endif;