POST request using guzzle6 with pfx-certificate - guzzle6

Is it possible to create a POST request using guzzle6 which has .pfx-certificate attached to it?
The documention only mentions pem-format: http://docs.guzzlephp.org/en/stable/request-options.html#cert

Although the documentation at http://docs.guzzlephp.org/en/stable/request-options.html#cert doesn't mention it, it seems to be possible to also use pfx-format with guzzle.

PFX certificates are used for "mutual authentications", that means, the PFX is generated with your local private key and the remote public cert.
To generate a PFX key you run:
openssl pkcs12 -inkey your_privkey.pem -in remote_pub.cert -export -out mixed.pfx
To make a request using the PFX cert, you can:
$api = new \GuzzleHttp\Client([
'base_uri' => $baseUrl,
'cert' => 'path/to/mixed.pfx',
'curl' => [CURLOPT_SSLCERTTYPE => 'P12'], // to define it's a PFX key
]);

this will work in drupal 8 too
use GuzzleHttp\Client;
// Base URI is used with relative requests
$client = new Client([
'base_uri' => 'https://www.google.com',
'cert' => 'pathtopfxflie/nameof.pfx',
'curl' => [CURLOPT_SSLCERTTYPE => 'P12']]);
$response = $client->request('METHOD', 'api path',['headers' => ['Employer' => 100]]);
//get status code using $response->getStatusCode();
$body = $response->getBody();
$arr_body = json_decode($body);

Related

PayPal Rest API - End Point Used

In my Dev environment, I can correctly use the Rest API to the sandbox site:
$sdkConfig = array(
"mode" => 'sandbox'
);
$cred = new OAuthTokenCredential(
$SANDBOX_clientId,
$SANDBOX_clientSecret
);
$access_token = $cred->getAccessToken($sdkConfig);
When using the same code with Live Keys and a verified Live account:
$sdkConfig = array(
"mode" => 'live'
);
$cred = new OAuthTokenCredential(
$LIVE_clientId,
$LIVE_clientSecret
);
$access_token = $cred->getAccessToken($sdkConfig);
I get this error:
Http response code 401 when accessing https://api.sandbox.paypal.com/v1/oauth2/token
How does the PayPal REST API know which endpoint to access?
I am not specifying the endpoint in the sandbox or live calls and am not using a bootstrap or ini file. The account is verified and approved.
The best way I would recommend is to create an ApiContext object similar to shown at https://gist.github.com/jaypatel512/a2b037ab5ddc51fa7280
<?php
// 1. Autoload the SDK Package. This will include all the files and classes to your autoloader
require __DIR__ . '/PayPal-PHP-SDK/autoload.php';
// 2. Provide your Secret Key. Replace the given one with your app clientId, and Secret
// https://developer.paypal.com/webapps/developer/applications/myapps
$apiContext = new \PayPal\Rest\ApiContext(
new \PayPal\Auth\OAuthTokenCredential(
'AYSq3RDGsmBLJE-otTkBtM-jBRd1TCQwFf9RGfwddNXWz0uFU9ztymylOhRS', // ClientID
'EGnHDxD_qRPdaLdZz8iCr8N7_MzF-YHPTkjs6NKYQvQSBngp4PTTVWkPZRbL' // ClientSecret
)
);
// Step 2.1 : Between Step 2 and Step 3
$apiContext->setConfig(
array(
'mode' => 'live',
'log.LogEnabled' => true,
'log.FileName' => 'PayPal.log',
'log.LogLevel' => 'FINE'
)
);
// 3. Lets try to save a credit card to Vault using Vault API mentioned here
// https://developer.paypal.com/webapps/developer/docs/api/#store-a-credit-card
$creditCard = new \PayPal\Api\CreditCard();
$creditCard->setType("visa")
->setNumber("4417119669820331")
->setExpireMonth("11")
->setExpireYear("2019")
->setCvv2("012")
->setFirstName("Joe")
->setLastName("Shopper");
// 4. Make a Create Call and Print the Card
try {
$creditCard->create($apiContext);
echo $creditCard;
}
catch (\PayPal\Exception\PayPalConnectionException $ex) {
echo $ex;
}

Bad file descriptor in Net::LDAP::Bind

