Using PayPal IPN - How do I choose recipient of payment? - paypal

Below is the script I am using for processing credit cards. Right now, the payment goes to me based on $clientId and $clientSecret. I am needing the recipient to be variable based on a users paypal email. If I have the users PayPal email, how would I go about pulling the appropriate information to send the money to the user?
#!/usr/bin/php
<?php
# Sandbox
$host = 'https://api.sandbox.paypal.com';
$clientId = 'ATopphBpQ1BOCE3Bi5QLdXH8XjH_btoKoXXHsMNSUVe9cx_nbiB0fpglcwNE';
$clientSecret = 'EFvOWhDKf9-F9uEEHaA4LV_t373Zk-B0-h2vT6d-1BjaqsrPo_DWH74wTJ_M';
$token = '';
// function to read stdin
function read_stdin() {
$fr=fopen("php://stdin","r"); // open our file pointer to read from stdin
$input = fgets($fr,128); // read a maximum of 128 characters
$input = rtrim($input); // trim any trailing spaces.
fclose ($fr); // close the file handle
return $input; // return the text entered
}
function get_access_token($url, $postdata) {
global $clientId, $clientSecret;
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_USERPWD, $clientId . ":" . $clientSecret);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postdata);
# curl_setopt($curl, CURLOPT_VERBOSE, TRUE);
$response = curl_exec( $curl );
if (empty($response)) {
// some kind of an error happened
die(curl_error($curl));
curl_close($curl); // close cURL handler
} else {
$info = curl_getinfo($curl);
echo "Time took: " . $info['total_time']*1000 . "ms<br>";
curl_close($curl); // close cURL handler
if($info['http_code'] != 200 && $info['http_code'] != 201 ) {
echo "Received error: " . $info['http_code']. "<br>";
echo "Raw response:".$response."<br>";
die();
}
}
// Convert the result from JSON format to a PHP array
$jsonResponse = json_decode( $response );
return $jsonResponse->access_token;
}
function make_post_call($url, $postdata) {
global $token;
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Authorization: Bearer '.$token,
'Accept: application/json',
'Content-Type: application/json'
));
curl_setopt($curl, CURLOPT_POSTFIELDS, $postdata);
#curl_setopt($curl, CURLOPT_VERBOSE, TRUE);
$response = curl_exec( $curl );
if (empty($response)) {
// some kind of an error happened
die(curl_error($curl));
curl_close($curl); // close cURL handler
} else {
$info = curl_getinfo($curl);
echo "Time took: " . $info['total_time']*1000 . "ms<br>";
curl_close($curl); // close cURL handler
if($info['http_code'] != 200 && $info['http_code'] != 201 ) {
echo "Received error: " . $info['http_code']. "<br>";
echo "Raw response:".$response."<br>";
die();
}
}
// Convert the result from JSON format to a PHP array
$jsonResponse = json_decode($response, TRUE);
return $jsonResponse;
}
function make_get_call($url) {
global $token;
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Authorization: Bearer '.$token,
'Accept: application/json',
'Content-Type: application/json'
));
#curl_setopt($curl, CURLOPT_VERBOSE, TRUE);
$response = curl_exec( $curl );
if (empty($response)) {
// some kind of an error happened
die(curl_error($curl));
curl_close($curl); // close cURL handler
} else {
$info = curl_getinfo($curl);
echo "Time took: " . $info['total_time']*1000 . "ms<br>";
curl_close($curl); // close cURL handler
if($info['http_code'] != 200 && $info['http_code'] != 201 ) {
echo "Received error: " . $info['http_code']. "<br>";
echo "Raw response:".$response."<br>";
die();
}
}
// Convert the result from JSON format to a PHP array
$jsonResponse = json_decode($response, TRUE);
return $jsonResponse;
}
echo "<br>";
echo "###########################################<br>";
echo "Obtaining OAuth2 Access Token.... <br>";
$url = $host.'/v1/oauth2/token';
$postArgs = 'grant_type=client_credentials';
$token = get_access_token($url,$postArgs);
echo "Got OAuth Token: ".$token;
echo "<br> <br>";
echo "###########################################<br>";
echo "Making a Credit Card Payment... <br>";
$url = $host.'/v1/payments/payment';
$payment = array(
'intent' => 'sale',
'payer' => array(
'payment_method' => 'credit_card',
'funding_instruments' => array ( array(
'credit_card' => array (
'number' => '5500005555555559',
'type' => 'mastercard',
'expire_month' => 12,
'expire_year' => 2018,
'cvv2' => 111,
'first_name' => 'Joe',
'last_name' => 'Shopper'
)
))
),
'transactions' => array (array(
'amount' => array(
'total' => '7.47',
'currency' => 'USD'
),
'description' => 'payment by a credit card using a test script'
))
);
echo "<b>Payer Variable Details:</b> :";
print_r($payment['payer']);
$json = json_encode($payment);
$json_resp = make_post_call($url, $json);
foreach ($json_resp['links'] as $link) {
if($link['rel'] == 'self'){
$payment_detail_url = $link['href'];
$payment_detail_method = $link['method'];
}
}
$related_resource_count = 0;
$related_resources = "";
foreach ($json_resp['transactions'] as $transaction) {
if($transaction['related_resources']) {
$related_resource_count = count($transaction['related_resources']);
foreach ($transaction['related_resources'] as $related_resource) {
if($related_resource['sale']){
$related_resources = $related_resources."sale ";
$sale = $related_resource['sale'];
foreach ($sale['links'] as $link) {
if($link['rel'] == 'self'){
$sale_detail_url = $link['href'];
$sale_detail_method = $link['method'];
}else if($link['rel'] == 'refund'){
$refund_url = $link['href'];
$refund_method = $link['method'];
}
}
} else if($related_resource['refund']){
$related_resources = $related_resources."refund";
}
}
}
}
echo "Payment Created successfully: " . $json_resp['id'] ." with state '". $json_resp['state']."'<br>";
echo "Payment related_resources:". $related_resource_count . "(". $related_resources.")";
echo "<br> <br>";
echo "###########################################<br>";
echo "Obtaining Payment Details... <br>";
$json_resp = make_get_call($payment_detail_url);
echo "Payment details obtained for: " . $json_resp['id'] ." with state '". $json_resp['state']. "'";
echo "<br> <br>";
echo "###########################################<br>";
echo "Obtaining Sale details...<br>";
$json_resp = make_get_call($sale_detail_url);
echo "Sale details obtained for: " . $json_resp['id'] ." with state '". $json_resp['state']."'";
echo "<br> <br>";
echo "###########################################<br>";
echo "Refunding a Sale... <br>";
$refund = array(
'amount' => array(
'total' => '7.47',
'currency' => 'USD'
)
);
$json = json_encode($refund);
$json_resp = make_post_call($refund_url, $json);
echo "Refund processed " . $json_resp['id'] ." with state '". $json_resp['state']."'";
echo "<br> <br>";
echo "###########################################<br>";
echo "Obtaining Sale details...<br>";
$json_resp = make_get_call($sale_detail_url);
echo "Sale details obtained for: " . $json_resp['id'] ." with state '". $json_resp['state']."'";
echo "<br> <br>";
echo "###########################################<br>";
echo "Obtaining Payment Details... <br>";
$json_resp = make_get_call($payment_detail_url);
$related_resource_count = 0;
$related_resources = "";
foreach ($json_resp['transactions'] as $transaction) {
if($transaction['related_resources']) {
$related_resource_count = count($transaction['related_resources']);
foreach ($transaction['related_resources'] as $related_resource) {
if($related_resource['sale']){
$related_resources = $related_resources."sale ";
} else if($related_resource['refund']){
$related_resources = $related_resources."refund";
}
}
}
}
echo "Payment details obtained for: " . $json_resp['id'] ." with state '". $json_resp['state']. "' <br>";
echo "Payment related_resources:". $related_resource_count . "(". $related_resources.")";
echo "<br> <br>";
echo "###########################################<br>";
echo "Saving a Credit Card in vault... <br>";
$url = $host.'/v1/vault/credit-card';
$creditcard = array(
'payer_id' => 'testuser#yahoo.com',
'number' => '4417119669820331',
'type' => 'visa',
'expire_month' => 11,
'expire_year' => 2018,
'first_name' => 'John',
'last_name' => 'Doe'
);
$json = json_encode($creditcard);
$json_resp = make_post_call($url, $json);
$credit_card_id = $json_resp['id'];
echo "Credit Card saved ".$credit_card_id." with state '".$json_resp['state']."'";
echo "<br> <br>";
echo "###########################################<br>";
echo "Making a Payment with saved credit card... <br>";
$url = $host.'/v1/payments/payment';
$payment = array(
'intent' => 'sale',
'payer' => array(
'payment_method' => 'credit_card',
'funding_instruments' => array ( array(
'credit_card_token' => array (
'credit_card_id' => $credit_card_id,
'payer_id' => 'testuser#yahoo.com'
)
))
),
'transactions' => array (array(
'amount' => array(
'total' => '7.47',
'currency' => 'USD'
),
'description' => 'payment using a saved card'
))
);
$json = json_encode($payment);
$json_resp = make_post_call($url, $json);
echo "Payment Created successfully: " . $json_resp['id'] ." with state '". $json_resp['state']."'<br>";
echo "<br> <br>";
echo "###########################################<br>";
echo "Obtaining all Payments (list) ... <br>";
$payment_list_url = $host.'/v1/payments/payment?start_id=PAY-1JJ14633E59990232KE6QU3I';
$json_resp = make_get_call($payment_list_url);
echo "Number of Payment resources returned: " . count($json_resp['payments']);
$counter = 0;
foreach ($json_resp['payments'] as $payment) {
echo "<br>" . $counter++ . ". " . $payment['id'];
}
echo "<br>Next Payment ID: ". $json_resp['next_id'];
echo "<br>Obtaining subset (2-4) of the Payments ... <br>";
$payment_list_url = $host.'/v1/payments/payment?start_index=1&count=3';
$json_resp = make_get_call($payment_list_url);
echo "Number of Payment resources returned: " . count($json_resp['payments']);
$counter = 0;
foreach ($json_resp['payments'] as $payment) {
echo "<br>" . $counter++ . ". " . $payment['id'];
}
echo "<br>Next Payment ID: ". $json_resp['next_id'];
echo "<br>Obtaining the next 10 starting from the previous next_id ... <br>";
$payment_list_url = $host.'/v1/payments/payment?start_id='.$json_resp['next_id'];
$json_resp = make_get_call($payment_list_url);
echo "Number of Payment resources returned: " . count($json_resp['payments']);
$counter = 0;
foreach ($json_resp['payments'] as $payment) {
echo "<br>" . $counter++ . ". " . $payment['id'];
}
echo "<br> <br>";
echo "###########################################<br>";
echo "Making a Credit Card Authorization... <br>";
$url = $host.'/v1/payments/payment';
$payment = array(
'intent' => 'authorize',
'payer' => array(
'payment_method' => 'credit_card',
'funding_instruments' => array ( array(
'credit_card' => array (
'number' => '5500005555555559',
'type' => 'mastercard',
'expire_month' => 12,
'expire_year' => 2018,
'cvv2' => 111,
'first_name' => 'Joe',
'last_name' => 'Shopper'
)
))
),
'transactions' => array (array(
'amount' => array(
'total' => '7.47',
'currency' => 'USD'
),
'description' => 'payment by a credit card using a test script'
))
);
$json = json_encode($payment);
$json_resp = make_post_call($url, $json);
foreach ($json_resp['links'] as $link) {
if($link['rel'] == 'self'){
$payment_detail_url = $link['href'];
$payment_detail_method = $link['method'];
}
}
$related_resource_count = 0;
$related_resources = "";
foreach ($json_resp['transactions'] as $transaction) {
if($transaction['related_resources']) {
$related_resource_count = count($transaction['related_resources']);
foreach ($transaction['related_resources'] as $related_resource) {
if($related_resource['authorization']){
$related_resources = $related_resources."authorization ";
$authorization = $related_resource['authorization'];
foreach ($authorization['links'] as $link) {
if($link['rel'] == 'self'){
$auth_detail_url = $link['href'];
$auth_detail_method = $link['method'];
}else if($link['rel'] == 'refund'){
$refund_url = $link['href'];
$refund_method = $link['method'];
}else if($link['rel'] == 'void'){
$void_url = $link['href'];
$void_method = $link['method'];
}else if($link['rel'] == 'capture'){
$capture_url = $link['href'];
$capture_method = $link['method'];
}
}
} else if($related_resource['refund']){
$related_resources = $related_resources."refund";
}
}
}
}
echo "Payment Created successfully: " . $json_resp['id'] ." with state '". $json_resp['state']."'<br>";
echo "Payment related_resources:". $related_resource_count . "(". $related_resources.")";
echo "<br> <br>";
echo "###########################################<br>";
echo "Obtaining Payment Details... <br>";
$json_resp = make_get_call($payment_detail_url);
echo "Payment details obtained for: " . $json_resp['id'] ." with state '". $json_resp['state']. "'";
echo "<br> <br>";
echo "###########################################<br>";
echo "Obtaining Authorization details...<br>";
$json_resp = make_get_call($auth_detail_url);
echo "Authorization details obtained for: " . $json_resp['id'] ." with state '". $json_resp['state']."'";
echo "<br> <br>";
echo "###########################################<br>";
echo "Capturing Authorization ...<br>";
$capture = array(
'amount' => array(
'total' => '5.47',
'currency' => 'USD'
)
);
$json = json_encode($capture);
$json_resp = make_post_call($capture_url, $json);
echo "Capture processed " . $json_resp['id'] ." with state '". $json_resp['state']."'";
foreach ($json_resp['links'] as $link) {
if($link['rel'] == 'self'){
$capture_detail_url = $link['href'];
$capture_detail_method = $link['method'];
}else if($link['rel'] == 'refund'){
$refund_url = $link['href'];
$refund_method = $link['method'];
}
}
echo "<br> <br>";
echo "###########################################<br>";
echo "Obtaining Authorization details...<br>";
$json_resp = make_get_call($auth_detail_url);
echo "Authorization details obtained for: " . $json_resp['id'] ." with state '". $json_resp['state']."'";
echo "<br> <br>";
echo "###########################################<br>";
echo "Obtaining Capture details...<br>";
$json_resp = make_get_call($capture_detail_url);
echo "Capture details obtained for: " . $json_resp['id'] ." with state '". $json_resp['state']."'";
echo "<br> <br>";
echo "###########################################<br>";
echo "Refunding a Capture... <br>";
$refund = array(
'amount' => array(
'total' => '2.47',
'currency' => 'USD'
)
);
$json = json_encode($refund);
$json_resp = make_post_call($refund_url, $json);
echo "Refund processed " . $json_resp['id'] ." with state '". $json_resp['state']."'";
echo "<br> <br>";
echo "###########################################<br>";
echo "Obtaining Capture details...<br>";
$json_resp = make_get_call($capture_detail_url);
echo "Capture details obtained for: " . $json_resp['id'] ." with state '". $json_resp['state']."'";
echo "<br> <br>";
echo "###########################################<br>";
echo "Voiding Authorization ...<br>";
$void = array();
$json = json_encode($void);
$json_resp = make_post_call($void_url, $json);
echo "Void processed " . $json_resp['id'] ." with state '". $json_resp['state']."'";
echo "<br> <br>";
echo "###########################################<br>";
echo "Obtaining Authorization details...<br>";
$json_resp = make_get_call($auth_detail_url);
echo "Authorization details obtained for: " . $json_resp['id'] ." with state '". $json_resp['state']."'";
echo "<br> <br>";
echo "###########################################<br>";
echo "Obtaining parent Payment Details for the Authorization ... <br>";
$json_resp = make_get_call($payment_detail_url);
$related_resource_count = 0;
$related_resources = "";
foreach ($json_resp['transactions'] as $transaction) {
if($transaction['related_resources']) {
$related_resource_count = count($transaction['related_resources']);
foreach ($transaction['related_resources'] as $related_resource) {
if($related_resource['authorization']){
$related_resources = $related_resources."authorization ";
} else if($related_resource['capture']){
$related_resources = $related_resources."capture ";
} else if($related_resource['refund']){
$related_resources = $related_resources."refund ";
}
}
}
}
echo "Payment details obtained for: " . $json_resp['id'] ." with state '". $json_resp['state']. "' <br>";
echo "Payment related_resources:". $related_resource_count . "(". $related_resources.")";
echo "<br> <br>";
die;
//END CREDIT CARD FUNCTIONS
//Paypal Payment
echo "###########################################<br>";
echo "Initiating a Payment with PayPal Account... <br>";
$url = $host.'/v1/payments/payment';
$payment = array(
'intent' => 'sale',
'payer' => array(
'payment_method' => 'paypal'
),
'transactions' => array (array(
'amount' => array(
'total' => '7.47',
'currency' => 'USD'
),
'description' => 'payment using a PayPal account'
)),
'redirect_urls' => array (
'return_url' => 'http://project.aimlessmedia.com/001/return.php?cancelled=0&returned=1',
'cancel_url' => 'http://project.aimlessmedia.com/001/return.php?cancelled=1&returned=1'
)
);
$json = json_encode($payment);
$json_resp = make_post_call($url, $json);
foreach ($json_resp['links'] as $link) {
if($link['rel'] == 'execute'){
$payment_execute_url = $link['href'];
$payment_execute_method = $link['method'];
} else if($link['rel'] == 'approval_url'){
$payment_approval_url = $link['href'];
$payment_approval_method = $link['method'];
}
}
echo "Payment Created successfully: " . $json_resp['id'] ." with state '". $json_resp['state']."'<br><br>";
echo "Please goto ".$payment_approval_url." in your browser and approve the payment with a PayPal Account.<br>";
echo "Enter PayerId from the return url to continue:";
$payerId = read_stdin();
echo "<br> <br>";
echo "###########################################<br>";
echo "Executing the PayPal Payment for PayerId (".$payerId.")... <br>";
$payment_execute = array(
'payer_id' => $payerId
);
$json = json_encode($payment_execute);
$json_resp = make_post_call($payment_execute_url, $json);
echo "Payment Execute processed " . $json_resp['id'] ." with state '". $json_resp['state']."'";
echo "<br> <br>";
?>

