I want to send an SMS by using external URL API such as https://bsms.ufone.com/bsms_v8_api/sendapi-0.3.jsp, I've created a plugin file and used curl to call the URL API as:
add_action( 'wpcf7_mail_sent','custom_api' );
function custom_api( $contact_form ) {
$title = $contact_form->title();
if($title === 'Contact form 1') {
$submission = WPCF7_Submission::get_instance();
if($submission)
{
$posted_data = $submission->get_posted_data();
$name = $posted_data['your-name'];
$email = $posted_data['your-email'];
$contact_number = $posted_data['your-contact-number'];
$subject = $posted_data['your-subject'];
$message = $posted_data['your-message'];
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$resp = curl_exec($curl);
curl_close($curl);
}
}
}
The problem is that the form is submitted successfully but I'm not receiving any SMS.
What could be the issue and how to fix it?
I've defined the url as: $url= 'https://bsms.ufone.com/bsms_v8_api/sendapi-0.3.jsp?message=testing&lang=English&mobilenum=923159021409&groupname=&messagetype=Transactional; Moreover, I've also tried using wp_remote_get
Below is the response of the URL API which is basically XML file, I've tried to use the simpleXML_load_file too but it returns bool(false)
Please add the api url in $url also if there's any access token then please use it. Moreover, as you are using WordPress you can use wp_remote_post to post data. You can see the reference here.
Related
Contact form 7 loading infinitely after connecting it to our CRM API though the email is being sent and data getting submitted and saved the user feels that the data has not yet been submitted since the loader keeps moving.
Here's my code added in functions.php
add_action('wpcf7_mail_sent', function ($cf7) {
if(isset($_POST['your-name']) && isset($_POST['your-email']) && isset($_POST['mobile_no'])){
$name = $_POST['your-name'];
$email = $_POST['your-email'];
$phone = $_POST['mobile_no'];
$data = array(
"name"=>"$name",
"email"=>"$email",
"mobile"=>"$phone",
"secret_key"=>"{secret_key}",
);
leadToNoPaperFormAPI($data);
}
});
function leadToNoPaperFormAPI($data=array())
{
if(is_array($data) && !empty($data))
{
$data_string = json_encode($data);
$ch = curl_init('{API_URL}');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$result = curl_exec($ch);
$array = json_decode($result);
}
}
Any help will be highly appreciated. :)
Please note the code gets executed and the form gets submitted & email sent, however, the user on the browser doesn't see the success message just sees the loader.
I am trying to send woocommerce order to netsuite via an external api I have written. I am nw to woocommerce and do not fully get how to add this functionality.
I have added the following code to the functions.php file in public_html/wp-content/themes/reverie-master/
add_action( 'woocommerce_payment_complete'', 'wdm_send_order_to_ext');
function wdm_send_order_to_ext( $order_id ){
// get order object and order details
$order = new WC_Order( $order_id );
$email = $order->billing_email;
$phone = $order->billing_phone;
//Create the data object
$orderData = array(
'customer_email' => $email,
'customer_phone' => $phone
);
$apiData = array(
'caller' => 'woocommerce',
'json' => $orderData,
'key' => 'MY_SECRET_KEY'
);
$jsonData =json_encode($orderData);
$url = "";
$api_mode = 'sandbox';
if($api_mode == 'sandbox'){
// sandbox URL example
$url = "https://forms.netsuite.com/app/site/hosting/scriptlet.nl?script=XXX&deploy=X&compid=XXXXXXX_SB1&h=XXXXXXXXXXXXXXXX";
}
else{
// production URL example
$url = "";
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($jsonData));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec ($ch);
curl_close ($ch);
// the handle response
if (strpos($response,'ERROR') !== false) {
print_r($response);
} else {
// success
}
}
I have tested the brunt of this code, just the parts that do not concern woocommerce in a different site and I can see the data showing up in NetSuite. However, when I go through my store and place an order, and take payment, I do not see the data come into NetSuite. Do I have this code in the right location? Is there something I am missing?
Update
I installed the plugin Code Snippets and added the code there instead. Set it to Run snippet everywhere. Still no luck.
Looks like you have a double quote on the first link
change
add_action( 'woocommerce_payment_complete'', 'wdm_send_order_to_ext');
to
add_action( 'woocommerce_payment_complete', 'wdm_send_order_to_ext');
Rather than use curl - you can always use the build in WordPress wp_remote_post() function
Also make sure you have WP_DEBUG set to true in wp-config.php while testing.
I'm integrating SMS API with WooCommerce to send automatic order updates to customers mobiles whenever the make any purchase on site.
below is my code for the same
add_action('woocommerce_payment_complete', 'custom_process_order', 10, 1);
function custom_process_order($billing_phone)
{
$username = "my username";
$hash = "d761fbd7bd31c5eeec2a5b2556d6b9d3b1a1ae51";
//Multiple mobiles numbers separated by comma
$mobileNumber = "$billing_phone";
$senderId = "ORNGMT";
$message = urlencode("Dear Customer");
$postData = array(
'hash' => $hash,
'mobiles' => $$billing_phone,
'message' => $message,
'sender' => $senderId,
);
$url='http://api.textlocal.in/send/?';
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $postData
//,CURLOPT_FOLLOWLOCATION => true
));
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$output = curl_exec($ch);
if(curl_errno($ch))
{
echo 'error:' . curl_error($ch);
}
curl_close($ch);
echo $output;
}
is it correct ?
I've added this code to functions.php page
my sms gateway provider has sent me below example code to send sms with PHP
<?php
// Authorisation details.
$username = "your login id";
$hash = "your hash key";
// Configuration variables. Consult http://api.textlocal.in/docs for more info.
$test = "0";
// Data for text message. This is the text message data.
$sender = "API Test"; // This is who the message appears to be from.
$numbers = "44777000000"; // A single number or a comma-seperated list of numbers
$message = "This is a test message from the PHP API script.";
// 612 chars or less
// A single number or a comma-seperated list of numbers
$message = urlencode($message);
$data = "username=".$username."&hash=".$hash."&message=".$message."&sender=".$sender."&numbers=".$numbers."&test=".$test;
$ch = curl_init('http://api.textlocal.in/send/?');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch); // This is the result from the API
curl_close($ch);
?>
Integrating message API for each event will be difficult and you need to customize the at the code level.
You can use a popular SMSplugin for wordpress woocommerce
https://wordpress.org/plugins/woocommerce-apg-sms-notifications/
Just you need to configure this plugin from woocommerce Admin login and it will send sms notifications automatically. We are using it with Spring Edge sms gateway.. Working Good.
Tested and working
Custom api Integration with Woocommerce wordpress
Ufone pakistan sms integration with woocommerce wordpress
if you are looking for integration with ufone pakistan sms api bsms ufone pakistan service provider with woocommerce wordpress then use the following code in your functions file
sms api integration ufone bsms with wordpress woocommerce thanks to the author on this page Integrating custom SMS API with woocommerce
//add this line for calling your function on creation of order in woocommerce
add_action('woocommerce_order_status_processing', 'custom_func', 10, 3);
function custom_func ($order_id) {
$order_details = new WC_Order($order_id);
//fetch all required fields
$billing_phone = $order_details->get_billing_phone();
$billing_name = $order_details->get_billing_first_name();
$billing_last_name = $order_details->get_billing_last_name();
$total_bill = $order_details->get_total();
$textmessage = rawurlencode("Dear $billing_name, Thank you for your order. Your order #$order_id is being processed. Please wait for confirmation call Total Bill = $total_bill");
// Now put HTTP ufone BSMS API URL
$url = "https://bsms.ufone.com/bsms_v8_api/sendapi-0.3.jsp?id=msisdn&message=$textmessage&shortcode=SHORTCODE&lang=English&mobilenum=$billing_phone&password=password&messagetype=Nontransactional";
// NOW WILL CALL FUNCTION CURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
$err = curl_error($ch);
curl_close($ch);
return $order_id;
}
$billingphone in your function is ID. Try this below code. It works
add_action('woocommerce_payment_complete', 'custom_process_order', 10, 1);
function custom_process_order($order_id) {
//Lets get data about the order made
$order = new WC_Order( $order_id );
//Now will fetch customer/buyer id here
$customer_id = $order->user_id;
//now finally we fetch phone number
$billing_phone = get_user_meta( $customer_id, 'billing_phone', true );
// Now put your HTTP SMS API URL . I PUT WHICH WE ARE USING
$jsonurl = "http://tsms.thirdeyegoa.com/api/sendmsg.php?user=USERNAME&pass=PASSWORD&sender=MYSENDERID&phone=".$billing_phone."&priority=ndnd&stype=normal&text=MY MESSAGE TO CUSTOMER.";
// NOW WILL CALL FUNCTION CURL
$json = curl($jsonurl);
return $order_id;
}
Same you can do for Order Completed too with respective hook.
i write this piece of code and it is working.
add_action('woocommerce_order_status_completed','payment_complete');
function payment_complete($order_id)
{
$order=new Wc_order($order_id);
$order_meta = get_post_meta($order_id);
$shipping_first_name = $order_meta['_shipping_first_name'][0];
$phone=$order_meta['_billing_phone'][0];
$first_name=$order->billing_first_name;
$last_name=$order->billing_last_name;
$name=$first_name."".$last_name;
$mobile=$order->billing_mobile;
$items = $order->get_items();
foreach ( $items as $item ) {
$product_name = $item['name'];
$product_id = $item['product_id'];
$product_variation_id = $item['variation_id'];
$time=$item['timings'];
$slot=$item['time_slot'];
$qty= $item['qty'];
$date=$item['tour_date'];
}
$text="your message here";
$data="user=username&pass=password&sender=sendername&phone=".$phone."&priority=ndnd&stype=normal&text=".$text;
$ch = curl_init('http://bhashsms.com/api/sendmsg.php?');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
echo $result;
curl_close($ch);
}
I am from Textlocal. Let me help you out with the code.
Firstly the error that you are getting - 'Unexpected Token' is generally due to an invalid JSON response. If you are unaware of the source of the issue, I would suggest you to look in the Javascript console in the Dev section (triggering the error). For reference, you can check Mike's blog out here.
In the code you have shared, Textlocal API is not receiving the parameters that are mandatory for a successful POST call. You can rephrase your function like this:
add_action('woocommerce_payment_complete', 'custom_process_order', 10, 1);
function custom_process_order($order_id) {
$order = new WC_Order( $order_id );
$customer_id = $order->user_id;
$billing_phone = get_user_meta( $customer_id, 'billing_phone', true );
$data="username=USERNAME&hash=hash&sender=ORNGMT&numbers=".$billing_phone."&message=MY MESSAGE TO CUSTOMER.";
$jsonurl = curl_init('https://api.textlocal.in/send?');
$json = curl($jsonurl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($json);
echo $result;
curl_close($json);
return $order_id;
}
If you need any further assistance, please reach out to our support team (support#textlocal.in)
I am trying to modify LinkedIn's sample authorization code to post a company update.
Have the original code example working, meaning I can login to my user profile. So the next step would be posting the update.
Have found some info on the Internet and here at stackoverflow.com, and the result is the function PostUpdate() found in the code below. The rest of the code pretty much comes straight from the Linkedin code sample.
So this code seems to run, I get no errors reported, but I also get no update on the company page. There is one issue I notice, after successfully logging-in, the code prints "Hello $user->firstName $user->lastName." but my name does NOT show up on the screen. The "Hello" does, so perhaps this indicates where a problem might be found.
<?php
//config.php contains the API KEY, SECRET, AND COMPANY ID
//define('API_KEY', 'your key');
//define('API_SECRET', 'your secret');
//define('COMPANY_ID', 'your company id');
require_once('config.php');
// You must pre-register your redirect_uri at https://www.linkedin.com/secure/developer
define('REDIRECT_URI', 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['SCRIPT_NAME']);
define('SCOPE', 'r_basicprofile r_emailaddress w_share rw_company_admin');
// You'll probably use a database
session_name('linkedin');
session_start();
// OAuth 2 Control Flow
if (isset($_GET['error'])) {
// LinkedIn returned an error
print $_GET['error'] . ': ' . $_GET['error_description'];
exit;
} elseif (isset($_GET['code'])) {
// User authorized your application
if ($_SESSION['state'] == $_GET['state']) {
// Get token so you can make API calls
getAccessToken();
} else {
// CSRF attack? Or did you mix up your states?
exit;
}
} else {
if ((empty($_SESSION['expires_at'])) || (time() > $_SESSION['expires_at'])) {
// Token has expired, clear the state
$_SESSION = array();
}
if (empty($_SESSION['access_token'])) {
// Start authorization process
getAuthorizationCode();
}
}
// Congratulations! You have a valid token. Now fetch your profile
$user = fetch('GET', '/v1/people/~:(firstName,lastName)');
print "Hello $user->firstName $user->lastName.";
// temporary message content for test purposes
$xml_txt = "<?xml version='1.0' encoding='UTF-8'?>
<share>
<visibility>
<code>anyone</code>
</visibility>
<comment>Testing a full company share!!!!!</comment>
<content>
<submitted-url>https://www.example.com/test-2.html</submitted-url>
<title>Test Share with Content</title>
<description>content description</description>
<submitted-image-url>https://www.example.com/img/internet.jpg</submitted-image-url>
</content>
</share>";
//Post the message
$result = PostUpdate($xml_txt);
//Done
exit;
function PostUpdate($message) {
print $_SESSION['access_token'];
$url = 'https://api.linkedin.com/v1/companies/'. COMPANY_ID . '/shares';
// build your message
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $message );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/xml', 'Authorization: Bearer ' . $this->access_token));
$response = curl_exec($ch);
$http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
print_r($response);
echo $http_status;
}
function getAuthorizationCode() {
$params = array(
'response_type' => 'code',
'client_id' => API_KEY,
'scope' => SCOPE,
'state' => uniqid('', true), // unique long string
'redirect_uri' => REDIRECT_URI,
);
// Authentication request
$url = 'https://www.linkedin.com/uas/oauth2/authorization?' . http_build_query($params);
// Needed to identify request when it returns to us
$_SESSION['state'] = $params['state'];
// Redirect user to authenticate
header("Location: $url");
exit;
}
function getAccessToken() {
$params = array(
'grant_type' => 'authorization_code',
'client_id' => API_KEY,
'client_secret' => API_SECRET,
'code' => $_GET['code'],
'redirect_uri' => REDIRECT_URI,
);
// Access Token request
$url = 'https://www.linkedin.com/uas/oauth2/accessToken?' . http_build_query($params);
// Tell streams to make a POST request
$context = stream_context_create(
array('http' =>
array('method' => 'POST',
)
)
);
// Retrieve access token information
$response = file_get_contents($url, false, $context);
// Native PHP object, please
$token = json_decode($response);
// Store access token and expiration time
$_SESSION['access_token'] = $token->access_token; // guard this!
$_SESSION['expires_in'] = $token->expires_in; // relative time (in seconds)
$_SESSION['expires_at'] = time() + $_SESSION['expires_in']; // absolute time
return true;
}
function fetch($method, $resource, $body = '') {
print $_SESSION['access_token'];
$opts = array(
'http'=>array(
'method' => $method,
'header' => "Authorization: Bearer " . $_SESSION['access_token'] . "\r\n" . "x-li-format: json\r\n"
)
);
// Need to use HTTPS
$url = 'https://api.linkedin.com' . $resource;
// Append query parameters (if there are any)
if (count($params)) { $url .= '?' . http_build_query($params); }
// Tell streams to make a (GET, POST, PUT, or DELETE) request
// And use OAuth 2 access token as Authorization
$context = stream_context_create($opts);
// Hocus Pocus
$response = file_get_contents($url, false, $context);
// Native PHP object, please
return json_decode($response);
}
Finally posted a company update (share) successfully.
One issue that made the LinkedIn code sample (https://developer-programs.linkedin.com/documents/code-samples) non-functional was that file_get_contents() was not working, and this was because allow_url_fopen was not enabled in PHP.ini. I believe allow_url_fopen is not enabled by default, as it is a security issue. I found a work-around online use cUrl. See the code below.
//First, in getAccessToken() replace:
$response = file_get_contents($url, false, $context)
with
$response = curl_get_contents($url);
And here is the code added to the LinkedIn code sample, after the
'print "Hello $user->firstName $user->lastName.";'
// temporary message content for test purposes
$xml_txt = "<?xml version='1.0' encoding='UTF-8'?>
<share>
<visibility>
<code>anyone</code>
</visibility>
<comment>There are a lot of great career opportunities here!</comment>
</share>";
//Post the message
$result = PostUpdate($xml_txt);
//Done
exit;
function PostUpdate($message) {
print 'here in PostUpdate <br />';
print '$message = ' . $message .' <br />';
$url = 'https://api.linkedin.com/v1/companies/'. COMPANY_ID . '/shares';
// build your message
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $message );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/xml', 'Authorization: Bearer ' . $_SESSION['access_token']));
$response = curl_exec($ch);
$http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
print_r($response);
echo '$http_status = '. $http_status;
}
function curl_get_contents($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
Maybe it aint pretty, but after a couple of days struggling with it, I feel surprisingly elated. And thank you LinkedIn for providing a lets-all-reinvent the-wheel code sample with a built-in "issue". If you folks wipe your tail-ends the same half-arsed way you provide code samples, yer walking around with three inches of dried skidmarks in yer undies. Crusty, you know whut I'm sayin.
I wants to add posts in Wordpress site using xml-rpc and curl OR any alternate method without logging in WP admin. Is this possible?
I got the answer and Following code is working for me.
function wpPostXMLRPC ($title,$body,$rpcurl,$username,$password,$category='Uncategorized',$keywords='',$encoding='UTF-8') {
$title = htmlentities($title,ENT_NOQUOTES,$encoding);
$keywords = htmlentities($keywords,ENT_NOQUOTES,$encoding);
$content = array (
'title'=>$title,
'description'=>$body,
'mt_allow_comments'=>0,
'mt_allow_pings'=>0,
'post_type'=>'post',
'mt_keywords'=>$keywords,
'categories'=>array(
$category
)
);
$params = array(
0,
$username,
$password,
$content,
true
);
$request = xmlrpc_encode_request('metaWeblog.newPost', $params);
$ch = curl_init();
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
curl_setopt($ch, CURLOPT_URL, $rpcurl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 1);
$results = curl_exec($ch);
curl_close($ch);
return $results;
}
$title = 'post-title';
$body = 'POST BODY WILL GOES HERE';
$rpcurl = 'http://example.com/xmlrpc.php';
$username = 'xxx';
$password = 'xxx';
$category = 'test';
$chk = wpPostXMLRPC($title,$body,$rpcurl,$username,$password,$category,$keywords='',$encoding='UTF-8');
if($chk) {
echo $chk;
} else {
echo 'failed';
}
There is a built-in feature in Wordpress that allow you to publish an article via e-mail. Never tested it though, but it may suit your needs.
You can configure it in your site's admin, under settings > writing (URL is like http://yourwordpresssite.com/wp-admin/options-writing.php).
However, if you need an API, you'll find useful things in Wordpress Codex pages related to XML-RPC support and wp.newPost.
For a code sample, you can have a look at this snippet, which seems a good basis to me.