I am establishing the following LDAP connection with Net::LDAP:
my $ldap = Net::LDAP->new( $ldap_host, version => 3 );
my $mesg = $ldap->start_tls(
verify => 'none',
);
$mesg = $ldap->bind( $dn, password => $ldappass );
This will work, and even let me make a query later to check a user's credentials.
But if I try to verify server certificate:
my $ldap = Net::LDAP->new( $ldap_host, version => 3 );
my $mesg = $ldap->start_tls(
verify => 'require',
cafile => '/var/certs/Certificate_Bundle.pem'
);
$mesg = $ldap->bind( $dn, password => $ldappass );
It will successfully establish the connection and verify the server certificate, but while trying the Bind operation I get the following LDAP message parameters:
'resultCode' => 82,
'pdu' => '0O`J3cn=foo1,ou=foo2,dc=foo3Passwd',
'errorMessage' => 'Bad file descriptor'
I'm surprised because result code 82 is defined as LDAP_LOCAL_ERROR, but all the certificate bit seems to work. If I change the 'cafile' parameter to a wrong value, it will fail with a 'I/O Error Connection reset by peer' error message.
Any ideas? Thanks in advance.
UPDATE: I just realized that the certificate verification was not being successful. The LDAP server was using other certificate than the one I had been told. I realized that by using openssl to monitor the handshaking process:
openssl s_client -connect *server:port* -showcerts -state
and there you can see the certificate that the server is effectively using.

Linkedin OAuth and Zend retrieving Acces Token returns 'Error in HTTP request'

Answer + new question
I found out that the code below works just fine on a LIVE server. LinkedIN blocked all requests from localhost.
That established; Does anybody know how to test an application from localhost with LinkedIN OAuth? Because doing this on a live server sucks!
Old Question
I'm trying to connect with Zend_OAuth to LinkedIN. This code used to work, but now it returns an error in http request while I'm trying to retrieve an access token.
Tried checking the LinkedIN api, but the code still seems valid. Tried several scripts but all with the same result.
The config is setup in the preDispatch of my controller
$this->configLinkedin = array(
'version' => '1.0',
'siteUrl' => 'http://'.$_SERVER['HTTP_HOST'].$this->view->baseUrl(false).'/news/index/connectlinkedin',
'callbackUrl' => 'http://'.$_SERVER['HTTP_HOST'].$this->view->baseUrl(false).'/news/index/connectlinkedin',
'requestTokenUrl' => 'https://api.linkedin.com/uas/oauth/requestToken',
'userAuthorisationUrl' => 'https://api.linkedin.com/uas/oauth/authorize',
'accessTokenUrl' => 'https://api.linkedin.com/uas/oauth/accessToken',
'consumerKey' => 'XXX',
'consumerSecret' => 'XXX'
);
And the code in the action to connect to linkedIN is
$this->consumer = new Zend_Oauth_Consumer($this->configLinkedin);
if(!empty($_GET) && isset($_SESSION['LINKEDIN_REQUEST_TOKEN']))
{
$token = $this->consumer->getAccessToken($_GET, unserialize($_SESSION['LINKEDIN_REQUEST_TOKEN']));
// Use HTTP Client with built-in OAuth request handling
$client = $token->getHttpClient($this->configLinkedin);
// Set LinkedIn URI
$client->setUri('https://api.linkedin.com/v1/people/~:(id,first-name,last-name,picture-url)');
// Set Method (GET, POST or PUT)
$client->setMethod(Zend_Http_Client::GET);
// Get Request Response
$response = $client->request();
$this->NewsService->TokenSocialMedia(
$token,
'linkedin',
serialize($response->getBody())
);
$_SESSION['LINKEDIN_REQUEST_TOKEN'] = null;
$this->_helper->flashMessenger(array('message' => $this->view->translate('The CMS is successfully connected to your linkedin account'), 'status' => 'success'));
$this->_helper->redirector('settings#settingSocial', 'index');
}
else
{
$token = $this->consumer->getRequestToken();
$_SESSION['LINKEDIN_REQUEST_TOKEN'] = serialize($token);
$this->consumer->redirect();
}
What am I missing or doing wrong? I use a similair setup for Twitter and that works fine.
UPDATE 20 September 211
I found out that this rule is returning the error:
$token = $this->consumer->getRequestToken();
I'm still clueless why, and reading the linkedin api doesn't help a bit. Will keep you posted.
I got similar problem and after adding openssl extension it was solved
try adding to php.ini this line:
extension=php_openssl.dll
I got the same issue, try to turn off ssl before asking the new consumer :
$httpConfig = array(
'adapter' => 'Zend\Http\Client\Adapter\Socket',
'sslverifypeer' => false
);
$httpClient = new HTTPClient(null, $httpConfig);
OAuth::setHttpClient($httpClient);

