Authorization HTTP header with ASP.NET - php

I want to create an authorization http header using asp.net i have the code given in documentation if i want to do it using php+ curl here is the link http://help.voxeo.com/go/help/evolution.sms.postapi .
I dont want to install php on my IIS and want to work purely in .net environment . Can some one give asp alternative to following code :
$botkey='[999999]';
$from="14075551212";
$userKey = $_REQUEST['userkey'];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://api.messaging.staging.voxeo.net/1.0/messaging');
curl_setopt($ch, CURLOPT_HEADER, 0);
$data="botkey=".$botkey."&apimethod=send&msg=".$msg."&userkey=".$userKey."&network=SMS& from=".$from;
curl_setopt($ch, CURLOPT_USERPWD, '[Evolution User Name]:[Evolution Password]');
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
c url_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 100);
I need ASP.net alternative to below curl
curl -u MyUserName:MyPassword "http://api.messaging.staging.voxeo.net/1.0/messaging" -X POST -d "botkey=12345&apimethod=send&msg=My%20test%20message.&user=14075555555&network=SMS&from=14076666666"

I'm not sure I understand you completely but this is something I had to do to allow flash to get to a secure section of my app. I have more checks in place which I have removed for sake of clarity but this will create an authorisation cookie if this is what you need. I must ask though, why can't you use the normal authentication methods in ASP.NET?
void Application_BeginRequest(object sender, EventArgs e)
{
string SessionParamName = "";
string SessionCookieName = "";
string AuthParamName = "";
string AuthCookieName = "";
try
{
SessionParamName = "ASPSESSID";
SessionCookieName = "ASP.NET_SessionId";
if (HttpContext.Current.Request.Form[SessionParamName] != null)
UpdateCookie(SessionCookieName, HttpContext.Current.Request.Form[SessionParamName]);
else if (HttpContext.Current.Request.QueryString[SessionParamName] != null)
UpdateCookie(SessionCookieName, HttpContext.Current.Request.QueryString[SessionParamName]);
}
catch { }
try
{
AuthParamName = "AUTHID";
AuthCookieName = FormsAuthentication.FormsCookieName;
if (HttpContext.Current.Request.Form[AuthParamName] != null)
UpdateCookie(AuthCookieName, HttpContext.Current.Request.Form[AuthParamName]);
else if (HttpContext.Current.Request.QueryString[AuthParamName] != null)
UpdateCookie(AuthCookieName, HttpContext.Current.Request.QueryString[AuthParamName]);
}
catch { }
}
private void UpdateCookie(string CookieName, string CookieValue)
{
HttpCookie Cookie = HttpContext.Current.Request.Cookies.Get(CookieName);
if (Cookie == null)
Cookie = new HttpCookie(CookieName);
Cookie.Value = CookieValue;
HttpContext.Current.Response.Cookies.Add(Cookie);
}

Related

curl command not working on bigrock server…?

<?php
if(isset($_POST["submit"]))
{
$adm=$_POST["admno"];
$phn=$_POST["phn1"];
include("model.php");
$db = new database;
$r=$db->register($adm);
while($row=mysql_fetch_array($r))
{
if($row["phn_no1"]==$phn || $row["phn_no2"]==$phn || $row["phn_no3"]==$phn)
{
$formatted = "".substr($phn,6,10)." ";
$password = $formatted + $adm;
echo $password;
$db->setpassword($adm,$password);
$pre = 'PREFIX';
$suf = '%20ThankYou';
$sms = $pre.$password.$suf;
session_start();
$ch = curl_init("http://www.perfectbulksms.in/Sendsmsapi.aspx? USERID=ID&PASSWORD=PASS&SENDERID=SID&TO=$phn&MESSAGE=$sms");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
$result = curl_exec($ch);
curl_close($ch);
header("Location:password.php?msg=new");
}
else
{
header("Location:register.php?msg=invalid");
}
}
}
?>
this code is working perfect on my local host .. but when i put it on server ... it takes lots of time but the code in curl command is not working it only refers to next page ... i checked that curl is enabled .. if i use only sms api without curl command it sends sms immidiately.... but i want to run both header and also want to hide my sms api.... is there any alternate of this ???