I believe credit card payments to a recipient's email is not supported as of yet.
Check here: https://developer.paypal.com/webapps/developer/docs/api/#errors (scroll down to "Validation Issues")
Specification of payee by email is not currently supported
You can’t currently use an email to indicate the payee.

Related

reply to sender mail php script

I have been looking for a mailform script and came up with his. Works fine, but just this matter: when I reply to the received email, I am replying to myself, whilst I would like to reply automatically to the mailadres of the sender.
<?php
$to = "MY#MAILADRES.COM";
$subject = "mail via website";
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$onderwerp = $_POST['onderwerp'];
$comments = $_POST['message'];
$message = "
name: $firstname $lastname
email: $email
subject: $onderwerp
message: $comments
";
$mime_boundary="==Multipart_Boundary_x".md5(mt_rand())."x";
$headers = "From: MY#MAILADRES.COM\r\n".
"MIME-Version: 1.0\r\n" .
"Content-Type: multipart/mixed;\r\n" .
" boundary=\"{$mime_boundary}\"";
$message = "This is a multi-part message in MIME format.\n\n" .
"--{$mime_boundary}\n" .
"Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$message . "\n\n";
foreach($_FILES as $userfile)
{
$tmp_name = $userfile['tmp_name'];
$type = $userfile['type'];
$name = $userfile['name'];
$size = $userfile['size'];
if (file_exists($tmp_name))
{
if(is_uploaded_file($tmp_name))
{
$file = fopen($tmp_name,'rb');
$data = fread($file,filesize($tmp_name));
fclose($file);
$data = chunk_split(base64_encode($data));
}
$message .= "--{$mime_boundary}\n" .
"Content-Type: {$type};\n" .
" name=\"{$name}\"\n" .
"Content-Disposition: attachment;\n" .
" filename=\"{$fileatt_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n";
}
}
$message.="--{$mime_boundary}--\n";
if (mail($to, $subject, $message, $headers))
echo "Thanks for getting in touch.<br>Your message wil get my full attention.<br>I will get back to you soon.";
else
echo "Error in mail.<br>Please try again.";
?>
What should I change in this code, please?
I added these (seperately):
$headers .= "From: Contact Form (Domain.com) <no-reply#domain.com>\r\n";
$headers .= "Reply-To: ".$_REQUEST['email']."<". $_REQUEST['email'].">\r\n"
But none seem to work. I got this code to work with and all good, except for the reply-to.