Google Latitude and OAuth Signed requests

I've written a script that authenticates against Google's OAuth API for Latitude, using Net::OAuth. It correctly authenticates (as I can successfully fetch data out of the API). However, when I try to add an historical entry, I get a 401 Unknown authorization header response. I'm using the following code:
my $location_data = $json->encode(\%data);
$request = Net::OAuth->request("protected resource")->new(
consumer_key => $c_key,
consumer_secret => $c_secret,
token => $token,
token_secret => $token_secret,
verifier => $verifier,
request_url => 'https://www.googleapis.com/latitude/v1/location',
request_method => 'POST',
signature_method => $s_method,
timestamp => time,
nonce => &nonce(),
extra_params => {
key => $s_key
}
);
$request->sign;
$ua->default_header("Authorization", $request->to_authorization_header);
$ua->default_header("Content-Type", "application/json");
my $res = $ua->post('https://www.googleapis.com/latitude/v1/location?key=' . $s_key,
Content => $location_data);
All of the variables are used in the fetch portion of the API, so I know those are all ok. I'm not sure if I'm using the correct URL to post against, and I've tried what's in the sample above, as well as $request->to_url.
Any suggestions would be greatly appreciated.
After some back and forth with the Latitude API team, it was determined that this error comes from the fact that the Content-Type is not actually being set to application/json. Changing the above code to:
$ua->default_header("Authorization", $request->to_authorization_header);
my $res = $ua->post('https://www.googleapis.com/latitude/v1/location?key=' . $s_key,
'Content-Type' => 'application/json',
Content => $location_data);
And everything works as expected.

Image Upload with Zend_Service_Nirvanix

I can't seem to upload an image using Zend_Service_Nirvanix. Is it even possible?
I have a feeling that my problem has something to do with not being able to figure out how to set the UploadHost on the Transfer Service.
Any help is greatly appreciated! My deadline is July 16th!
Here is my code:
$nirvanix = new Zend_Service_Nirvanix(array('appKey' => $key,
'username' => $user,
'password' => pass));
$NSImfs = $nirvanix->getService('IMFS');
$options = array('sizeBytes' => filesize($source));
$storageNode = $NSImfs->getStorageNode($options);
$NSTransfer = $nirvanix->getService('Transfer');
$options = array('uploadToken' => $storageNode->getStorageNode->UploadToken,
'path' => $original,
'fileData' => file_get_contents($source));
$result = $NSTransfer->uploadFile($options);
Here is the error I keep getting:
Zend_Service_Nirvanix_Exception: XML
could not be parsed from response:
Server Error in '/' Application. The
resource cannot be found. Description:
HTTP 404. The resource you are looking
for (or one of its dependencies) could
have been removed, had its name
changed, or is temporarily
unavailable. Please review the
following URL and make sure that it is
spelled correctly.
Requested URL:
/ws/Transfer/UploadFile.ashx
in
/Applications/MAMP/bin/php5/lib/php/Zend/Service/Nirvanix/Response.php
on line 119
You're getting a 404?
Have you checked for an updated version of that library?
Try going into the libray and changing UploadFile.ashx to UploadFile.aspx. I don't think ashx is not a standard extension.
Maybe that will fix it.
There's a commercial upload tool from Aurigma that has support for file and image upload to Nirvanix. Here's the link (see Uploading to Nirvanix section there) to the help topic to check.
To do a local upload (rather than a web upload via the browser) you just have to call the putContents method passing the files data.
Example:
$nirvanix = new Zend_Service_Nirvanix(array('appKey' => $key,
'username' => $user,
'password' => pass));
$NSImfs = $nirvanix->getService('IMFS');
$response = $NSImfs->putContents($destination_file_and_path,
file_get_contents($source_file));
if($response->ResponseCode != 0)
{
echo 'Fail!';
}
You would only call GetStorageNode if you want to generate a token to pass a browser the upload token.