PHP Mysql insert statement from a function - php

This code gets values from a database and forms a sms template and then passes the moble number and message to webservice to send the sms. It's part of a function wall().....
$name = $resultarr['name'];
$amount = $resultarr['amount'];
$transaction_id = $resultarr['trans_id'];
$date = $resultarr['time_paid'];
//message template
$message = "Dear $name we have received $amount from you. MPESA transaction Id $transaction_id on $date.";
$mobilenumber = $resultarr['msisdn']; // get mobile number from array
$message_sent = $message;
$serviceArguments = array(
"mobilenumber" => $mobilenumber,
"message" => $message_sent
);
$client = new SoapClient("http://59.38.606.10:8080/smsengine/smsws?WSDL");
$result = $client->process($serviceArguments);
grabdetails($message_sent, $mobilenumber);
return $result;
}
//I call the function wall() to send sms
wall();
$perm = wall();
$status = $sperm->return; //outputing the status
// Here I want to capture the $status variable and put it in a db below
echo "$status";
function grabdetails($messagee, $mobno)
{
$message_sent = $messagee;
$mobilenumber = $mobno;
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "smsdb";
// Create connection
// Check connection
$sql = "INSERT INTO smsdb (sms_text, receiver_number, time_sent, status)
VALUES
('$message_sent', '$mobilenumber', NOW(), $status )";
Question is how do I grab $status ind insert it into the db since its not in the function? Kindly. help, anyone?

The code above is not complete, but I assume that the function on top where you do $client = new SoapClient("http://59.38.606.10:8080/smsengine/smsws?WSDL"); is actually the wall function. If so, then what that function returns, i.e. $result actually has the status you need. So with this code snippet (assuming $sperm is a typo and should actually be $perm, the response from the wall function), you get the response from wall(), which is an object and has the status you need.
$perm = wall();
$status = $sperm->return; //outputing the status
// Here I want to capture the $status variable and put it in a db below
echo "$status";
If that's right, then before calling grabdetails in the wall function, you actually have the status and you can send it to the function like this:
grabdetails($message_sent, $mobilenumber, $result->return);
And then change the definition of the grabdetails to receive the status as well and use it in the DB insert.

Related

PHP: Stripe API does not display any error when entering a bad card number

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>

Shopify Order Create Webhook Inserting Into Mysql Using PHP

I have been building a private web based app for my shopify store that caters more towards our business needs. While i am able to do a dump of "all-orders", or "all-products", etc to Mysql, i haven't been able to figure out executing the shopify order creation webhook to insert a new order when created in Shopify to a Mysql database.
Instead i would need to run my script every "x" times to see if there is a new order (This could if i'm not mistaken lead to exceeding my API limit if i am running other API calls concurrently).
I understand the process of events however i am struggling to execute!
1. New order created in Shopify by Customer &or Admin.
2. Triggers webhook and sends Json to desired url i.e(https://mydomain//new-order.php). -> [Struggling]
3. When this happens the Json is decoded. -> [Struggling]
4. Assigned to a variable. -> [This i can do]
5. Inserted into a Mysql database. -> [This i can do]
=> Question:
How do you once you have created the webhook (in Shopify) get it to trigger your code to run thereafter and execute?
below is the code that i have put together, but when i sent a test hook the database isn't being updated.
All in the [new-orders.php] file (Broken up to show my train of thought):
[1] Private app credentials for connecting to Shopify store.
<?php
$api_url = https://apikey:password#my-store.shopify.com';
$shopify = $api_url . '/admin/webhooks.json';
[2] Create an array for the webhook argumnets when the webhook is triggered & assign to variable $webhooks.
$arguments = array(
'topic' => 'order/creation',
'address' => 'https://mydomain//new-order.php'
);
$webhooks = $api_url . '/admin/webhooks.json', $arguments;
[3] Decode the webhook data.
$webhook_content = '';
$webhook = fopen('php://input' , 'rb');
while(!feof($webhook)){ //loop through the input stream while the end of file is not reached
$webhook_content .= fread($webhook, 4096); //append the content on the current iteration
}
fclose($webhook); //close the resource
$orders = json_decode($webhook_content, true); //convert the json to array
[4] Add the new order to the Mysql database table.
// not sure if a foreach loop is necessary in this case?
foreach($orders as $order){
$servername = "mysql.servername.com";
$database = "database_name";
$username = "user_name";
$password = "password";
$sql = "mysql:host=$servername;dbname=$database;";
// Create a new connection to the MySQL database using PDO, $my_Db_Connection is an object
try {
$db = new PDO($sql, $username, $password);
//echo "<p> DB Connect = Success.</p>";
} catch (PDOException $error) {
echo 'Connection error: ' . $error->getMessage();
}
$order_id = $order['id'];
$order_number = $order['name'];
$f_name = $order['billing_address']['name'];
$payment_gateway = $order['gateway'];
$financial_status = $order['financial_status'];
$order_value = $order['total_price'];
$order_status = $order['#'];
$shipping_province = $order['shipping_address']['province'];
$created_at = $order['created_at'];
$updated_at = $order['updated_at'];
$shipping_method = $order['shipping_lines'][0]['title'];
$stmt = $db->query("INSERT INTO orders(order_id, order_number, cust_fname, payment_gateway, financial_status, order_value, order_status, ship_to, created_at, updated_at, shipping_method)
VALUES ('$created_at', '$order_id', '$order_number', '$f_name', '$payment_gateway', '$financial_status', '$order_value', '$order_status', '$shipping_province', '$created_at', '$updated_at', '$shipping_method')");
}
?>
Any help would be greatly appreciated and i hope i have given enough context to the issue i am currently facing. If any other information is required i will try my best to explain why i have done something the way i have.
Regards,
Update, managed to figure this out and for those of you potentially struggling with the following this is how i solved.
There are 2 aspect here!
1. Setting up the webhook [Shopify -> Notifications -> webhooks].
2. The php file that processes the webhook.
1. -> Create Webhook in shopify and point to where you php url [example.com/Process-webhook.php]
2. -> Process-webhook.php
php code
// Load variables
$webhook_content = NULL;
// Get webhook content from the POST
$webhook = fopen('php://input' , 'rb');
while (!feof($webhook)) {
$webhook_content .= fread($webhook, 4096);
}
fclose($webhook);
// Decode Shopify POST
$webhook_content = json_decode($webhook_content, TRUE);
$servername = "server_name";
$database = "database";
$username = "user_name";
$password = "password";
$sql = "mysql:host=$servername;dbname=$database;";
// Create a new connection to the MySQL database using PDO, $my_Db_Connection is an object
try {
$db = new PDO($sql, $username, $password);
//echo "<p> DB Connect = Success.</p>";
} catch (PDOException $error) {
echo 'Connection error: ' . $error->getMessage();
}
//Assign to variable
$order_id = $webhook_content['id'];
$order_number = $webhook_content['name'];
$f_name = $webhook_content['billing_address']['name'];
$payment_gateway = $webhook_content['gateway'];
$financial_status = $webhook_content['financial_status'];
$pick_status = $webhook_content['NULL'];
$pack_status = $webhook_content['NULL'];
$fulfill_status = $webhook_content['NULL'];
$order_value = $webhook_content['total_price'];
$order_status = $webhook_content['NULL'];
$shipping_province = $webhook_content['shipping_address']['province'];
// I wanted to insert the variant_id's and quantity as a string in one column. With this i can unserialise and use when needed
$items = [];
foreach($webhook_content["line_items"] as $item) {
$items[$item["variant_id"]]['quantity'] = $item["quantity"];
}
$items = serialize($items);
$created_at = $webhook_content['created_at'];
$updated_at = $webhook_content['updated_at'];
$shipping_method = $webhook_content['shipping_lines'][0]['title'];
$stmt = $db->query("INSERT INTO orders(order_id,
order_number,
cust_fname,
payment_gateway,
financial_status,
order_value,
order_status,
ship_to,
items,
created_at,
updated_at,
shipping_method)
VALUES ('$order_id',
'$order_number',
'$f_name',
'$payment_gateway',
'$financial_status',
'$order_value',
'$order_status',
'$shipping_province',
'$items',
'$created_at',
'$updated_at',
'$shipping_method')");
?>

Adding media to Twilio group messaging system

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 re-initialize the Docusign PHP API with different credentials

We have a case where we need to check envelope status in two separate Docusign accounts. If we don't get status in the first, we want to check the second.
I'm having trouble getting the API to re-initialize with the credentials of our second account. I'm calling this snippet with the new variables:
require_once('docusign/SignatureApi.php');
$IntegratorsKey = "abcd";
$UserID = "dave#account.com";
$Password = "xxxxx";
$_apiEndpoint = $Endpoint;
$_apiWsdl = "docusign/api/APIService.wsdl";
$api_options = array('location'=>$_apiEndpoint,'trace'=>true,'features' => SOAP_SINGLE_ELEMENT_ARRAYS);
$api = new APIService($_apiWsdl, $api_options);
$api->setCredentials("[" . $IntegratorsKey . "]" . $UserID, $Password);
$res = RequestEnvelopStatuses($envelopes);
$envelopeStatuses = $res->RequestStatusesResult;
if(!count($envelopeStatuses->EnvelopeStatuses->EnvelopeStatus)){
// If we did not find envelopes, check other account
$IntegratorsKey = "wxyz";
$UserID = "fred#altaccount.com";
$Password = "xxxxx";
$api->setCredentials("[" . $IntegratorsKey . "]" . $UserID, $Password);
// retry request
$res = RequestEnvelopStatuses($envelopes);
$envelopeStatuses = $res->RequestStatusesResult;
}
It doesn't return an error, but won't return envelope status either. It seems to still use the first credentials (guessing). The second attempt always seems to return whatever the first attempt did.
Is there a better / preferred way to do this?
That does not look like the proper way to get the envelope status. Maybe that's why you are not finding them and trying to look again?
// Create a filter using account ID and today as a start time
$envStatusFilter = new EnvelopeStatusFilter();
$envStatusFilter->AccountId = $AccountID;
$beginDateTime = new EnvelopeStatusFilterBeginDateTime();
$beginDateTime->_ = todayXsdDate(); // note that this helper function
// is in CodeSnippets/include/utils.php
// in the PHP SDK
$envStatusFilter->BeginDateTime = $beginDateTime;
// Send
$requestStatusesparams = new RequestStatuses();
$requestStatusesparams->EnvelopeStatusFilter = $envStatusFilter;
$response = $api->RequestStatuses($requestStatusesparams);

can i send multiple messages to multiple devices at a time using GCM push plugin in php

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);
}
}
?>

Categories