openssl_sign and PHP 4 identical signature for different messages

I have to maintain an application in php 4 that must send signed data via openssl_sign. The issue is that for different data of the same size, the signature is always the same.
Eg. this code:
$signature = null;
$message1 = 'foobar';
$privkey1 = openssl_pkey_get_private('file://path/to/private/key/privkey1.pem');
while ($msg = openssl_error_string()) {
echo $msg . "<br />\n";
}
openssl_sign($message1, $signature, $privkey1);
while ($msg = openssl_error_string()) {
echo $msg . "<br />\n";
}
openssl_free_key($privkey1);
while ($msg = openssl_error_string()) {
echo $msg . "<br />\n";
}
$signature2 = null;
$message2 = 'foobaz';
$privkey2 = openssl_pkey_get_private('file://path/to/private/key/privkey1.pem');
while ($msg = openssl_error_string()) {
echo $msg . "<br />\n";
}
openssl_sign($message2, $signature2, $privkey2);
while ($msg = openssl_error_string()) {
echo $msg . "<br />\n";
}
openssl_free_key($privkey2);
while ($msg = openssl_error_string()) {
echo $msg . "<br />\n";
}
echo base64_encode($signature) . '<br/>';
echo base64_encode($signature2) . '<br/>';
Outputs this:
uANYD6qKuvlcyK2svarB0ESPO7qLa75cEIhCmjkTF23cwveSE+Mxuhsl7JKjOEOPf7v8mCoTLmdlm/2RDD0Nabdpi+5Ez8Di8dFNpXtMVRByJvewOOGxTgYt/1XPIqe+dvLunkqtl8dHkRhtzuBHay1suco53Ybs7r41YKdqnkk=
uANYD6qKuvlcyK2svarB0ESPO7qLa75cEIhCmjkTF23cwveSE+Mxuhsl7JKjOEOPf7v8mCoTLmdlm/2RDD0Nabdpi+5Ez8Di8dFNpXtMVRByJvewOOGxTgYt/1XPIqe+dvLunkqtl8dHkRhtzuBHay1suco53Ybs7r41YKdqnkk=
Does anyone know what the reason of this problem?

