When making requests in Guzzle you can use this to set username and password:
$request->setAuth($username, $password);
This worked great for my single requests. Now I need to make a set of parallel requests and I don't exactly know how I should set this. I have already set auth and my Authorization headers for both my single and parallel requests, and like I said, the single works because I can set $request->setAuth(). How can I set setAuth() for a parallel request, or is there something else I need to use?
EDIT Here is my code.
$client = new Client('https://service.example.com/');
$username = 'username';
$password = 'password';
$auth = base64_encode($username . ":" . $password);
$dm = $_POST['domains'];
$domains = explode("\n", $dm);
$client->setDefaultOption('auth', array($username, $password, 'Any'));
$options = array(
'query' => array(
'unit'=> 'y',
'period' => $_POST['period'],
'password' => urlencode($_POST['password']),
'registrant' => 'abcdefg-00004'
),
'headers' => array(
'Authorization' => 'Basic '.$auth,
'Accept' =>'application/hal+json',
'Access-Control-Allow-Origin' => '*'
),
'auth' => array($username, $password, 'Basic'),
'timeout' => '30',
'connect_timeout' => '10',
'cookies' => array('cert_url' => 'https://url.tocert.com/cert/su82jhdea3df5e81cd2cs8ejrae621b3a475312vd'),
'verify' => true,
'debug' => true,
);
$requests = array();
foreach($domains as $d){
$requests[] = $client->post($_POST['server-name'].'/domain?method=POST&callback=?&name='.$d, array(), $options);
}
//Do it
try {
$bulk_create = $client->send($requests);
foreach($bulk_create as $create){
echo $create->getBody();
}
} catch (MultiTransferException $e) {
echo "The following exceptions were encountered:\n";
foreach ($e as $exception) {
echo $exception->getMessage() . "\n";
}
echo "The following requests failed:\n";
foreach ($e->getFailedRequests() as $request) {
echo $request . "\n\n";
}
echo "The following requests succeeded:\n";
foreach ($e->getSuccessfulRequests() as $request) {
echo $request . "\n\n";
}
}
Related
Hi Stackoverflow community,
I am attempting to implement the "convertPaymentMethodToToken" method from USAePay soap api documentations. For the function to work, it is required to fetch the customer number from the UsaEpay acct, and it generates a Method ID through a "getCustomer" request, that will be used for the conversion. However, the implementation works only for a single customer and fails when I try to process multiple customers at once. The error message I receive is: "An error occurred while fetching details of customer 'customer1': 40030: Customer Not Found......".
I have a large customer database of over 20,000 customers, and my goal is to convert each of their payment methods to tokens efficiently, without having to perform individual conversions for each customer. The USAePay documentation only provides information on how to implement the feature for a single customer.
here is my code by getting Method ID for a single customer
<?php
$wsdl = "https://secure.usaepay.com/soap/gate/INBGTWZC/usaepay.wsdl";
$sourceKey = "your soruce key";
$pin = "1234";
function getClient($wsdl) {
return new SoapClient($wsdl, array(
'trace' => 1,
'exceptions' => 1,
'stream_context' => stream_context_create(
array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
)
)
));
}
function getToken($sourceKey, $pin) {
$seed = time() . rand();
return array(
'SourceKey' => $sourceKey,
'PinHash' => array(
'Type' => 'sha1',
'Seed' => $seed,
'HashValue' => sha1($sourceKey . $seed . $pin)
),
'ClientIP' => $_SERVER['REMOTE_ADDR']
);
}
$client = getClient($wsdl);
$token = getToken($sourceKey, $pin);
try {
$custnum='customer number';
print_r($client->getCustomer($token,$custnum));
} catch (Exception $e) {
// Code to handle the exception
echo "An error occurred: " . $e->getMessage();
}
?>
and here the successful response I get back (with the Method ID included)
Successful response.
here Is the code I'm trying it to do with multiple customers
<?php
$wsdl = "https://sandbox.usaepay.com/soap/gate/43R1QPKU/usaepay.wsdl";
$sourceKey = "your api key";
$pin = "1234";
function getClient($wsdl) {
return new SoapClient($wsdl, array(
'trace' => 1,
'exceptions' => 1,
'stream_context' => stream_context_create(
array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
)
)
));
}
function getToken($sourceKey, $pin) {
$seed = time() . rand();
return array(
'SourceKey' => $sourceKey,
'PinHash' => array(
'Type' => 'sha1',
'Seed' => $seed,
'HashValue' => sha1($sourceKey . $seed . $pin)
),
'ClientIP' => $_SERVER['REMOTE_ADDR']
);
}
$client = getClient($wsdl);
$token = getToken($sourceKey, $pin);
$custnums = array();
for ($i = 1; $i <= 3; $i++) {
$custnums[] = 'customer' . $i;
}
$methodIDs = array();
foreach ($custnums as $custnum) {
try {
$result = $client->getCustomer($token, $custnum);
$methodID = $result[0]->MethodID;
$methodIDs[] = $methodID;
error_log("Method ID for customer $custnum: $methodID");
} catch (Exception $e) {
echo " An error occurred: " . $e->getMessage();
}
}
?>
I've already been working on it all day,
Can anyone help me with this?
Thanks in advance
How can I use the SoapClient with the method "sites_web_domain_add" to interact with the ispconfig api? My Code produces a folowing error:
error
Also soap client/server is set to enabled.
If i execute the code in my terminal it just works fine but not in my controller, so have I missed something? Like importing the right soap?
Thanks for helping!
$username = 'apiuser';
$password = '1234';
$soap_location = 'https://localhost:8080/remote/index.php';
$soap_uri = 'https://localhost:8080/remote/';
$context = stream_context_create(
[
'ssl' => [
'verify_peer' => false,
'verify_peer_name' => false,
]
]
);
$client = new SoapClient(
null,
[
'location' => $soap_location,
'uri' => $soap_uri,
'trace' => 1,
'exceptions' => 1,
'stream_context' => $context
]
);
try {
if ($session_id = $client->login($username, $password)) {
echo "Login successful. Session ID: $session_id<br>";
}
//* Set the function parameters.
$client_id = 1;
$params = [
'server_id' => 1,
'ip_address' => '*',
'domain' => 'test2.int',
'type' => 'vhost', // vhost | alias | vhostalias | subdomain | vhostsubdomain
];
$client->sites_web_domain_add($session_id, $client_id, $params, $readonly = false);
if ($client->logout($session_id)) {
echo "Logged out.<br>";
}
} catch (SoapFault $e) {
echo $client->__getLastResponse();
die("SOAP Error: {$e->getMessage()}");
}
I have created a function that contacts a remote API using Guzzle but I cannot get it to return all of the data available.
I call the function here:
$arr = array(
'skip' => 0,
'take' => 1000,
);
$sims = api_request('sims', $arr);
And here is the function, where I have tried the following in my $response variable
json_decode($x->getBody(), true)
json_decode($x->getBody()->getContents(), true)
But neither has shown any more records. It returns 10 records, and I know there are over 51 available that it should be returning.
use GuzzleHttp\Client;
function api_request($url, $vars = array(), $type = 'GET') {
$username = '***';
$password = '***';
//use GuzzleHttp\Client;
$client = new Client([
'auth' => [$username, $password],
]);
$auth_header = 'Basic '.$username.':'.$password;
$headers = ['Authorization' => $auth_header, 'Content-Type' => 'application/json'];
$json_data = json_encode($vars);
$end_point = 'https://simportal-api.azurewebsites.net/api/v1/';
try {
$x = $client->request($type, $end_point.$url, ['headers' => $headers, 'body' => $json_data]);
$response = array(
'success' => true,
'response' => // SEE ABOVE //
);
} catch (GuzzleHttp\Exception\ClientException $e) {
$response = array(
'success' => false,
'errors' => json_decode($e->getResponse()->getBody(true)),
);
}
return $response;
}
By reading the documentation on https://simportal-api.azurewebsites.net/Help/Api/GET-api-v1-sims_search_skip_take I assume that the server is not accepting your parameters in the body of that GET request and assuming the default of 10, as it is normal in many applications, get requests tend to only use query string parameters.
In that function I'd try to change it in order to send a body in case of a POST/PUT/PATCH request, and a "query" without json_encode in case of a GET/DELETE request. Example from guzzle documentation:
$client->request('GET', 'http://httpbin.org', [
'query' => ['foo' => 'bar']
]);
Source: https://docs.guzzlephp.org/en/stable/quickstart.html#query-string-parameters
I am trying to send a request to RingCentral API. The link to documentation is https://developers.ringcentral.com/api-reference/Fax/createFaxMessage If I don't specify faxResolution or coverIndex everything goes well, fax could be sent. But if I add faxResolution param like in the code below, I receive error "Parameter [faxResolution] value is invalid", "errorCode" : "CMN-101". The same thing with coverIndex param. My client is GuzzleHttp 6.3
$token = $this->ringcentral->platform()->auth()->data()['access_token'];
$a = array();
foreach ($destination_numbers as $number) {
$a[] = [
'name' => 'to',
'contents' => $number,
'headers' => ['Content-Type' => 'multipart/form-data']
];
}
$a[] = [
'name' => 'faxResolution',
'contents' => 'High',
'headers' => ['Content-Type' => 'multipart/form-data']
];
foreach ($attachments as $attachment) {
$file_pointer = fopen($attachment, 'r');
$mime = mime_content_type($attachment);
$a[] = [
'name' => 'attachment',
'contents' => $file_pointer,
'headers' => ['Content-Type' => $mime]
];
}
$client = new Client();
try {
$response = $client->request('POST', url(config('services.ringcentral.app_url')) . '/restapi/v1.0/account/~/extension/~/fax', [
'headers' => [
'Accept' => 'application/json',
'Authorization' => 'Bearer ' . $token
],
'multipart' => $a
]);
$response = json_decode($response->getBody(), true);
} catch (\GuzzleHttp\Exception\ClientException $e) {
echo($e->getResponse()->getBody()->getContents());
}
Here's what RingCentral suggests when using PHP. I included all of what they suggested, but just look at the part about faxResolution (2/3 of the way down)
<?php
// https://developers.ringcentral.com/my-account.html#/applications
// Find your credentials at the above url, set them as environment variables, or enter them below
// PATH PARAMETERS
$accountId = '<ENTER VALUE>';
$extensionId = '<ENTER VALUE>';
$recipient = '<ENTER VALUE>';
require('vendor/autoload.php');
$rcsdk = new RingCentral\SDK\SDK(getenv('clientId'), getenv('clientSecret'), getenv('serverURL'));
$platform = $rcsdk->platform();
$platform->login(getenv('username'), getenv('extension'), getenv('password'));
$request = $rcsdk->createMultipartBuilder()
->setBody(array(
'to' => array(array('phoneNumber' => $recipient)),
'faxResolution' => 'High',
))
->add(fopen('fax.jpg', 'r'))
->request("/restapi/v1.0/account/{$accountId}/extension/{$extensionId}/fax");
$r = $platform->sendRequest($request);
?>
In my wp project, I am using Assently for e-signature implementation. Though I have an account and created a pdf form file to be filled by the user I just am not able to proceed a bit. I am finding documentation not clear.
Also, I am not clear about what needs to be done so that the user will be shown form to process the transaction.
So, any help/suggestions to proceed forward is appreciated.
I have tried the following based on assently-laravel. But it's asking me to login. What is an error here?
Code:
define('ASSENTLY_DEBUG', true);
define('ASSENTLY_KEY', 'key');
define('ASSENTLY_SECRET', 'secret-generated');
include_once('assently/Assently.php');
$assently = new Assently();
$assently->authenticate(ASSENTLY_KEY, ASSENTLY_SECRET);
$url = 'https://test.assently.com/api/v2/createcasefromtemplate';
$default = array(
'Id' => '5a0e0869-' . rand(1111, 9999) . '-4b79-' . rand(1111, 9999) . '-466ea5cca5ce'
);
$data = array(
'auth' => $assently->auth(),
'templateId' => '0e004e2b-b192-4ce2-8f47-d7a4576d7df6',
'newCaseId' => '5a0e0869-' . rand(1111, 9999) . '-4b79-' . rand(1111, 9999) . '-466ea5cca5ce',
'agentUsername' => ''
);
$data = array(
'json' => $data
);
$options = array(
'http' => array(
'header' => "Content-type: application/json; charset=utf-8\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
echo '<pre>';
print_r($result);
die;
create this class inside assently folder
use Assently\AssentlyCase;
use Exception;
class CustomAssentlyCase extends AssentlyCase
{
public function createFromTemplate($data)
{
$default = [
'newCaseId' => '5a0e0869-'.rand(1111, 9999).'-4b79-'.rand(1111, 9999).'-466ea5cca5ce'
];
$json = array_merge($default, $data);
try{
$response = $this->client->post($this->url('createcasefromtemplate'), [
'auth' => $this->assently->auth(),
'json' => $json
]);
}catch(Exception $e){
print_r($e->getMessage());
}
return $response;
}
}
Use
define('ASSENTLY_DEBUG', true);
define('ASSENTLY_KEY', 'key');
define('ASSENTLY_SECRET', 'secret-generated');
include_once('assently/Assently.php');
include_once('assently/CustomAssentlyCase.php');
$assently = new Assently();
$assently->authenticate(ASSENTLY_KEY, ASSENTLY_SECRET);
$data = array(
'templateId' => '0e004e2b-b192-4ce2-8f47-d7a4576d7df6',
'newCaseId' => '5a0e0869-'.rand(1111, 9999).'-4b79-'.rand(1111, 9999).'-466ea5cca5ce',
'agentUsername' => 'agentUsername' // PUT your agent username here it is required
);
$customAssentlyCase = new CustomAssentlyCase($assently);
$result = $customAssentlyCase->createFromTemplate($data);
print_r($result);
Try this, though not tested but should work. Good luck.