How to reset user password by wordpress rest api - wordpress-rest-api

Any one of you know know to send a reset link for lost password by wordpress rest api ? I have been looking into wordpress rest api documentation but I haven't find out anything about it. Maybe someone has done a custom function for that.

I found out a way to do that:
function runRetrivePassword($data)
{
global $wpdb, $wp_hasher;
$user_data = get_user_by('email', $data['email']);
if (!$user_data) return array('result' => false);
do_action('lostpassword_post');
$user_login = $user_data->user_login;
$user_email = $user_data->user_email;
$key = get_password_reset_key($user_data);
$message = __('Someone requested that the password be reset for the following account:') . "\r\n\r\n";
$message .= network_home_url('/') . "\r\n\r\n";
$message .= sprintf(__('Username: %s'), $user_login) . "\r\n\r\n";
$message .= __('If this was a mistake, just ignore this email and nothing will happen.') . "\r\n\r\n";
$message .= __('To reset your password, visit the following address:') . "\r\n\r\n";
$message .= network_site_url("wp-login.php?action=rp&key=$key&login=" . rawurlencode($user_login), 'login');
if (is_multisite())
$blogname = $GLOBALS['current_site']->site_name;
else
$blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
$title = sprintf(__('[%s] Password Reset'), $blogname);
$title = apply_filters('retrieve_password_title', $title);
$message = apply_filters('retrieve_password_message', $message, $key);
if ($message && !wp_mail($user_email, $title, $message))
wp_die(__('The e-mail could not be sent.') . "<br />\n" . __('Possible reason: your host may have disabled the mail() function...'));
return array('result' => true);
}
add_action('rest_api_init', function () {
register_rest_route('apiuser/v1', '/forgotpwd/(?P<email>\S+)', array(
'methods' => 'GET',
'callback' => 'runRetrivePassword'
));
});

Related

PayPal sends multiple IPN's