Push notification from a Webpage with many devices (Device Tokens)

I created an application with a push notification method. All is working fine. I can get the push notification on my iPhone. I created a sample web application to send push notification. Now, I created a data source for the List of Device tokens. I want my web application to send notifications to many devices(List of devices) that's why I put a sample table on my MySql database containing list of device tokens. My question is, How can I send push notification to many devices at a Time?
Here is my code for php Simplepush.php
<?php
// Put your device token here (without spaces):
$deviceToken = $_POST['devicetoken'];
// Put your private key's passphrase here:
$passphrase = '123jakes123#';
// Put your alert message here:
$message = $_POST['message'];
////////////////////////////////////////////////////////////////////////////////
$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 'Connected to APNS' . PHP_EOL;
// Create the payload body
$body['aps'] = array(
'alert' => $message,
'sound' => 'default',
'badge' => 1
);
// 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 'Message not delivered' . PHP_EOL;
else
echo 'Message successfully delivered' . PHP_EOL;
// Close the connection to the server
fclose($fp);
?>
Code for push notification using list of Device token
<?php
$con=mysqli_connect("localhost", "xxx", "xxxxx","xxxxxx");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM push");
echo "<table border='1'>
<tr>
<th>id</th>
<th>Device Token</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['token'] . "</td>";
echo "</tr>";
$deviceToken = $row['token'];
$passphrase = '123jakes123#';
$message = $_POST['message'];
}
echo "</table>";
////////////////////////////////////////////////////////////////////////////////
$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 'Connected to APNS' . PHP_EOL;
// Create the payload body
$body['aps'] = array(
'alert' => $message,
'sound' => 'default',
'badge' => 1
);
// 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 'Message not delivered' . PHP_EOL;
else
echo 'Message successfully delivered' . PHP_EOL;
// Close the connection to the server
fclose($fp);
mysqli_close($con);
?>

