I'm using PHP, is there a way of sending emails when a successful payment is done in Stripe for TEST ACCOUNT other than sending it manually from the dashboard using any code or alternative ways?
EDIT1: I've added phpmailer code to my file and it says email sent but I didn't receive any emails. I've tried it in a contact form in another page it works but when I add it in the file where there is stripe (with some changes) it doesn't work. Here is the code in thankYou.php:
<?php
require_once 'core/init.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'PHPMailer/Exception.php';
require 'PHPMailer/PHPMailer.php';
require 'PHPMailer/SMTP.php';
if(isset($_POST['submit_2'])) {
$mail = new PHPMailer();
$mail->CharSet = 'UTF-8';
$mail->IsSMTP();
$mail->Mailer = 'smtp';
$mail->SMTPAuth = true;
$mail->Host = 'smtp.gmail.com';
$mail->Port = 465;
$mail->SMTPSecure = 'ssl';
$mail->addAddress($_POST['email']);
$mail->Username = "myemail";
$mail->Password = "mypassword";
$mail->IsHTML(true);
$mail->SingleTo = true;
$mail->From = "myemail";
$mail->Subject = "Stripe";
$mail->Body = "Test";
if(!$mail->Send())
echo "Message was not sent <br />PHPMailer Error: " . $mail->ErrorInfo;
} else {
echo "Email sent";
}
// Set your secret key: remember to change this to your live secret key in production
// See your keys here https://dashboard.stripe.com/account/apikeys
\Stripe\Stripe::setApiKey(STRIPE_PRIVATE);
// Get the credit card details submitted by the form
$token = isset($_POST['stripeToken'])? $_POST['stripeToken']:'';
// Get the rest of the post data
$full_name = isset($_POST['full_name'])? sanitize($_POST['full_name']):'';
$email = isset($_POST['email'])? sanitize($_POST['email']):'';
$street = isset($_POST['street'])? sanitize($_POST['street']):'';
$street2 = isset($_POST['street2'])? sanitize($_POST['street2']):'';
$city = isset($_POST['city'])? sanitize($_POST['city']):'';
$state = isset($_POST['state'])? sanitize($_POST['state']):'';
$phone_number = isset($_POST['phone_number'])? sanitize($_POST['phone_number']):'';
$country = isset($_POST['country'])? sanitize($_POST['country']):'';
$tax = isset($_POST['tax'])? sanitize($_POST['tax']):'';
$sub_total = isset($_POST['sub_total'])? sanitize($_POST['sub_total']):'';
$grand_total = isset($_POST['grand_total'])? sanitize($_POST['grand_total']):'';
$cart_id = isset($_POST['cart_id'])? sanitize($_POST['cart_id']):'';
$description = isset($_POST['description'])? sanitize($_POST['description']):'';
$charge_amount = number_format((float)$grand_total,2) * 100;
$metadata = array(
"cart_id" => $cart_id,
"tax" => $tax,
"sub_total" => $sub_total,
);
// Create the charge on Stripe's servers - this will charge the user's card
try {
$charge = \Stripe\Charge::create(array(
"amount" => $charge_amount, // amount in cents, again
"currency" => CURRENCY,
"source" => $token,
"description" => $description,
"receipt_email" => $email,
"metadata" => $metadata)
);
//adjust inventory
$itemQ = $db->query("SELECT * FROM cart WHERE id = '{$cart_id}'");
$iresults = mysqli_fetch_assoc($itemQ);
$items = json_decode($iresults['items'],true);
foreach($items as $item){
$newAges = array();
$item_id = $item['id'];
$productQ = $db->query("SELECT ages, sold FROM products WHERE id = '{$item_id}'");
$product = mysqli_fetch_assoc($productQ);
$ages = agesToArray($product['ages']);
$soldproducts = $product['sold'];
foreach($ages as $age){
if($age['age'] == $item['age']){
$q = $age['quantity'] - $item['quantity'];
$newAges[] = array('age' => $age['age'],'quantity' => $q,'threshold' => $age['threshold']);
}else{
$newAges[] = array('age' => $age['age'],'quantity' => $age['quantity'],'threshold' => $age['threshold']);
}
}
if (isset($item['quantity'])) {
$sold = ($soldproducts + $item['quantity']);
}
$ageString = agesToString($newAges);
$db->query("UPDATE products SET ages = '{$ageString}', sold = '{$sold}' WHERE id = '{$item_id}'");
}
//update cart
$db->query("UPDATE cart SET paid = 1 WHERE id = '{$cart_id}'");
$db->query("INSERT INTO transactions
(charge_id,cart_id,full_name,email,street,street2,city,state,phone_number,country,sub_total,tax,grand_total,description,txn_type)
VALUES ('$charge->id','$cart_id','$full_name','$email','$street','$street2','$city','$state','$phone_number','$country','$sub_total',
'$tax','$grand_total','$description','$charge->object')");
$domain = ($_SERVER['HTTP_HOST'] != 'localhost')? '.'.$_SERVER['HTTP_HOST']:false;
setcookie(CART_COOKIE,'',1,"/",$domain,false);
include 'includes/head.php';
include 'includes/navigation.php';
?>
<div class="container-fluid" style="margin-top:100px;">
<h1 class="text-center text-success">Thank You!</h1>
<p> Your card has been successfully charged <?=money($grand_total);?>. You have been emailed a receipt. Please
check you spam folder if it is not in your inbox. Additionally you can print this page as a receipt.</p>
<p>Your receipt number is: <strong><?=$cart_id;?></strong></p>
<p>Your order will be shipped to the address below.</p>
<address>
<?=$full_name;?><br>
<?=$city. ', '.$state.' ';?><br>
<?=$street;?><br>
<?=$street2;?><br>
<?=$phone_number;?><br>
</address>
</div>
<?php
include 'includes/footer.php';
} catch(\Stripe\Error\Card $e) {
// The card has been declined
echo $e;
}
?>
And in the cart.php file (NOT ALL THE CODES):
<div class="form-group col-lg-6">
<label for="email">Email:</label>
<input class="form-control" id="email" name="email" type="text">
</div>
<button type="submit" name="submit_2" class="btn btn-primary" id="checkout_button" style="display:none;">Check Out >></button>
Please help...
This is from the Stripe API documentation (PHP):
receipt_email optional
The email address to which this charge’s receipt will be sent. The receipt will not be sent until the charge is paid, and no receipts will be sent for test mode charges. If this charge is for a Customer, the email address specified here will override the customer’s email address. If receipt_email is specified for a charge in live mode, a receipt will be sent regardless of your email settings
In "test" mode, it's totally impossible to automatically send email from stripe after payment even if you set "receipt_email" parameter. Only in "live" mode, it's possible.
Actually, I couldn't find the information above on stripe documentation so I asked stripe support, then, they said so as I said above.
Related
It seems I am missing something when trying to handle some errors with Stripe in test mode with PHP.
Payment are successful when I enter a test card number like 4242424242424242 (for VISA) but I have no error and nothing is recorded when I enter a bad card number.
It is like if the button "Pay" was not working although it displays an error message if I use a real correct card number in test mode.
Does someone know what am I doing wrong here ? Thanks.
Here is the PHP code :
// Check whether stripe token is not empty
if(!empty($_POST['stripeToken'])){
// Retrieve stripe token, card and user info from the submitted form data
$token = $_POST['stripeToken'];
$name = $_POST['name'];
$email = $_POST['email'];
$card_number = $_POST['card_number'];
$card_exp_month = $_POST['card_exp_month'];
$card_exp_year = $_POST['card_exp_year'];
$card_cvc = $_POST['card_cvc'];
$itemPrice = $_POST['itemPrice'];
$itemNumber = $_POST['itemNumber'];
$Ticket_number = $_POST['Ticket_number'];
// Include Stripe PHP library
require_once 'stripe-php/init.php';
// Set API key
\Stripe\Stripe::setApiKey(STRIPE_API_KEY);
// Add customer to stripe
$customer = \Stripe\Customer::create(array(
'email' => $email,
'source' => $token
));
// Unique order ID
$orderID = strtoupper(str_replace('.','',uniqid('', true)));
// Convert price to cents
$itemPrice = ($itemPrice*100);
// Charge a credit or a debit card
$charge = \Stripe\Charge::create(array(
'customer' => $customer->id,
'amount' => $itemPrice,
'currency' => $currency,
'description' => $itemName,
'metadata' => array(
'order_id' => $orderID
)
));
// Retrieve charge details
$chargeJson = $charge->jsonSerialize();
// Check whether the charge is successful
if($chargeJson['amount_refunded'] == 0 && empty($chargeJson['failure_code']) && $chargeJson['paid'] == 1 && $chargeJson['captured'] == 1){
// Order details
$transactionID = $chargeJson['balance_transaction'];
$paidAmount = $chargeJson['amount'];
$paidCurrency = $chargeJson['currency'];
$payment_status = $chargeJson['status'];
// Include database connection file
include_once 'dbConnect.php';
$itemPrice = ($itemPrice/100);
$paidAmount = ($paidAmount/100);
// Insert tansaction data into the database
$sql = "INSERT INTO orders(name,email,card_number,card_exp_month,card_exp_year,item_name,item_number,item_price,item_price_currency,paid_amount,paid_amount_currency,txn_id,payment_status,created,modified) VALUES('".$name."','".$email."','".$card_number."','".$card_exp_month."','".$card_exp_year."','".$itemName."','".$itemNumber."','".$itemPrice."','".$currency."','".$paidAmount."','".$paidCurrency."','".$transactionID."','".$payment_status."',NOW(),NOW())";
$insert = $db->query($sql);
$payment_id = $db->insert_id;
// If the order is successful
if($payment_status == 'succeeded'){
$ordStatus = 'success';
$statusMsg = '';
}else{
$statusMsg = "Your Payment has Failed!";
}
}else{
print '<pre>';print_r($chargeJson);
$statusMsg = "Transaction has been failed!";
}
}else{
$statusMsg = "Error on form submission.";
}
?>
Thank you for your answers but in fact it was a dummy mistake : I did not declare an id to display my error. I had to add the following code in my form :
<p id="payment-status" role="alert"></p>
I need to send mail to the admin with the inserted data using APi function ,
the function is look like that
public function requestbookingresort_post()
{
$languageid = $this->input->post('languageId');
$resort_id = $this->input->post('resortId');
$booking_from = $this->input->post('bookingFrom');
$booking_to = $this->input->post('bookingTo');
$contact_name = $this->input->post('contactName');
$contact_email = $this->input->post('contactEmail');
$contact_phone = $this->input->post('contactPhone');
$userid = $this->input->post('userId');
if (empty($languageid))
{
$languageRecord = getDefaultlanguage();
$languageid = $languageRecord->languageid;
}
$language_file = languagefilebyid($languageid);
$this->lang->load($language_file, $language_file);
if (empty($resort_id) || empty($booking_from) || empty($booking_to) || empty($contact_name) || empty($contact_email) || empty($contact_phone))
{
$arr['status'] = 'error';
$arr['statusMessage'] = lang('error_in_booking');
$arr['data'] = array();
}
else
{
$dataArray = array(
"languageid" => $languageid,
"userid" => empty($userid) ? "0" : $userid,
"resortid" => $resort_id,
"bookingfrom" => date("Y-m-d", strtotime($booking_from)),
"bookingto" => date("Y-m-d", strtotime($booking_to)),
"contactname" => $contact_name,
"contactemail" => $contact_email,
"contactphone" => $contact_phone,
"requestdatetime" => date("Y-m-d H:i:s"),
);
$this->load->model("Resort_model");
$booking_id = $this->Resort_model->saveBookingRequest($dataArray);
if (empty($booking_id))
{
$arr['status'] = 'error';
$arr['statusMessage'] = lang('error_occurred');
$arr['data'] = array();
}
else
{
$arr['status'] = 'success';
$arr['statusMessage'] = lang('booking_request_submit');
$arr['data'] = array();
}
}
$response = array(
"response" => $arr
);
$this->set_response($response, REST_Controller::HTTP_CREATED); // CREATED (201) being the HTTP response code
}
But i'm new at codeigniter and didn't know how to get this passed data from the database to send mail with that to the admin mail or something ?
Try this.
public function requestbookingresort_post()
{
// Your operations
$response = array(
"response" => $arr
);
$this->sendMail($response)
$this->set_response($response, REST_Controller::HTTP_CREATED); // CREATED (201) being the HTTP response code
}
public function sendMail($response)
{
$settings=$this->Some_model->getEmailSettings();
$mail = new PHPMailer();
$mail->IsSMTP(); // we are going to use SMTP
$mail->SMTPAuth = true; // enabled SMTP authentication
$mail->SMTPSecure = "ssl"; // prefix for secure protocol to connect to the server
$mail->Host = $settings->host; // setting GMail as our SMTP server
$mail->Port = $settings->port; // SMTP port to connect to GMail
$mail->Username = $settings->email; // user email address
$mail->Password = $settings->password; // password in GMail
$mail->SetFrom($settings->sent_email, $settings->sent_title); //Who is sending the email
$mail->AddReplyTo($settings->reply_email,$settings->reply_email); //email address that receives the response
$mail->Subject = "Your Booking has been confirmed";
$mail->IsHTML(true);
$body = $this->load->view('path/email_template', $response, true);
$mail->MsgHTML($body);
$destination = $response['contactEmail']; // Who is addressed the email to
$mail->AddAddress($destination);
if(!$mail->Send()) {
$data['code']=300;
$data["message"] = "Error: " . $mail->ErrorInfo;
}
}
Make sure you have PHPMailer in your libraries and you are loading the library in your constructor and I hope you are keeping Email settings in your database. If not you can manually provide host, port, username and password fields
My group messaging app allowing people in a group (people.php) to sms each other in a closed system where all users can view and reply to the sms.
My next step would be to allow the media files which I can see on the Twilio Console to be sent to others in this group message system and possibly save a record of that media file.
This my code so far, it functions just missing the media part.
listener.php
<?php
include("../Services/Twilio.php");
include("config.php");
$client = new Services_Twilio($accountsid, $authtoken);
include("functions.php");
include("pdo.class.php");
include("people.php");
if( isset($_POST['Body']) ){
$phone = $_POST['From'];
$message = ($_POST['Body']);
$media = ($_POST['MediaUrl0']);
$name = $people[ $phone ];
if( empty($name) ) $name = $phone;
// resends sms message to group
$message = '['.$name.'] '.$message .$media;
foreach ($people as $number => $name) {
if( $number == $phone ) continue;
$sid = send_sms($number,$message,$media);
}
// reply message for succesfull sent sms
print_sms_reply("Message delivered");
// insert sms traffic into database for record purposes
$now = time();
$pdo = Db::singleton();
$sql = "INSERT INTO message_log SET `message`='{$message}', `sent_from`='{$name}'";
$pdo->exec( $sql );
}
?>
function.php
<?php
function send_sms($number,$message){
global $client,$fromNumber;
$sms = $client->account->sms_messages->create(
$fromNumber,
$number,
$message
);
return $sms->sid;
}
function print_sms_reply ($sms_reply){
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
echo "<Response>\n<Sms>\n";
echo $sms_reply;
echo "</Sms></Response>\n";
}
?>
people.php
<?php
include("config.php");
$conn=mysqli_connect("$dbhost","$dbuser","$dbpass","$dbname")
or die (mysqli_error());
$query = "SELECT phone, name FROM grouplist";
$result = mysqli_query($conn, $query);
$people = array();
while ($row = mysqli_fetch_assoc($result)) {
$people[$row['phone']] = $row['name'];
}
?>
Twilio developer evangelist here.
Looks like you need to update your send_sms function to include the media url. Something like this should work:
<?php
function send_sms($number,$message,$media_url){
global $client,$fromNumber;
$sms = $client->account->messages->create(array(
'To' => $number,
'From' => $fromNumber,
'Body' => $message,
'MediaUrl' => $media_url
);
return $sms->sid;
}
?>
Notably, I've updated the call from $client->account->sms_messages->create because the sms_messages resource is deprecated and cannot send media messages. Using $client->account->messages->create uses the newer Messages resource and means you will be able to send media messages.
Let me know if this helps at all.
how to send multiple messages to multiple devices at a time
$apiKey = "xxxxx";
$registrationIdArray = array('xxx_1','xxx_2');
$msg = array('message' => 'message_1','title'=> 'title_1','message' => 'message_2','title'=> 'title_2');
$pusher = new Pusher($apiKey);
$pusher->notify($registrationIdArray, $msg);
I have edited my code please use this
<?php
include_once './GCM.php';
$regid = $_POST['regid'];//your registration id array
$fields1=$_POST['message'];//your message array
$total_message = count($fields1);//count total no of message
$total_records = count($regid);//Count total number of registration id
for($j=0;$j< $total_message;$j++)//loop for sending multiple messgae
{
for($i=0;$i< $total_records;$i++)//loop for sending to multiple device
{
$registatoin_ids = array($regid[$i]);
$message = array("price" => $total_message[$j]);
$result = $gcm->send_notification($registatoin_ids, $message);
}
}
?>
My page continues to error out (Error 324 - Chrome) when attempting to send e-mails with attachments using PHP's PEAR Mail extension. Although the page error's out - I do receive one of the approximately 800 e-mails. Here's what I'm working with:
function email_statements($type) {
switch($type) {
// Determine the type of statement to be e-mailed
case 'monthly':
// Array holding all unique AP e-mail addresses
$ap_email_addresses = array();
include('../path/to/db/connection/params.php');
// Grab the unique AP e-mail address set to receive statements
$stmt = $mysqli->prepare("SELECT email FROM statements GROUP BY email ORDER BY email ASC");
$stmt->execute();
$stmt->bind_result($ap_email_address);
// Add unique e-mail address to AP E-mail Addresses array
while($row = $stmt->fetch()) $ap_email_addresses[] = $ap_email_address;
$stmt->close();
$mysqli->close();
// Verify we grabbed the e-mail addresses
if(count($ap_email_addresses) == 0) {
// Exit and return error code if unable to grab e-mail addresses
$return_message = 1;
exit;
}
// E-mail addresses grabbed - proceed
else {
// PDF formatted date
date_default_timezone_set('America/New_York');
$formatted_date = date('m_d_Y');
// Now we have the unique e-mail addresses - associate those with the account numbers
include('../path/to/db/connection/params.php');
foreach($ap_email_addresses as $email_address) {
$file_names = array();
$stmt = $mysqli->prepare("SELECT customer_number FROM statements WHERE email = ?");
$stmt->bind_param("s", $email_address);
$stmt->execute();
$stmt->bind_result($ap_account_number);
// Constructs the name of the statement (PDF) file to be sent
while($output = $stmt->fetch()) $file_names[] = $ap_account_number . '_' . $formatted_date . '.pdf';
// Send e-mails
include('Mail.php');
include('Mail/mime.php');
// Include SMTP authentication parameters
include('../path/to/email/info.php');
// Set the e-mail recipients
$recipients = 'example#example.com';
// Set the e-mail subject
$subject = 'Monthly Account Statement';
// Create the e-mail body
$html =
'<html>
<body>
<p>Test E-mail</p>
</body>
</html>';
// Construct the message headers
$headers = array(
'From' => $from,
'Subject' => $subject,
'Content-Type' => 'text/html; charset=UTF-8',
'MIME-Version' => '1.0'
);
$mimeparams = array();
$mimeparams['text_encoding'] = '8bit';
$mimeparams['text_charset'] = 'UTF-8';
$mimeparams['html_charset'] = 'UTF-8';
$mimeparams['head_charset'] = 'UTF-8';
// Create a new instance
$mime = new Mail_mime();
// Specify the e-mail body
$mime->setHTMLBody($html);
// Attach the statements (PDF)
foreach($file_names as $attached_file) {
$file = '../path/to/the/pdf/file/' . $attached_file;
$file_name = $attached_file;
$content_type = "Application/pdf";
$mime->addAttachment ($file, $content_type, $file_name, 1);
}
// Create the body
$body = $mime->get($mimeparams);
// Add the headers
$headers = $mime->headers($headers);
// Create SMTP connect array to be passed
$smtp = Mail::factory('smtp', array ('host' => $host, 'port' => $port, 'auth' => true, 'username' => $username, 'password' => $password));
// Send the message
$mail = $smtp->send($recipients, $headers, $body);
if(PEAR::isError($mail)) echo 'Error';
else echo 'Sent';
// Close this account and cycle through the rest
$stmt->close();
}
$mysqli->close();
}
break;
}
}
Now I thought maybe I wasn't giving the script enough time to execute - so I set it ridiculously high set_time_limit(99999999) to ensure it had plenty of time, although it normally times out within 10-15 seconds. So basically it works like this, I have an internal DB that stores customer account numbers and e-mail addresses. Accounts can have the same e-mail address (It's sent to their company's AP department) - aka one e-mail address receives statements for multiple branches. From their each statement is already constructed with the format being ACCOUNTNUMBER_MM_DD_YYYY.pdf.
So I'm simply trying to have a short message in the body, and attach the monthly statements. Again, not sure why it's failing, and even though the script halts, I do receive ONE of the e-mails (I'm sending them all to myself at the moment just to test). Can anyone see where I may have an issue?
I discovered the issue. As of PHP 5.0+ you cannot have multiple instances of the same include file - aka Mail.php was included as it looped. Once it was moved outside of the loop, the issue was resolved.