逐步使用oAuth rest C#winform示例
我已经尝试了一段时间,现在需要找到一个逐步从地面上创建一个消费者应用程序的magento 我看了以下几点:逐步使用oAuth rest C#winform示例,c#,winforms,magento,oauth,C#,Winforms,Magento,Oauth,我已经尝试了一段时间,现在需要找到一个逐步从地面上创建一个消费者应用程序的magento 我看了以下几点: 还有很多其他的,但不清楚该怎么做。我需要这样做的是在C#中创建一个winform,它将需要在oAuth中使用针对magento的RESTAPI。真的,我有点迷路了 作为消费者,我得到的信息是 String callbackUrl = "liconnect://success"; String temporaryCredentialsRequestUrl = "http://dom
String callbackUrl = "liconnect://success";
String temporaryCredentialsRequestUrl = "http://domain.xxx/oauth/initiate?oauth_callback=" + HttpUtility.UrlEncode(callbackUrl);
String adminAuthorizationUrl = "http://domain.xxx/admin/oauth_authorize";
String accessTokenRequestUrl = "http://domain.xxx/oauth/token";
String apiUrl = "http://domain.xxx/api/rest";
String consumerKey = "KKKKKKKKKKKKKKK";
String consumerSecret = "SSSSSSSSSSSSSSSSSSS";
"liconnect://success"; 是去一些地方,但我也没走那么远,哈哈
oauth_令牌和oauth_令牌密钥需要保存,所以我不知道是否可以从中存储?但是,如果你不知道magento路径,你也必须登录。。我试着用HtmlAgilityPack构建一个刮板,一直到登录表单,但即使是你,我也会将页面上的所有内容传递给表单,magento认为这是个问题。我猜你会对标题做些什么。。因此,走这条路是行不通的
我也试着写一篇文章,然后使用System.Security.Cryptography,但效果并不理想
问题:
*任何一个疯狂的程序员,如果他有一条关于“如何做”的坚实路线,或者想接受挑战,把一条线放在这里给人们看?*有很多人在这里问同样的问题
更新 好吧,对于那些似乎不明白这一点的人来说,有一个解决办法。因此,我编写了一个php脚本来进行身份验证,并将其存储在一个隐藏的文件中。然后,我创建了一个登录名,这就是使用C#winform时的登录名。所以这是一个简单的示例,但请注意,这只是一个示例,因为您应该检查代理并在此处添加post数据以提高安全性。在中的第一次,您需要直接转到php文件,以便获得保存会话的文件 例如:
<?php
/**
* Example of retrieving the products list using Admin account
* via Magento REST API. OAuth authorization is used
* Preconditions:
* 1. Install php oauth extension
* 2. If you were authorized as a Customer before this step, clear browser cookies for 'yourhost'
* 3. Create at least one product in Magento
* 4. Configure resource permissions for Admin REST user for retrieving all product data for Admin
* 5. Create a Consumer
**/
// $callbackUrl is a path to your file with OAuth authentication example for the Admin user
session_start();
//The user name and pass are md5 on the C# side of things and send over like this so it's more then just pass your username and pass
$u="461d544a174bcb5asf2a9fd14576251e169";
$p="c3762e47e025a2e0b6f77afca8da626a81";
if(isset($_POST['username']) && $p == $_POST['pass'] && $u == $_POST['username']){
$callbackUrl = "http://domain.xxx/quick_look.php";
$temporaryCredentialsRequestUrl = "http://domain.xxx/oauth/initiate?oauth_callback=" . urlencode($callbackUrl);
$adminAuthorizationUrl = 'http://domain.xxx/admin/oauth_authorize';
$accessTokenRequestUrl = 'http://domain.xxx/oauth/token';
$apiUrl = 'http://domain.xxx/api/rest';
$consumerKey = 'nar78rw5nlkssddksdflklvkezgdria';
$consumerSecret = 'mo0lnht5;sdf;lsdgjcfdpgad5';
//sodoSess is a folder that is hidden and protected via .htaccess
// note.. secure it or else!!
function write_session($name,$value){
$myFile = "sodoSess/".$name.".txt";
$fh = fopen($myFile, 'w') or die("can't open file sodoSess/".$name.".txt");
fwrite($fh, $value);
fclose($fh);
}
function read_session($name){
$myFile = "sodoSess/".$name.".txt";
$fh = fopen($myFile, 'r') or die("can't open file sodoSess/".$name.".txt");
$data = fgets($fh);
fclose($fh);
return $data;
}
if (!isset($_GET['oauth_token']) && read_session('state') == 1) {
write_session('state',0);
}
try {
$authType = (read_session('state') == 2) ? OAUTH_AUTH_TYPE_AUTHORIZATION : OAUTH_AUTH_TYPE_URI;
$oauthClient = new OAuth($consumerKey, $consumerSecret, OAUTH_SIG_METHOD_HMACSHA1, $authType);
$oauthClient->enableDebug();
if (!isset($_GET['oauth_token']) && read_session('state')=="") {
$requestToken = $oauthClient->getRequestToken($temporaryCredentialsRequestUrl);
write_session('secret',$requestToken['oauth_token_secret']);
write_session('state',1);
header('Location: ' . $adminAuthorizationUrl . '?oauth_token=' . $requestToken['oauth_token']);
exit;
} else if (read_session('state') == 1) {
$oauthClient->setToken($_GET['oauth_token'], read_session('secret'));
$accessToken = $oauthClient->getAccessToken($accessTokenRequestUrl);
write_session('state',2);
write_session('token',$accessToken['oauth_token']);
write_session('secret',$accessToken['oauth_token_secret']);
header('Location: ' . $callbackUrl);
exit;
} else {
$oauthClient->setToken(read_session('token'), read_session('secret'));
//print_r($_POST);
if(isset($_POST["addCustomer"])){
require_once ( "/var/www/html/app/Mage.php" );
umask(0);
Mage::app('default');
$customer = Mage::getModel('customer/customer');
//$customer = new Mage_Customer_Model_Customer();
$password = "321456321456";
$email = $_POST["email"];
$firstname = $_POST["firstname"];
$lastname = $_POST["lastname"];
$street1 = $_POST["street1"];
$street2 = $_POST["street2"];
$city = $_POST["city"];
$postcode = $_POST["postcode"];
$telephone = $_POST["telephone"];
$customer->setWebsiteId(Mage::app()->getWebsite()->getId());
$customer->loadByEmail($email);
//Zend_Debug::dump($customer->debug()); exit;
if(!$customer->getId()) {
$customer->setEmail($email);
$customer->setFirstname($firstname);
$customer->setLastname($lastname);
$customer->setPassword($password);
}
try {
$customer->save();
$customer->setConfirmation(null);
$customer->save();
//Make a "login" of new customer
//Mage::getSingleton('customer/session')->loginById($customer->getId());
echo "added user";
}
catch (Exception $ex) {
//Zend_Debug::dump($ex->getMessage());
}
//Build billing and shipping address for customer, for checkout
$_custom_address = array (
'firstname' => $firstname,
'lastname' => $lastname,
'street' => array (
'0' => $street1,
'1' => $street2,
),
'city' => $city,
'region_id' => '',
'region' => '',
'postcode' => $postcode,
'country_id' => 'US',
'telephone' => $telephone,
);
$customAddress = Mage::getModel('customer/address');
//$customAddress = new Mage_Customer_Model_Address();
$customAddress->setData($_custom_address)
->setCustomerId($customer->getId())
->setIsDefaultBilling('1')
->setIsDefaultShipping('1')
->setSaveInAddressBook('1');
try {
$customAddress->save();
}
catch (Exception $ex) {
//Zend_Debug::dump($ex->getMessage());
}
Mage::getSingleton('checkout/session')
->getQuote()
->setBillingAddress(Mage::getSingleton('sales/quote_address')->importCustomerAddress($customAddress));
//echo $_POST["firstname"]." ".$_POST["lastname"]." <br/>-- ".$_POST["email"]." <br/>MADE IT!";
}else{
/* call class to handle everything */
//for now what is the stock level here?
$resourceUrl = "$apiUrl/products?filter[1][attribute]=sku&filter[1][in]=".$_POST['sku'];
if(isset($_GET['p_id']))$resourceUrl .="/".$_GET['p_id'];
$oauthClient->fetch($resourceUrl, array(), 'GET', array('Content-Type' => 'application/json'));
$productsList = json_decode($oauthClient->getLastResponse());
//print_r($productsList);
foreach($productsList as $item){
$resourceUrl = "$apiUrl/stockitems/".$item->entity_id;
$oauthClient->fetch($resourceUrl, array(), 'GET', array('Content-Type' => 'application/json'));
}
$item = json_decode($oauthClient->getLastResponse());
echo "<h1>currently there is</h1>".round($item->qty);
}
}
} catch (OAuthException $e) {
print_r($e->getMessage());
echo "<br/>";
print_r($e->lastResponse);
}
}else{
echo "fail";
}
?>
您可以选择混合这两种资源来获得解决方案
这是针对WindowsPhone7的,可以在WinForm应用程序中使用,只需稍作更改(尽管我不敢尝试),您必须知道
Windows Phone 7的示例是使用twitter,应该能够通过更改Magnetor的oauth流URL进行自定义您看到这个测试工具了吗-?相信您必须在Winforms/C中执行类似的code
?这个想法/概念应该是一样的。是的,我已经看到了,甚至在我的网站上也有,但这是使用php扩展的php版本。的确,对于winfrom来说,这是一个需要在C#中复制的过程,但是我们回到了我在这里发布的问题。tk代表tryI认为casperOne将此作为一个真正的问题来结束为时过早。这个问题几乎是一样的,有两个很好的答案:我觉得到Wrox代码的链接是我见过的如何在客户端应用程序中执行OAuth的最好例子。我没有silver light访问权限。同样值得一提的是,它和我发布的其他URL一样混乱。我在一步一步地寻找一个清晰的答案。我会试着看看我是否能拿出点什么来,但这方面的评论也不清楚。谢谢你的尝试。
private void button5_Click(object sender, EventArgs e)
{
var myValue = Microsoft.VisualBasic.Interaction.InputBox("What is the sku of the itme you wish to find", "Look product", "");
if (myValue != "") {
sendPost("&sku=" + myValue);
}
}
public void sendPost(String postData) {
//step 1 talk with site
WebRequest req = WebRequest.Create("http://domain.xxx/quick_look.php");
string MainPostData = "username=YOURUSERNAME_MD5&pass=YOURPASSWORD_MD5";
byte[] send = Encoding.Default.GetBytes(MainPostData + (!String.IsNullOrWhiteSpace(postData) ? "&" + postData.TrimStart('&') : ""));
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = send.Length;
//this is where you salt the data by adjusting the header
//then testing for that adjustment
Stream sout = req.GetRequestStream();
sout.Write(send, 0, send.Length);
sout.Flush();
sout.Close();
WebResponse res = req.GetResponse();
StreamReader sr = new StreamReader(res.GetResponseStream());
string returnvalue = sr.ReadToEnd();
HtmlAgilityPack.HtmlDocument hDoc = new HtmlAgilityPack.HtmlDocument();
webBrowser1.Navigate("about:blank");
webBrowser1.Document.OpenNew(true);
webBrowser1.Document.Write("<html><body>" + returnvalue + "</body></html>");
webBrowser1.Stop();
}