PHP Developer

Wednesday, 20 June 2018

Rest API

$siteurl = site_url();
$baseuri = $siteurl."/wp-json";
$method = $request->get_method();
$body = $request->get_body();
$route = $request->get_route();
$params = json_encode($request->get_params());
$fullapiurl = $baseuri.$route;
$ctype = $request->get_content_type();
$contentType = isset($ctype)?$ctype['value']:'application/json';
$url = parse_url($siteurl);

$route == "/wc/v2/login";


//authenication method over http
            $oauthTimestamp = time();
            $nonce = md5(mt_rand());
            $oauthSignatureMethod = "HMAC-SHA1";
            $oauthVersion = "1.0";

            $sigBase = $method."&" . rawurlencode($fullapiurl) . "&"
                . rawurlencode("oauth_consumer_key=" . rawurlencode($consumer_key)
                . "&oauth_nonce=" . rawurlencode($nonce)
                . "&oauth_signature_method=" . rawurlencode($oauthSignatureMethod)
                . "&oauth_timestamp=" . $oauthTimestamp
                . "&oauth_version=" . $oauthVersion);

            $sigKey = $consumer_secret . "&";
            $oauthSig = base64_encode(hash_hmac("sha1", $sigBase, $sigKey, true));

            $requestUrl = $fullapiurl . "?"
                . "oauth_consumer_key=" . rawurlencode($consumer_key)
                . "&oauth_nonce=" . rawurlencode($nonce)
                . "&oauth_signature_method=" . rawurlencode($oauthSignatureMethod)
                . "&oauth_timestamp=" . rawurlencode($oauthTimestamp)
                . "&oauth_version=" . rawurlencode($oauthVersion)
                . "&oauth_signature=" . rawurlencode($oauthSig);

$ch = curl_init($requestUrl);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $httpMethod = strtolower($method);
    if($httpMethod == "post"){           
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $body);       
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                        'Content-Type: '.$contentType,
                       'Content-Length: ' . strlen($body))
         );
    }   
    else{
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);       
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                        'Content-Type: '.$contentType)
         );
    }
   
    $response = curl_exec($ch);
    if(curl_errno($ch)) {
      echo 'Curl error: ' . curl_error($ch);
    }
    curl_close($ch);

No comments:

Post a Comment