I am using the Twilio messaging service to send from multiple numbers.
I want to get messages that were sent from that messaging service.
I am trying to use stream, as I don't want thousands of messages
for each call.
Is there a way to get only messages that were sent out using a
particular messaging service?
$searcher = new TwilioLogRetriever;
$searcher->listMessagesForMessagingService('MGxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
TwilioLogRetriever
<?php
use Twilio\Rest\Client;
class TwilioLogRetriever {
function listMessagesForMessagingService($messagingServicesSid) {
$client = new Client(Configure::Read('twilio.accountSid'), Configure::read('twilio.authToken'));
$once = false;
$n = 0;
// Try specifying 'from' (just guessing)
foreach ($client->messages->stream(['from' => $messagingServicesSid]) as $message) {
++$n;
//echo $message->body . "\n";
$data = [
'from' => $message->from,
'to' => $message->to,
'direction' => $message->direction,
'messagingServiceSid' => $message->messagingServiceSid,
'numMedia' => $message->numMedia,
'numSegments' => $message->numSegments,
'price' => $message->price,
'priceUnit' => $message->priceUnit,
'sid' => $message->sid,
'status' => $message->status,
'body' => $message->body,
];
$data['dateCreated'] = $message->dateCreated->format('Y-m-d H:i:s');
$data['dateUpdated'] = $message->dateUpdated->format('Y-m-d H:i:s');
$data['dateSent'] = $message->dateSent->format('Y-m-d H:i:s');
if ( ! $once ) {
print_r($message);
$once = true;
}
}
$this->out(__METHOD__. " Found $n messages." );
}
function out($message ) {
echo $message . "\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
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);
}
}
The 2nd foreach should send to each new_token->mob .but it sends to one and then stops.what am doing wrong?
My code is :
foreach($new_tokens as $new_tokenss)
{
foreach($new_tokenss as $new_token)
{
$message = "Message";
$message_encoded = urlencode($message);
$postData = array(
'authkey' => \Config::get('procedures.msg91.authKey'),
'mobiles' => $new_token->mob,
'message' => $message_encoded,
'sender' => \Config::get('procedures.msg91.senderId'),
'route' => \Config::get('procedures.msg91.route')
);
$curl = new \anlutro\cURL\cURL;
$curl->post(\Config::get('procedures.msg91.api_url'), $postData);
return 'New emergency patient';
}
}
return 'New emergency patient';
This like makes the function to return the above mentioned value and thus break the for loop.
I am using mailchimp api v2. I am using the mailchimp recommended full api v2 php wrapper. I am able to create a campaign, but not sure how to send it. With the send method, It wants the campaign id, but I am letting mailchimp create the campaign id when creating the campaign.
My create campaign code looks like this:
$api_key = "my_api_key";
require('Mailchimp.php');
//Create Campaign
$Mailchimp = new Mailchimp($api_key);
$result = $Mailchimp->campaigns->create('regular',
array('list_id' => 'my_list_id',
'subject' => 'This is a test subject',
'from_email' => 'test#test.com',
'from_name' => 'From Name'),
array('html' => '<div>test html email</div>',
'text' => 'This is plain text.')
);
if( $result === false ) {
// response wasn't even json
echo 'didnt work';
}
else if( isset($result->status) && $result->status == 'error' ) {
echo 'Error info: '.$result->status.', '.$result->code.', '.$result->name.', '.$result->error;
} else {
echo 'worked';
}
This seems to be working for me.
$Mailchimp = new Mailchimp($api_key);
$result = $Mailchimp->campaigns->create('regular',
array('list_id' => 'my_list_id',
'subject' => 'This is a test subjects',
'from_email' => 'test#test.com',
'from_name' => 'From_Name'),
array('html' => '<div>test html email</div>',
'text' => 'This is plain text.')
);
if( $result === false ) {
// response wasn't even json
echo 'sorry';
}
else if( isset($result->status) && $result->status == 'error' ) {
echo 'Error info: '.$result->status.', '.$result->code.', '.$result->name.', '.$result->error;
} else {
echo 'worked';
$mySend = $Mailchimp->campaigns->send($result['id']);
}
I'm using mandrill to manage my website emails.But I also want to use a mailbox like yahoo or google so I set a route in mandrill which forward inbound emails that will send to info#mydomain.com, to my default mail box(myEmail#ymail.com).I wrote a PHP code which receive an email, decode it, and forward it to a my email. I use SwiftMailer to send SMTP email.
It works nice for emails without any attachment.But there is a strange problem with attachments.They deliver corruptly.I can not open them.
I search throughly and test a lot, but unfortunately couldn't find the problem.
<?php
if(!isset($_POST['mandrill_events'])) {
echo 'A mandrill error occurred: Invalid mandrill_events';
exit;
}
// -------------- Receive --------------------------
$mail = array_pop(json_decode($_POST['mandrill_events']));
// ----------------- Send ----------------------------------------
include_once "swiftmailer-master/lib/swift_required.php";
$subject = $mail->msg->subject . " From " . $mail->msg->from_email;
$from = array('info#myDomain.ir' =>'myDomain');
$to = array(
'myEmail#yahoo.com' => 'Hamed Gh'
);
$transport = Swift_SmtpTransport::newInstance('smtp.mandrillapp.com', 25,tls);
$transport->setUsername('username');
$transport->setPassword('***********');
$swift = Swift_Mailer::newInstance($transport);
$message = new Swift_Message($subject);
$message->setFrom($from);
//I think there is a problem here!!
foreach ($mail->msg->attachments as $attachment) {
$myType = $attachment->type;
$myName = $attachment->name;
$myContent = $attachment->content;
$attachment = Swift_Attachment::newInstance()
->setFilename($myName)
->setContentType($myType)
->setBody($myContent)
;
$message->attach($attachment);
}
$body = $mail->msg->html;
$message->setBody($body, 'text/html');
$message->setTo($to);
$text = "Mandrill speaks plaintext";
$message->addPart($text, 'text/plain');
if($recipients = $swift->send($message, $failures) )
{
echo 'Message successfully sent!';
} else {
echo "There was an error:\n";
print_r($failures);
}
?>
At the end I couldn't find the problem with SwiftMailer but I could answer my need with mandrill API,
this code works for me:
<?php
if(!isset($_POST['mandrill_events'])) {
echo 'A mandrill error occurred: Invalid mandrill_events';
exit;
}
require 'mandrill/src/Mandrill.php';
// -------------- Receive --------------------------
$mail = array_pop(json_decode($_POST['mandrill_events']));
$attachments = array();
foreach ($mail->msg->attachments as $attachment) {
$attachments[] = array(
'type' => $attachment->type,
'name' => $attachment->name,
'content' => $attachment->content,
);
}
$headers = array();
// Support only Reply-to header
if(isset($mail->msg->headers->{'Reply-to'})) {
$headers[] = array('Reply-to' => $mail->msg->headers->{'Reply-to'});
}
// ----------------- Send ----------------------------------------
try {
$mandrill = new Mandrill('-------------');
$message = array(
'html' => $mail->msg->html,
'text' => 'Example text content',
'subject' => $mail->msg->subject . " From " . $mail->msg->from_email,
'from_email' => 'info#mydomain.com',
'from_name' => 'info',
'to' => array(
array(
'email' => 'me#yahoo.com',
'name' => 'me',
'type' => 'to'
)
),
'headers' => array('Reply-To' => 'info#mydomain.com'),
'important' => false,
'track_opens' => null,
'track_clicks' => null,
'auto_text' => null,
'auto_html' => null,
'inline_css' => null,
'url_strip_qs' => null,
'preserve_recipients' => null,
'view_content_link' => null,
'bcc_address' => null,
'tracking_domain' => null,
'signing_domain' => null,
'return_path_domain' => null,
'merge' => true,
'attachments' => $attachments
);
$async = false;
$ip_pool = 'Main Pool';
$send_at = null;
$result = $mandrill->messages->send($message, $async, $ip_pool, $send_at);
} catch(Mandrill_Error $e) {
// Mandrill errors are thrown as exceptions
echo 'A mandrill error occurred: ' . get_class($e) . ' - ' . $e->getMessage();
// A mandrill error occurred: Mandrill_Unknown_Subaccount - No subaccount exists with the id 'customer-123'
throw $e;
}
?>