PHP Form fields will not send to email

I have created a send to email PHP script.
The form seems to work correctly when sending only one field (the message field) but as soon as other fields are added, the form ceases to be emailed on to the inbox (yet the form still fires correctly and reroutes to the thankyou just fine.)
Here is the code I currently have, this does not work
<?php
$email = $_REQUEST['email'] ;
$name = $_REQUEST['name'] ;
$services = $_REQUEST['services'] ;
$message = $_REQUEST['message'] ;
if (!isset($_REQUEST['email'])) {
header( "Location: feedback.html" );
}
elseif (empty($email) || empty($message)) {
header( "Location: error.html" );
}
else {
mail( "info#website.co.uk", "Message via your website!",
$name, $services, $message, "From: $email" );
header( "Location: thankyou.html" );
}
?>
This is the previous code, this does work, but only displays the message
<?php
$email = $_REQUEST['email'] ;
$message = $_REQUEST['message'] ;
if (!isset($_REQUEST['email'])) {
header( "Location: feedback.html" );
}
elseif (empty($email) || empty($message)) {
header( "Location: error.html" );
}
else {
mail( "info#website.co.uk", "Message via your website!",
$message, "From: $email" );
header( "Location: thankyou.html" );
}
?>
This is the HTML for the form:
<form method="post" action="sendmail.php">
<label>Name:</label> <input name="name" type="text" /><br />
<label>Email:</label> <input name="email" type="text" /><br />
<label>What service do you require?:</label> <input name="services" type="text" /><br />
<label>Message:</label><br />
<textarea name="message" rows="15" cols="40">
</textarea><br />
<input type="submit" />
</form>
As per the mail() docs the message body should be passed as a single parameter. So it should look something more like:
mail( "info#website.co.uk", "Message via your website!", "$name\r\n $services\r\n $message", "From: $email");
According to php.net the correct use of the mail() function is:
<?
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Additional headers
$headers .= 'To: Mary <mary#example.com>, Kelly <kelly#example.com>' . "\r\n";
$headers .= 'From: Birthday Reminder <birthday#example.com>' . "\r\n";
$headers .= 'Cc: birthdayarchive#example.com' . "\r\n";
$headers .= 'Bcc: birthdaycheck#example.com' . "\r\n";
// Mail it
mail($to, $subject, $message, $headers);
?>
You are trying to send the additional data ($services) as a header.
Try to merge your $message and $service >
$message = $service . "\r\n\r\n" . $message;
mail( "info#website.co.uk", "Message via your website!",
$message, "From: $email" );
You can't just add more and more variables to mail(). There is only one parameter that specifies the content of the email, which would be the third one, as you can see in the official documentation:
bool mail ( string $to , string $subject , string $message [, string $additional_headers [, string $additional_parameters ]] )
If you want to have more than just $message in your mail, you need to put everything into one variable to be given to the function as content.
$content = $message;
$content .= "\n" . $services;
// etc...
mail($to, $subject, $content);
Try this
<?php
$email = $_POST['email'] ;
$name = $_POST['name'] ;
$services = $_POST['services'] ;
$message = $_POST['message'] ;
if (!isset($_POST['email'])) {
header( "Location: feedback.html" );
}
elseif (empty($email) || empty($message)) {
header( "Location: error.html" );
}
else {
mail( "info#website.co.uk", "Message via your website!",
$name . $services. $message . "From: $email" );
header( "Location: thankyou.html" );
}
?>