I have this code, everything works fine. It's just that PayPal keeps resending multiple IPNs. I have read the forum of PayPal and they say that PayPal isn't getting a HTTP/1.1 200 OK from me, so it keeps resending the IPN. How would I go about this?
function sql_execute($sql){
$sql_connect = #mysql_connect($_SERVER['HTTP_HOST'].':3306','root', '****') or
die('Could not connect: ' . mysql_error());
mysql_select_db('4bkk');
mysql_query($sql);
$rows = mysql_affected_rows($sql_connect); //mysql_insert_id();
mysql_close();
return $rows;
}
function sql_query($sql){
// echo $sql;
$sql_connect = #mysql_connect($_SERVER['HTTP_HOST'].':3306','****', 'zzz111') or
die('Could not connect: ' . mysql_error());
mysql_select_db('4bkk');
$rs = mysql_query($sql) or die(mysql_error());
mysql_close();
return $rs;
}
function logtrace($o){
$q = "INSERT INTO log (trace, trace_time) VALUES ('$o', NOW() )";
sql_query($q);
}
function send_email($t,$s,$m,$h){
//mail($t, $s, $m, $h);
$fh = fopen('result_ipn_test.txt', 'w');
fwrite($fh, $t.' '.$s.' '.$m.' '.$h);
fclose($fh);
logtrace('Mail is sent and exit called');
exit();
}
logtrace('__________NEW SESSION__________');
$url = 'https://www.sandbox.paypal.com/cgi-bin/webscr';
$postFields = 'cmd=_notify-validate';
foreach($_POST as $key => $value)
{
$postFields .= "&$key=".urlencode($value);
}
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $postFields
));
$result = curl_exec($ch);
$info = curl_getinfo($ch);
logtrace($info['url']);
curl_close($ch);
//get buyers information from PAYPAL checkout
$email = $_POST['payer_email'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$amount = $_POST['amount3'];
$plan = $_POST['option_selection1'];
logtrace($email.' -- '.$active);
$q = "SELECT * FROM users WHERE email='$email' AND user_level='' AND active='unverified'"; //Unprocessed record = no user_level and active = 'unverified'
$ex = sql_execute($q);
//logtrace("THIS ".$q." => ".$ex);
if(sql_execute($q)){
logtrace('IT IS TRUE');
$flag = TRUE;
}
else{
logtrace('FALSE');
$flag = FALSE;
}
logtrace($result.' RESPONSE FROM PAYPAL');
if(($result=='VERIFIED') && $flag){ //Checks first if PayPal is valid, email address exists in
//records and checks if user_level='' and active='unverified',
//if not enters.
logtrace('USER IS READY FOR VERIFICATION');
$q = "SELECT * FROM users WHERE email='$email'";
$data = sql_query($q);
$con = mysql_fetch_array($data);
//Get buyers information from the database
$email2 = $con['email'];
$first_name = $con['first_name'];
$last_name = $con['last_name'];
$active = $con['active'];
$user_level = $con['user_level'];
logtrace('Emails match');
$u = "UPDATE users SET active='verified', user_level='$plan' WHERE email='$email' LIMIT 1";
if (sql_query($u)) { //Successful verification
logtrace('|| Update was sucessful');
}
else{ // Unsuccessful verification.
logtrace('|| Something went wrong with update.');
}
}
else{ // The user doesn't have any record in the database.
$q = "SELECT * FROM users WHERE email='$email' AND (user_level='Monthly' OR user_level='Quarterly' OR user_level='Yearly')";
if(sql_execute($q)){ // The user is already verified
logtrace('THE USER IS ALREADY VERIFIED');
}
else{ // The user does not exist.
logtrace('THE USER HAS NO RECORD ON DATABASE');
}
}
Please refer the sample code https://www.x.com/instant-payment-notification-4
Based on the above code you can try setting curl options for
CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1
CURLOPT_HTTPHEADER, array('Connection: Close')
in your above code where you set as curl_setopt_array ...
This should resolve your HTTP/1.1 200 OK issue I think.

How to send Push Notification to multiple devices?

This is the first time I am using push notification in my App. I have gone through sample applications along with books and I got how to send push notification to a single device. But I am not getting exactly what changes should I do in my program to send push notification to multiple devices. I am using 'PushMeBaby' application for server side coding.
Please, help me out.
Try this example code and modify for your environment.
$apnsHost = '<APNS host>';
$apnsPort = <port num>;
$apnsCert = '<cert>';
$streamContext = stream_context_create();
stream_context_set_option($streamContext, 'ssl', 'local_cert', $apnsCert);
$apns = stream_socket_client('ssl://' . $apnsHost . ':' . $apnsPort, $error, $errorString, 60, STREAM_CLIENT_CONNECT, $streamContext);
$payload['aps'] = array('alert' => 'some notification', 'badge' => 0, 'sound' => 'none');
$payload = json_encode($payload);
// Note: $device_tokens_array has list of 5 devices' tokens
for($i=0; $i<5; $i++)
{
$apnsMessage = chr(0) . chr(0) . chr(32) . pack('H*', str_replace(' ', '', $device_tokens_array[i])) . chr(0) . chr(strlen($payload)) . $payload;
fwrite($apns, $apnsMessage);
}?>
This article helps verifying drop connection and connection status: Apple Push Notification: Sending high volumes of messages
Other reference links:
How can I send push notification to multiple devices in one go in iPhone?
and
how to handle multiple devices when using Push Notification?
I found that you have to create a new stream_context_create for each fwrite to prevent apple from closing the connection for a bad token.
This is what I have done here
<?php
set_time_limit(0);
$root_path = "add your root path here";
require_once($root_path."webroot\cron\library\config.php");
require_once($root_path."Vendor\ApnsPHP\Autoload.php");
global $obj_basic;
// Basic settings
$timezone = new DateTimeZone('America/New_York');
$date = new DateTime();
$date->setTimezone($timezone);
$time = $date->format('H:i:s');
//Get notifications data to send push notifications
$queueQuery = " SELECT `notifications`.*, `messages`.`mes_message`, `messages`.`user_id`, `messages`.`mes_originated_from` FROM `notifications`
INNER JOIN `messages`
ON `notifications`.`message_id` = `messages`.`mes_id`
WHERE `notifications`.`created` <= NOW()";
$queueData = $obj_basic->get_query_data($queueQuery);
if(!empty($queueData)) {
// Put your private key's passphrase here:
$passphrase = 'Push';
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'server_certificates_bundle_sandbox.pem');
stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
// Open a connection to the APNS server
$fp = stream_socket_client(
'ssl://gateway.sandbox.push.apple.com:2195', $err,
$errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);
if (!$fp)
exit("Failed to connect: $err $errstr" . PHP_EOL);
echo '<br>'.date("Y-m-d H:i:s").' Connected to APNS' . PHP_EOL;
foreach($queueData as $val) {
// Put your device token here (without spaces):
$deviceToken = $val['device_token'];
// Create message
// Get senders name
$sql = "SELECT `name` FROM `users` WHERE id =".$val['user_id'];
$name = $obj_basic->get_query_data($sql);
$name = $name[0]['name'];
$message = $name." : ";
// Get total unread messaged for receiver
$query = "SELECT COUNT(*) as count FROM `messages` WHERE mes_parent = 0 AND user_id = ".$val['user_id']." AND mes_readstatus_doc != 0 AND mes_status = 1";
$totalUnread = $obj_basic->get_query_data($query);
$totalUnread = $totalUnread[0]['count'];
$message .= " This is a test message.";
// Create the payload body
$body['aps'] = array(
'alert' => $message,
'badge' => $totalUnread,
'sound' => 'default'
);
// Encode the payload as JSON
$payload = json_encode($body);
// Build the binary notification
$msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;
// Send it to the server
$result = fwrite($fp, $msg, strlen($msg));
if (!$result) {
echo '<br>'.date("Y-m-d H:i:s").' Message not delivered' . PHP_EOL;
} else {
$sqlDelete = "DELETE FROM `notifications` WHERE id = ".$val['id'];
$query_delete = $obj_basic->run_query($sqlDelete,'DELETE');
echo '<br>'.date("Y-m-d H:i:s").' Message successfully delivered' . PHP_EOL;
}
}
// Close the connection to the server
fclose($fp);
echo '<br>'.date("Y-m-d H:i:s").' Connection closed to APNS' . PHP_EOL;
} else {
echo '<br>'.date("Y-m-d H:i:s").' Queue is empty!';
}

