An error occurred: 40030: Customer Not Found, using UsaEpay soap API - php

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

Related

How can I use SoapClient in my Php Programm

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()}");
}

Estes Freight Pickup Web Service Basic Authentication

I am trying to create a test pickup request using Estes web services. This particular service requires Basic Authentication using my login credentials. However, I can't seem to figure out how to perform the authentication using PHP and SoapClient. I keep getting the following error:
PHP Fatal error: Uncaught SoapFault exception: [soapenv:Client] [ISS.0088.9164] Access to WSDescriptor estesrtpickup.base.ws.provider.soapws:pickupRequestSSL denied.
My last attempt I tried to pass the credentials into WSDL address, but to no avail. Like so:
$client_pickup = new SoapClient('https://USERNAME:PASSWORD#apitest.estes-express.com/tools/pickup/request/v1.0?wsdl');
Here is my current block of PHP code for the Pickup Webservice:
public static function estesFreightPickupRequest($option) {
self::$ShipToCity = preg_replace("/[^a-zA-Z0-9\s]/", "", $option->ShipToCity);
self::$ShipToStateProvinceCode = preg_replace("/[^a-zA-Z0-9\s]/", "", $option->ShipToStateProvinceCode);
self::$ShipToPostalCode = (string)$option->ShipToPostalCode;
self::$ShipToPostalCode = substr(trim(self::$ShipToPostalCode), 0, 5);
self::$ShipToPostalCode = str_pad(self::$ShipToPostalCode, 5, "0", STR_PAD_LEFT);
self::$ShipToAddressLine = preg_replace("/[^a-zA-Z0-9\s]/", "", $option->ShipToAddressLine);
$Weight = $option->weight;
$d = strtotime("tomorrow");
$request_date = date("Y-m-d", $d);
$path_to_wsdl_pickup = "https://apitest.estes-express.com/tools/pickup/request/v1.0?wsdl";
ini_set("soap.wsdl_cache_enabled", "0");
$client_pickup = new SoapClient('https://USERNAME:PASSWORD#apitest.estes-express.com/tools/pickup/request/v1.0?wsdl');
ini_set("soap.wsdl_cache_enabled", "0");
$header_pickup = new SoapHeader('http://www.estes-express.com/tools/pickup');
$client_pickup->__setSoapHeaders($header_pickup);
//Enter the body data for WSDL
$request_pickup = array(
'requestNumber' => date("Y-m-d"),
'shipper' => array(
'shipperName' => 'COMPANY NAME',
'accountCode' => 'ACCOUNT CODE',
'shipperAddress' => array(
'addressInfo' => array(
'addressLine1' => '1620 TEST CT',
'city' => 'SOMETOWN',
'stateProvince' => 'MO',
'postalCode' => '65222',
'countryAbbrev' => 'US'
)
)
),
'requestAction' => 'LL',
'pickupDate'=> date("Y-m-d"),
'pickupStartTime' => '1200',
'pickupEndTime' => '1500',
'totalPieces' => '1',
'totalWeight' => '100',
'totalHandlingUnits' => '1',
'whoRequested' => 'S'
);
try {
$response_pickup = $client_pickup->createPickupRequestWS($request_pickup);
//Error log the request and response
error_log($client->__getLastRequest());
error_log($client->__getLastResponse());
//$rateReply = $response->quoteInfo->quote->pricing->totalPrice;
//Get the response data
$result_array = array();
$result_array['totalPrice'] = $estes_total_rate_amount;
return $result_array;
} catch (SoapFault $exception) {
error_log('ERROR LOG::' . $exception, $client);
}
}

Php Soap connection refusal

Guys I have an issue I have been learning soap the last few days, I've been trying to connect to a web service for online store to verify users tv licenses before they can purchase a tv set.
I have written the following code to test the web service provided by TV licenses company.
<?php
$wdsl = "https://secure4.tvlic.co.za/AccountEnquiryService_Test_1.0/AccountEnquiryService.svc?wsdl";
$options = array(
'trace' => true,
'exceptions' => true,
'connection_timeout' => 1
);
try{
$client = new SoapClient($wdsl,$options);
$apiauth = array(
'Rquid' => '3600cd32-28b9-4a4f-a522-4326def4a9c2',
'ApiKey' => '5957237e-101c-4ff2-8fdc-4bd6c9393a1d',
'AccountIdentifier' => '9211186012088',
'AccountIdentifierType' => 'SaidNumber');
$header = new SoapHeader('http://tempuri.org/','Auth',$apiauth,true);
$client->__setSoapHeaders($header);
$account = $client->GetAccount();
var_dump($account);
echo "<pre>";
var_dump($client);
echo "</pre>";
}catch (Exception $e) {
echo "Error!";
echo $e->getMessage() . "<br>";
echo 'Last response: ' . $client->__getLastResponse();
}
?>
The wdsl does not require a client certificate, the api key above is for testing only.
The problem I always hit
unable to connect to host
But if I write an invalid function I get an error that the function is invalid for this services, When I use __GetFunctions() I do see the functions in the services, but when I try to use one of them I hit could not connect to host, Can guys help me out to connect to this service.
hopefully this should get you going, I assume that the live wsdl will work correctly without having to call __setLocation()
<?php
$wdsl = "https://secure4.tvlic.co.za/AccountEnquiryService_Test_1.0/AccountEnquiryService.svc?wsdl";
$options = array(
'trace' => true,
'exceptions' => true,
'connection_timeout' => 1
);
try {
$client = new SoapClient($wdsl, $options);
// use https location - the host for http (http://jhb-tvlicweb2.sabc.co.za/AccountEnquiryService_Test_1.0/AccountEnquiryService.svc) dosn't exist
$client->__setLocation('https://secure4.tvlic.co.za/AccountEnquiryService_Test_1.0/AccountEnquiryService.svc');
// setup parameters
$arrParams = array(
'request' => array(
'Header' => array(
'Rquid' => '3600cd32-28b9-4a4f-a522-4326def4a9c2',
'ApiKey' => '5957237e-101c-4ff2-8fdc-4bd6c9393a1d'
),
'AccountIdentifier' => '9211186012088',
'AccountIdentifierType' => 'SaidNumber'
)
);
// request parameters passed in the body not the header
$account = $client->GetAccount($arrParams);
var_dump($account);
echo "<pre>";
var_dump($client);
echo "</pre>";
} catch (\Exception $e) {
echo "Error!";
echo $e->getMessage() . "<br>";
echo 'Last response: ' . $client->__getLastResponse();
}