Is it possible execute a function in Prestashop via hooks without creating a module?

I have created this test function (lets call it ABtest.php) to send a test message:
$host = "http://localhost:8080";
$id = "123";
$email = "mine.mail#gmail.com";
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERPWD, "mine.mail:mypassword");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HTTPAUTH, TRUE);
function send($host,$id,$email,$ch){
curl_setopt($ch, CURLOPT_URL, $host . "/c/" . $id . "/your ID/");
curl_setopt($ch, CURLOPT_POSTFIELDS, "to=" . $email . "&subject=Your ID ");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
$output = curl_exec($ch);
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) != 200 && curl_getinfo($ch, CURLINFO_HTTP_CODE) != 201) {
printf("An error occured (HTTP %d): %sn", curl_getinfo($ch, CURLINFO_HTTP_CODE), $output);
} else {
printf("Success");
}
}
I would like to place this code into my hook hookValidateOrder($params) like this:
public function hookValidateOrder($params)
{
$id = $params['cart']->id;
$host = "http://localhost:8080";
$email = "mine.mail#gmail.com";
// + the rest of my PHP function - see the 1st code block above
}
The problem is that I don´t really know where to place my code. As You can see I am not creating a module, I just want to execute my PHP function via hookValidateOrder($params) hook.
Is that possible and where do I place it?
I don't think so. Not in the proper way.
But you can create an override, in the overrides folder for PaymentModule.php:
abstract class PaymentModule extends PaymentModuleCore
{
public function validateOrder($id_cart, $id_order_state, $amount_paid, $payment_method = 'Unknown', $message = null, $extra_vars = array(), $currency_special = null, $dont_touch_amount = false, $secure_key = false, Shop $shop = null)
{
// do what you need before
parent::validateOrder($id_cart, $id_order_state, $amount_paid, $payment_method, $message, $extra_vars, $currency_special, $dont_touch_amount, $secure_key, $shop);
// do what you need after
}
}
You can also override the any module to do it, or the hook exec and check if it's trying to execute the hookValidateOrder then you place your code.
If you do create an override, don't forget to delete (or rename) the file cache/class_index.php after, to index you new override.

PHP and timestamp protocol

In PHP i must sign a document with the Timestamp Protocol via HTTP (RFC 3161) using ARUBA as CA.
The Aruba's documentation says:
To time-stamp a datum you must call the url https://servizi.arubapec.it/tsa/ngrequest.php
with a POST method. In the POST body you must insert the structure TimeStampReq (RFC 3161)
encode in DER.
How can i make the request using the php?
you can use curl function in php.
Ok, This is part of my edited/modified tcpdf.php.
//Send request to TSA Server with Curl
if(extension_loaded('curl')) {
$hdaLog .= "\nCurl was already Loaded\nCurl is sending tsRequest to \"".$this->timestamp_url."\"";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->timestamp_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_USERAGENT, '1');
curl_setopt($ch, CURLOPT_POSTFIELDS, $raw_data);
$tsResponse = curl_exec($ch);
if($tsResponse != false) {
$hdaLog .= "\ntsRequest is sent";
} else {
hdaLog("$hdaLog\ncan't send tsRequest, Timestamp failed",'w');
}
//parse ts response
$hexTs = bin2hex($tsResponse);
$tsparse = asn1parse($hexTs);
$tsparse0 = asn1parse($tsparse[0][1]);
if(count($tsparse0 > 1)) { //Remove response status data, only take timeStampToken
$timeStamp = seq($tsparse0[1][1]);
} else {
$timeStamp = seq($tsparse0[0][1]);
}
//Add timestamp to TCPDF Signature
$timeStamp = seq("060B2A864886F70D010910020E".set($timeStamp));
$pkcs7 = int($pa1[0][1]).seq($pa1[1][1]).seq($pa1[2][1]).explicit(0, $pa1[3][1]).seq($pa1[4][1]).oct($pa1[5][1]);
$time = seq($pkcs7.explicit(1,$timeStamp));
$aa=seq(int(1). set($p3[1][1]).seq($p3[2][1]).explicit(0, $p3[3][1]).set($time));
$hdaSignature = seq("06092A864886F70D010702".explicit(0,($aa)))."0000";
$signature = $hdaSignature;
hdaLog("$hdaLog\nTimestamp Success");
} else {
$hdaLog .= "\nCurl was not loaded, trying to load it...";
if(#dl('php_curl.dll')) {
$hdaLog .= "\nCurl successfully Loaded";
} else {
hdaLog("$hdaLog\nCurl failed to load timestamping failed", 'w');
}
}