PayPal IPN Help (Not UPDATE Database)

Hi there all been trying to get this working for about 2 days now. The Payment is going through no problem but it not update the Database :(
Here is the Code :
<?php
require_once(WWW_DIR."/lib/users.php");
// Connect to database
$con = mysql_connect("localhost","root","******");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-validate';
foreach ($_POST as $key => $value)
{
$value = urlencode(stripslashes($value));
$req .= "&$key=$value";
}
// post back to PayPal system to validate
$header .= "POST /cgi-bin/webscr HTTP/1.0\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
$fp = fsockopen ('ssl://www.sandbox.paypal.com', 443, $errno, $errstr, 30); // Test
//$fp = fsockopen ('ssl://www.paypal.com', 443, $errno, $errstr, 30); // Live
// assign posted variables to local variables
$item_name = $_POST['item_name'];
$payment_status = $_POST['payment_status'];
$payment_amount = $_POST['mc_gross'];
$txn_id = $_POST['txn_id'];
$payer_email = $_POST['payer_email'];
$name = $_POST['first_name'] . " " . $_POST['last_name'];
$address_street = $_POST['address_street'];
$address_zip = $_POST['address_zip'];
$address_city = $_POST['address_city'];
$contact_phone = $_POST['contact_phone'];
$email = $_POST['payer_email'];
$uid = $users->currentUserId();
//timezone set
date_default_timezone_set('Europe/London');
if (!$fp)
{
// HTTP ERROR
} else
{
fputs($fp, $header . $req);
while (!feof($fp))
{
$res = fgets($fp, 1024);
if (strcmp($res, "VERIFIED") == 0) {
if($payment_status != "Completed"){
if($payment_amount == 2.00)
{
$role = 6;
}
else
if($payment_amount == 5.00)
{
$role = 8;
}
else
if($payment_amount == 8.00)
{
$role = 9;
}
//update user records
$sql = sprintf("UPDATE users SET role = %d WHERE ID = %d", $role, $uid);
mysql_query($sql);
//log payment
//mysql_query("INSERT INTO payments (email, item_name, payment_status, txn_id, payment_ammount) VALUES('" . mysql_escape_string($email) . "', '" . $item_name . "', '" . $payment_status . "', '" . $txn_id . "', '" . $payment_amount . "' ) ") or die(mysql_error());
}} else
if (strcmp($res, "INVALID") == 0)
{
// log for manual investigation
}
}
fclose($fp);
}
?>
If you have any Questions just ask I will try and Answer ASAP if you could get this working I would be very happy
Thanks
Change:
// post back to PayPal system to validate
$header .= "POST /cgi-bin/webscr HTTP/1.0\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
To:
// post back to PayPal system to validate
$header .= "POST /cgi-bin/webscr HTTP/1.1\r\n";
$header .= "Host: www.sandbox.paypal.com\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n";
$header .= "Connection: close\r\n\r\n";
Change:
if (strcmp($res, "VERIFIED") == 0) {
To:
if (strcmp(trim($res), "VERIFIED") == 0) {
And lastly, change:
if (strcmp($res, "INVALID") == 0)
To:
if (strcmp(trim($res), "INVALID") == 0)
Reason:
The PayPal Sandbox is configured to reject HTTP 1.0 requests without a Host header specified, so your current script will never properly validate.