paypal express checkout problem

Hi I am integrating paypal with my website. I want that user enter their all information on my site (creditcard information and personal information).
I have down loded paypalfunctions.php from paypal developer website.
My code is :-
if(isset($_POST['submitCard']))
{
$firstName =trim($_POST['firstName']);
$lastName =trim($_POST['lastName']);
$street =trim($_POST['street']);
$city =trim($_POST['city']);
$state =trim($_POST['state']);
$zip =trim($_POST['zip']);
$countryCode =$_POST['country'];
$currencyCode ='USD';
$paymentType ='Sale';
$paymentAmount =$_POST['productPrice'];
$creditCardType =$_POST['cardType'];
$creditCardNumber=$_POST['cardNo'];
$expDate ='122015';
$cvv2 =$_POST['cvv'];
$returnResult=DirectPayment( $paymentType, $paymentAmount, $creditCardType, $creditCardNumber,
$expDate, $cvv2, $firstName, $lastName, $street, $city, $state, $zip,
$countryCode, $currencyCode );
echo '<pre>';
print_r($returnResult);
DirectPayment method is in paypalFunctions.php and this is
function DirectPayment( $paymentType, $paymentAmount, $creditCardType, $creditCardNumber,
$expDate, $cvv2, $firstName, $lastName, $street, $city, $state, $zip,
$countryCode, $currencyCode )
{
//Construct the parameter string that describes DoDirectPayment
$nvpstr = "&AMT=" . $paymentAmount;
$nvpstr = $nvpstr . "&CURRENCYCODE=" . $currencyCode;
$nvpstr = $nvpstr . "&PAYMENTACTION=" . $paymentType;
$nvpstr = $nvpstr . "&CREDITCARDTYPE=" . $creditCardType;
$nvpstr = $nvpstr . "&ACCT=" . $creditCardNumber;
$nvpstr = $nvpstr . "&EXPDATE=" . $expDate;
$nvpstr = $nvpstr . "&CVV2=" . $cvv2;
$nvpstr = $nvpstr . "&FIRSTNAME=" . $firstName;
$nvpstr = $nvpstr . "&LASTNAME=" . $lastName;
$nvpstr = $nvpstr . "&STREET=" . $street;
$nvpstr = $nvpstr . "&CITY=" . $city;
$nvpstr = $nvpstr . "&STATE=" . $state;
$nvpstr = $nvpstr . "&COUNTRYCODE=" . $countryCode;
$nvpstr = $nvpstr . "&IPADDRESS=" . $_SERVER['REMOTE_ADDR'];
$resArray=hash_call("DoDirectPayment", $nvpstr);
return $resArray;
}
/**
'-------------------------------------------------------------------------------------------------------------------------------------------
* hash_call: Function to perform the API call to PayPal using API signature
* #methodName is name of API method.
* #nvpStr is nvp string.
* returns an associtive array containing the response from the server.
'-------------------------------------------------------------------------------------------------------------------------------------------
*/
function hash_call($methodName,$nvpStr)
{
//declaring of global variables
global $API_Endpoint, $version, $API_UserName, $API_Password, $API_Signature;
global $USE_PROXY, $PROXY_HOST, $PROXY_PORT;
global $gv_ApiErrorURL;
global $sBNCode;
//setting the curl parameters.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$API_Endpoint);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
//turning off the server and peer verification(TrustManager Concept).
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POST, 1);
//if USE_PROXY constant set to TRUE in Constants.php, then only proxy will be enabled.
//Set proxy name to PROXY_HOST and port number to PROXY_PORT in constants.php
if($USE_PROXY)
curl_setopt ($ch, CURLOPT_PROXY, $PROXY_HOST. ":" . $PROXY_PORT);
//NVPRequest for submitting to server
$nvpreq="METHOD=" . urlencode($methodName) . "&VERSION=" . urlencode($version) . "&PWD=" . urlencode($API_Password) . "&USER=" . urlencode($API_UserName) . "&SIGNATURE=" . urlencode($API_Signature) . $nvpStr . "&BUTTONSOURCE=" . urlencode($sBNCode);
//setting the nvpreq as POST FIELD to curl
curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);
//getting response from server
$response = curl_exec($ch);
//convrting NVPResponse to an Associative Array
$nvpResArray=deformatNVP($response);
$nvpReqArray=deformatNVP($nvpreq);
$_SESSION['nvpReqArray']=$nvpReqArray;
if (curl_errno($ch))
{
// moving to display page to display curl errors
$_SESSION['curl_error_no']=curl_errno($ch) ;
$_SESSION['curl_error_msg']=curl_error($ch);
//Execute the Error handling module to display errors.
}
else
{
//closing the curl
curl_close($ch);
}
return $nvpResArray;
}
}
?>
it gives error
Array
(
[TIMESTAMP] => 2010-12-21T06:06:54Z
[CORRELATIONID] => 1cafc53222e76
[ACK] => Failure
[VERSION] => 64
[BUILD] => 1620725
[L_ERRORCODE0] => 10002
[L_SHORTMESSAGE0] => Security error
[L_LONGMESSAGE0] => Security header is not valid
[L_SEVERITYCODE0] => Error
)
i cant understand what is problem is going on.Please help.
Here are a few things to need to worry about as well:
Login to the developer site:
https://developer.paypal.com/
Go to Applications
On the left side, hit "Sandbox Accounts"
You should be able to create one of type BUSINESS right there with the "Create Account" button if there isn't one.
Click on the account, choose "Profile", make sure the account is the BUSINESS kind.
The API Credentials tab will the display the username/password/signature you want to use.
If you don't use the credentials of a sandbox account when using the sandbox url, you are likely to get this 10002 Security error not valid code.
Have configure your API credentials correctly?
you can dump the hash_call out if needed.
If you are doing sandbox testing,
Make sure the endpoint of the call is: https://api-3t.sandbox.paypal.com/nvp
-- pointed to the 'SANDBOX'

