一步一步oAuth休息C#winform例子

jer*_*ass 9 c# oauth magento winforms

我已经尝试了一段时间,需要从头开始逐步找到为magento创建一个消费者应用程序.

我看过以下内容:

还有很多其他人,但目前还不清楚该怎么做.我需要的是在C#中进行winform,需要使用其余的api与oAuth进行magento.真的在这里我有点失落.

真的,我作为消费者获得的信息是

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";
Run Code Online (Sandbox Code Playgroud)

"liconnect://成功"; 是要通过一些通行证,但我没有得到那么多大声笑...

oauth_token和oauth_token_secret需要保存,所以我不知道是否可以存储?但是如果你不知道magento路径那么你必须登录..我尝试用HtmlAgilityPack构建一个刮刀并且一直到登录表单但是你甚至通过了表格中的所有内容page magento认为存在问题.我猜对标题做了..所以去那条路线没有用.

我也尝试过做一个帖子并使用System.Security.Cryptography,但是还没有成功.

问题: *任何疯狂的程序员都会有一个坚实的"如何"或想要接受挑战的人在这里为人们服务?*有很多人在这里问同样的问题.


UPDATE

好吧,对于那些似乎无法解决这个问题的人来说,还有很长的路要走.所以我编写了一个执行身份验证的php脚本,并将其存储在隐藏的文件中.然后我创建了一个登录,这是您使用C#winform获得的.所以..一个简单的例子,但注意这只是一个例子,因为你应该检查代理并加盐后期数据以增加安全性.第一次你需要直接进入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";
}
?>
Run Code Online (Sandbox Code Playgroud)

现在在另一边.. Form1.cs中的C#(你的事件方法在哪里)

    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();
    }
Run Code Online (Sandbox Code Playgroud)

你去吧 现在,您可以通过安全的方式从C#winfrom连接到magento api,这将永远(如果您添加盐和代理调整)到hack.我仍然想要一种方法来做到这一点但是......这很有效.

Typ*_*ist 2

您可以选择混合这两种资源来获得解决方案。

这个示例适用于 Windows Phone 7,只需稍作更改即可在 win 表单应用程序中使用(尽管我不敢尝试),并且您必须注意Megneto API 。

Windows Phone 7 示例是 Twitter,应该能够通过更改 Magneto 的 oauth 流 url 进行自定义