how to setup recurring payments in paypal

I'm trying to setup recurring payments in paypal with PHP. But the problem that I'm having is that I don't know if I'm doing the right thing. I have this class which makes the request to the Paypal API:
<?php
class Paypal {
protected $_errors = array();
protected $_credentials = array(
'USER' => 'my-user-id',
'PWD' => 'my-pass',
'SIGNATURE' => 'my-signature',
);
protected $_endPoint = 'https://api-3t.sandbox.paypal.com/nvp';
protected $_version = '74.0';
public function request($method,$params = array()) {
$this -> _errors = array();
if( empty($method) ) {
$this -> _errors = array('API method is missing');
return false;
}
$requestParams = array(
'METHOD' => $method,
'VERSION' => $this -> _version
) + $this -> _credentials;
$request = http_build_query($requestParams + $params);
$http_header = array(
'X-PAYPAL-SECURITY-USERID' => 'my-user-id',
'X-PAYPAL-SECURITY-PASSWORD' => 'my-pass',
'X-PAYPAL-SECURITY-SIGNATURE' => 'my-signature',
'X-PAYPAL-REQUEST-DATA-FORMAT' => 'JSON',
'X-PAYPAL-RESPONSE-DATA-FORMAT' => 'JSON'
);
$curlOptions = array (
CURLOPT_HTTPHEADER => $http_header,
CURLOPT_URL => $this -> _endPoint,
CURLOPT_VERBOSE => 1,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $request
);
$ch = curl_init();
curl_setopt_array($ch,$curlOptions);
$response = curl_exec($ch);
if (curl_errno($ch)) {
$this -> _errors = curl_error($ch);
curl_close($ch);
return false;
} else {
curl_close($ch);
$responseArray = array();
parse_str($response,$responseArray);
return $responseArray;
}
}
}
?>
Then I'm making the initial request like this:
session_start();
require_once('Paypal.php');
$paypal = new Paypal();
$amount = 1;
$requestParams = array(
'RETURNURL' => 'http://localhost/tester/paypal/new_test/test_done.php',
'CANCELURL' => 'http://localhost/tester/paypal/new_test/test_cancel.php',
'NOSHIPPING' => '1',
'ALLOWNOTE' => '1',
'L_BILLINGTYPE0' => 'RecurringPayments',
'L_BILLINGAGREEMENTDESCRIPTION0' => 'site donation'
);
$orderParams = array(
'PAYMENTREQUEST_0_AMT' => '1',
'PAYMENTREQUEST_0_CURRENCYCODE' => 'USD',
'PAYMENTREQUEST_0_ITEMAMT' => $amount
);
$item = array(
'L_PAYMENTREQUEST_0_NAME0' => 'site donation',
'L_PAYMENTREQUEST_0_DESC0' => 'site donation',
'L_PAYMENTREQUEST_0_AMT0' => $amount,
'L_PAYMENTREQUEST_0_QTY0' => '1'
);
$response = $paypal->request('SetExpressCheckout', $requestParams + $orderParams + $item);
$sandbox_location = 'https://www.sandbox.paypal.com/webscr?cmd=_express-checkout&token=';
if(is_array($response) && $response['ACK'] == 'Success'){
$token = $response['TOKEN'];
$_SESSION['token'] = $token;
header('Location: ' . $sandbox_location . urlencode($token));
}
?>
As you can see I'm using the SetExpressCheckout API method to get the token that I need and store it in a session so that I can use it later with the request for CreateRecurringPaymentsProfile.
I'm currently redirected to a page similar to this:
Once the user is done logging in with paypal and confirming the amount it redirects to the success page that I've specified which contains this code:
session_start();
require_once('Paypal.php');
$amount = 1;
$paypal = new Paypal();
$token_param = array('TOKEN' => $_SESSION['token']);
$current_date = date('Y-m-d');
$recurring_payment_params = array(
'PROFILESTARTDATE' => gmdate('Y-m-d H:i:s', strtotime($current_date . ' + 1 months')),
'DESC' => 'site donation',
'BILLINGPERIOD' => 'Month',
'BILLINGFREQUENCY' => '1',
'TOTALBILLINGCYCLES' => '0',
'AMT' => $amount
);
$recurringpayment_response = $paypal->request('CreateRecurringPaymentsProfile', $recurring_payment_params + $token_param);
This works, I've verified in the sandbox account that the recurring payment profile was created and that the next billing due is next month. But the problem is that its not really visible in the paypal interface (the screenshot earlier) that they're paying for a subscription. Perhaps I'm getting the redirect url wrong? (https://www.sandbox.paypal.com/webscr?cmd=_express-checkout&token=) or do I have to add additional arguments to the SetExpressCheckout method? Please help.
You're only showing the login screen. After you login you'll see information about the subscription and the button will see "Agree and Pay" or "Agree and Continue" (depending on your useraction value in the return URL) instead of just "Pay" or "Continue".

Setting setAuth() on Guzzle when sending parallel requests

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";
}
}

Categories