mardi 29 novembre 2016

C# - Woocommerce API error Unauthorized on server

I trying to use WooCommerce.NET library in my Web MVC api application to call Woocommerce's API. I've wrote some php code in class-wc-api-customers.php file of Woocommerce to make more an API which allow authenticate user login from third party system (here is my Web MVC api application). Here is php code which I added into class-wc-api-customers.php file :

1.Register router

# GET /customers/login/<usernamepass> 
$routes[ $this->base . '/login/(?P<usernamepass>.+)' ] = array( array( array( $this, 'login_customer' ), WC_API_SERVER::READABLE ), );

2. login_customer function:

public function login_customer($usernamepass) {

        list($username, $password) = split('[-]', $usernamepass);   

// Checks the username.
if ( ! isset( $username) ) {
    return new WP_Error( 'woocommerce_api_missing_customer_username', sprintf( __( 'Missing parameter %s', 'woocommerce' ), 'username' ), array( 'status' => 400 ) );
}

// Checks the password.
if ( ! isset( $password) ) {
    return new WP_Error( 'woocommerce_api_missing_customer_password', sprintf( __( 'Missing parameter %s', 'woocommerce' ), 'password' ), array( 'status' => 400 ) );
}

// Attempts to login customer
$credentials = array();
$credentials['user_login'] = $username;
$credentials['user_password'] = $password;
$credentials['remember'] = true;
$user = wp_signon( $credentials, false );

// Checks for an error in the customer login.
if ( is_wp_error( $user) ) {
    return new WP_Error( 'woocommerce_api_cannot_login_customer', $user->get_error_message(), array( 'status' => 400 ) );
}

do_action( 'woocommerce_api_login_customer', $user );

$this->server->send_status( 201 );

return $this->get_customer( $user->ID );}

And I wrote a method LoginCustomers inside WCObject class of WooCommerce.NET library. Here is code :

public async Task LoginCustomers(string username, string password, Dictionary<string, string> parms = null){
    string json =  await API.SendHttpClientRequest("customers/login/" + username +"-"+password, RequestMethod.GET, string.Empty, parms);
    return json;}

Here is code of SendHttpClientRequest method :

public async Task SendHttpClientRequest(string endpoint, RequestMethod method, T requestBody, Dictionary<string, string> parms = null){

    HttpWebRequest httpWebRequest = null; 
    try 
    { 
        string requestUrl = GetOAuthEndPoint(method.ToString(), endpoint, parms); 
        string responseString = ""; 
        using (var client = new HttpClient()) 
        { 
            client.BaseAddress = new Uri(wc_url); 
            client.DefaultRequestHeaders.Accept.Clear(); 
            client.DefaultRequestHeaders.Accept.Add(new       MediaTypeWithQualityHeaderValue("application/json")); 
            var response = client.GetAsync(requestUrl).Result; 
            responseString = response.ReasonPhrase; 
            if (response.IsSuccessStatusCode) 
            { 
                 responseString = response.Content.ReadAsStringAsync().Result; 
            } 
        } 
        return responseString; 
    } 
    catch (WebException we) 
    { 
        if (httpWebRequest != null && httpWebRequest.HaveResponse) 
            if (we.Response != null) 
                throw new Exception(await GetStreamContent(we.Response.GetResponseStream(), we.Response.ContentType.Split('=')[1])); 
            else 
                throw we; 
        else 
            throw we; 
    } 
    catch (Exception e) 
    { 
        return e.Message; 
    } 
}

And here is code which I wrote to call that API from my Web MVC api application :

public async Task getWoocommerceCustomer(string uEmail, string uPassword)

{
    try
    {
        RestAPI rest = new RestAPI("http://ift.tt/2gFKSGc", "ck_xxx", "cs_xxx");
        WooCommerceNET.WooCommerce.Legacy.WCObject wc = new WooCommerceNET.WooCommerce.Legacy.WCObject(rest);
        string s = await wc.LoginCustomers(uEmail, uPassword);
        LogWriter.WriteLog("getWoocommerceCustomer s = " + s);
        return s;
    }
    catch (NullReferenceException e)
    {
        String ex = e.ToString();
        return null;
    }
}

When I run my application in debug mode, I got the json object which received from Woocommerce system by login_customer API which I wrote on Woocommerce when I used correct account and password as below :

{ "customer":{
      "id":3,
      "created_at":"2016-08-30T18:55:27Z", "last_update":"2016-11-26T13:22:00Z",
      "email":"customerregistered@gmail.com",
      "first_name":"Acid",
      "last_name":"Burn",
      "username":"acidburn",
      "role":"administrator",
      "last_order_id":null,
      "last_order_date":null,
      "orders_count":0,
      "total_spent":"0.00",
      "avatar_url":"http:\/\/0.gravatar.com\/avatar\/?s=96",
      "billing_address":{
                        "first_name":"",
                        "last_name":"",
                        "company":"",
                        "address_1":"",
                        "address_2":"",
                        "city":"",
                        "state":"",
                        "postcode":"",
                        "country":"",
                        "email":"",
                        "phone":""
                       },
      "shipping_address":{
                        "first_name":"",
                        "last_name":"",
                        "company":"",
                        "address_1":"",
                        "address_2":"",
                        "city":"",
                        "state":"",
                        "postcode":"",
                        "country":""
                        }
              }

}

I've set up, config IIS and deploy a server version on my computer from dll files which be generated by publish my application process. Then use Postman tool to call API. It got same result as above.

But when I deploy that files (dll files) to my server (VPS - I used Window Server 2012 R2). My API not work correctly, it always return Unauthorized even when I entered correct account and password.

Because server version on my computer, it work well for that API, So I think the difference of timezones not might cause my problems. My Window Server on VSP already installed .NET framework 4.5 and I tried to config some security option in Internet Explore on my Server to make Internet Explore possible connected to Woocommerce website. But my API still not work correctly.

I don't know why it work wrong. Someone has some idea for my problems ? please kindly help me. I am very grateful for that !




Aucun commentaire:

Enregistrer un commentaire