How do you access another PHP script in a PHP script?

I have a PHP page that needs to send data to another PHP page during the page execution and receive data back.
Can this be done? If so, how?
Update:
Sorry - meant to say that the second script is on a completely different server and domain.
Like how is Stripe doing it with their PHP option: https://stripe.com/docs/api?lang=php
EDIT
Looking at the Stripe source code, you will see they do use cURL (ApiRequestor.php):
private function _curlRequest($meth, $absUrl, $headers, $params, $myApiKey)
{
$curl = curl_init();
$meth = strtolower($meth);
$opts = array();
if ($meth == 'get') {
$opts[CURLOPT_HTTPGET] = 1;
if (count($params) > 0) {
$encoded = self::encode($params);
$absUrl = "$absUrl?$encoded";
}
} else if ($meth == 'post') {
$opts[CURLOPT_POST] = 1;
$opts[CURLOPT_POSTFIELDS] = self::encode($params);
} else if ($meth == 'delete') {
$opts[CURLOPT_CUSTOMREQUEST] = 'DELETE';
if (count($params) > 0) {
$encoded = self::encode($params);
$absUrl = "$absUrl?$encoded";
}
} else {
throw new Stripe_ApiError("Unrecognized method $meth");
}
$absUrl = self::utf8($absUrl);
$opts[CURLOPT_URL] = $absUrl;
$opts[CURLOPT_RETURNTRANSFER] = true;
$opts[CURLOPT_CONNECTTIMEOUT] = 30;
$opts[CURLOPT_TIMEOUT] = 80;
$opts[CURLOPT_RETURNTRANSFER] = true;
$opts[CURLOPT_HTTPHEADER] = $headers;
$opts[CURLOPT_USERPWD] = $myApiKey . ':';
$opts[CURLOPT_CAINFO] = dirname(__FILE__) . '/../data/ca-certificates.crt';
if (!Stripe::$verifySslCerts)
$opts[CURLOPT_SSL_VERIFYPEER] = false;
curl_setopt_array($curl, $opts);
$rbody = curl_exec($curl);
if ($rbody === false) {
$errno = curl_errno($curl);
$message = curl_error($curl);
curl_close($curl);
$this->handleCurlError($errno, $message);
}
$rcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
return array($rbody, $rcode);
}
cURL - from the PHP manual:
PHP supports libcurl, a library created by Daniel Stenberg, that
allows you to connect and communicate to many different types of
servers with many different types of protocols. libcurl currently
supports the http, https, ftp, gopher, telnet, dict, file, and ldap
protocols. libcurl also supports HTTPS certificates, HTTP POST, HTTP
PUT, FTP uploading (this can also be done with PHP's ftp extension),
HTTP form based upload, proxies, cookies, and user+password
authentication.
<?php
/* http://localhost/upload.php:
print_r($_POST);
print_r($_FILES);
*/
$ch = curl_init();
$data = array('name' => 'Foo', 'file' => '#/home/user/test.png');
curl_setopt($ch, CURLOPT_URL, 'http://localhost/upload.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_exec($ch);
?>
Use include('script2.php') from script1.php
Then you can call the functions within script2.php (assuming they have global scope) from script1.php.
The other possibility if you want to call a PHP script like the end user via URL's, cURL is a good tool to know about.
http://php.net/manual/en/book.curl.php

Gotomeeting php api(oauth) implementation

I am trying to create a php gotomeating api implementation. I successfully got the access_token but for any other requests I get error responses. This is my code:
<?php
session_start();
$key = '#';
$secret = '#';
$domain = $_SERVER['HTTP_HOST'];
$base = "/oauth/index.php";
$base_url = urlencode("http://$domain$base");
$OAuth_url = "https://api.citrixonline.com/oauth/authorize?client_id=$key&redirect_uri=$base_url";
$OAuth_exchange_keys_url = "http://api.citrixonline.com/oauth/access_token?grant_type=authorization_code&code={responseKey}&client_id=$key";
if($_SESSION['access_token']) CreateForm();else
if($_GET['send']) OAuth_Authentication($OAuth_url);
elseif($_GET['code']) OAuth_Exchanging_Response_Key($_GET['code'],$OAuth_exchange_keys_url);
function OAuth_Authentication ($url){
$_SESSION['access_token'] = false;
header("Location: $url");
}
function CreateForm(){
$data = getURL('https://api.citrixonline.com/G2M/rest/meetings?oauth_token='.$_SESSION['access_token'],false);
}
function OAuth_Exchanging_Response_Key($code,$url){
if($_SESSION['access_token']){
CreateForm();
return true;
}
$data = getURL(str_replace('{responseKey}',$code,$url));
if(IsJsonString($data)){
$data = json_decode($data);
$_SESSION['access_token'] = $data->access_token;
CreateForm();
}else{
echo 'error';
}
}
/*
* Helper functions
*/
/*
* checks if a string is json
*/
function IsJsonString($str){
try{
$jObject = json_decode($str);
}catch(Exception $e){
return false;
}
return (is_object($jObject)) ? true : false;
}
/*
* CURL function to get url
*/
function getURL($url,$auth_token = false,$data=false){
// Initialize session and set URL.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
// Set so curl_exec returns the result instead of outputting it.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
if($auth_token){
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: OAuth oauth_token='.$auth_token));
}
if($data){
curl_setopt($ch, CURLOPT_POST,true);
$d = json_encode('{ "subject":"test", "starttime":"2011-12-01T09:00:00Z", "endtime":"2011-12-01T10:00:00Z", "passwordrequired":false, "conferencecallinfo":"test", "timezonekey":"", "meetingtype":"Scheduled" }');
echo implode('&', array_map('urlify',array_keys($data),$data));
echo ';';
curl_setopt($ch, CURLOPT_POSTFIELDS,
implode('&', array_map('urlify',array_keys($data),$data))
);
}
// Get the response and close the channel.
$response = curl_exec($ch);
/*
* if redirect, redirect
*/
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($code == 301 || $code == 302) {
preg_match('/<a href="(.*?)">/', $response, $matches);
$newurl = str_replace('&','&',trim(array_pop($matches)));
$response = getURL($newurl);
} else {
$code = 0;
}
curl_close($ch);
return $response;
}
function urlify($key, $val) {
return urlencode($key).'='.urlencode($val);
}
to start the connect process you need to make a request to the php file fith send=1. I tryed diffrent atempts to get the list of meetings but could not get a good response.
Did anybody had prev problems with this or know of a solution for this?
Edit:
This is not a curl error, the server responds with error messages, in the forums from citrix they say it should work, no further details on why it dosen't work, if I have a problem with the way I implemented the oauth or the request code. The most comon error I get is: "error code:31305" that is not documented on the forum.
[I also posted this on the Citrix Developer Forums, but for completeness will mention it here as well.]
We are still finalizing the documentation for these interfaces and some parameters which are written as optional are actually required.
Compared to your example above, changes needed are:
set timezonekey to 67 (Pacific time)
set passwordrequired to false
set conferencecallinfo to Hybrid (meaning: both PSTN and VOIP will be provided)
Taking those changes into account, your sample data would look more like the following:
{"subject":"test meeting", "starttime":"2012-02-01T08:00:00",
"endtime":"2012-02-01T09:00:00", "timezonekey":"67",
"meetingtype":"Scheduled", "passwordrequired":"false",
"conferencecallinfo":"Hybrid"}
You can also check out a working PHP sample app I created: http://pastebin.com/zE77qzAz

Categories