Apple push notification service - no notification on device

This problem is driving me crazy. I'm implementing APNS. I already google and followed several tutorials. I implemented the server an it seems to work find here is the code:
<?php
$deviceToken = 'XXXX';
// Passphrase for the private key (ck.pem file)
// $pass = '';
// Get the parameters from http get or from command line
$message = $_GET['message'] or $message = $argv[1] or $message = 'Message received from javacom';
$badge = (int)$_GET['badge'] or $badge = (int)$argv[2];
$sound = $_GET['sound'] or $sound = $argv[3];
// Construct the notification payload
$body = array();
$body['aps'] = array('alert' => $message);
if ($badge)
$body['aps']['badge'] = $badge;
if ($sound)
$body['aps']['sound'] = $sound;
/* End of Configurable Items */
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'ck.pem');
// assume the private key passphase was removed.
//stream_context_set_option($ctx, 'ssl', 'passphrase', $pass);
$fp = stream_socket_client('ssl://gateway.sandbox.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx); // for production change the server to ssl://gateway.push.apple.com:219
if (!$fp) {
print "Failed to connect $err $errstr\n";
return;
} else {
print "Connection OK\n";
}
$payload = json_encode($body);
$msg = chr(0) . pack("n",32) . pack('H*', str_replace(' ', '', $deviceToken)) . pack("n",strlen($payload)) . $payload;
print "sending message :" . $payload . "\n";
fwrite($fp, $msg);
fclose($fp);
?>
It seems to work fine. I don't get any errors. But I don't get any push notification on my device. I don't know where the error could be. I also implemented the feedback script. No error and no output. My App is also prepared.
Thanks in advance.
Apple just released a technical note titled "Troubleshooting Push Notifications". It has tips for both sending and receiving. Maybe something there can help.

Sending multiple iPhone notifications

My code works ok when I need to send one notification, but each time when I need to send more than one, it only sends the first one. Here is the code:
<?php
$device_token = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$apnsHost = 'gateway.sandbox.push.apple.com';
$apnsPort = 2195;
$apnsCert = 'apns-dev.pem';
$streamContext = stream_context_create();
stream_context_set_option($streamContext, 'ssl', 'local_cert', $apnsCert);
$apns = stream_socket_client('ssl://' . $apnsHost . ':' . $apnsPort, $error, $errorString, 60, STREAM_CLIENT_CONNECT, $streamContext);
$payload['aps'] = array('alert' => 'some notification', 'badge' => 0, 'sound' => 'none');
$payload = json_encode($payload);
for($i=0; $i<5; $i++)
{
$apnsMessage = chr(0) . chr(0) . chr(32) . pack('H*', str_replace(' ', '', $device_token)) . chr(0) . chr(strlen($payload)) . $payload;
fwrite($apns, $apnsMessage);
}?>
What am I doing wrong?
Thx in advance,
Mladjo
You should open the connection to apns only once. Right now you are opening it in the loop which is wrong. I'm also using a slightly different scheme to build my messages. You should instead do it in this way:
$apns = stream_socket_client('ssl://' . $apnsHost . ':' . $apnsPort, $error, $errorString, 60, STREAM_CLIENT_CONNECT, $streamContext);
for($i=0; $i<5; $i++)
{
$apns_message = chr(0).pack('n', 32).pack('H*', $device_token).pack('n', strlen($payload)).$payload;
fwrite($apns, $apnsMessage);
}?>
Also note that apple recommends using the same connection to send all your push notifications so you shouldn't connect every time you have a push notification to send.
Have a look at the following document:
http://developer.apple.com/library/mac/#documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CommunicatingWIthAPS/CommunicatingWIthAPS.html#//apple_ref/doc/uid/TP40008194-CH101-SW3
It says that multiple notifications should be sent in a single transmission using the TCP/IP Nagle algorithm. You can find out what the Nagle algorithm is here:
http://en.wikipedia.org/wiki/Nagle%27s_algorithm
so I believe the code to create the message should look like:
// Create the payload body
$body['aps'] = array(
'alert' => "My App Message",
'badge' => 1);
// Encode the payload as JSON
$payload = json_encode($body);
// Loop through the token file and create the message
$msg = "";
$token_file = fopen("mytokens.txt","r");
if ($token_file) {
while ($line = fgets($token_file)) {
if (preg_match("/,/",$line)) {
list ($deviceToken,$active) = explode (",",$line);
if (strlen($deviceToken) == 64 && intval($active) == 1) {
// Build the binary notification
$msg .= chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;
}
}
}
fclose ($token_file);
}
if ($msg == "") {
echo "No phone registered for push notification";
exit;
}
And now open the TCP connection and send the Message....
Taking a shot in the dark here. Looking at your for loop.
It looks like you open the connection and push the message... but does that connection close itself? Do you need to initiate a new connection for each push thereby making it necessary to close the first connection at the end of the while loop before re-initiating another?