Skip to content

Instantly share code, notes, and snippets.

@BlueInkAlchemist
Last active June 8, 2018 23:59
Show Gist options
  • Save BlueInkAlchemist/1a4172882e82b611e6d255899d4fa0a8 to your computer and use it in GitHub Desktop.
Save BlueInkAlchemist/1a4172882e82b611e6d255899d4fa0a8 to your computer and use it in GitHub Desktop.
WordPress PHP Class facilitating automated PayPal transactions.
<?php
class Paypal_Payout_Helper {
protected static $instance = null;
private function __construct() {
}
public static function get_instance() {
if( null == self::$instance ) {
self::$instance = new self;
}
return self::$instance;
}
public function enqueue_scripts() {
wp_enqueue_script( "-plugin-angular", get_stylesheet_directory_uri() . "/js/angular.min.js", array("jquery"), $this->version);
wp_enqueue_script( "-plugin-jobsdone", get_stylesheet_directory_uri() . "/js/jobs-done-process.js", array("jquery"), $this->version);
wp_enqueue_script( "-plugin-testisgo", get_stylesheet_directory_uri() . "/js/recurring-test-process.js", array("jquery"), $this->version);
wp_localize_script( "my_jobs_done_thing", 'ajax-object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
wp_localize_script( "my_recurring_test_thing", 'ajax-object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
public function wp_info_fetch( $field_value, $meta_value ){
global $wpdb;
$results = $wpdb->get_results( "SELECT meta_value FROM wp_postmeta WHERE post_id = " . $field_value . " AND meta_key = '" . $meta_value . "'" );
return $results;
}
public function paypal_renew_sequence() {
global $wpdb;
$request_body = file_get_contents( 'php://input' );
$decodeit = json_decode( $request_body );
$customer_id = $decodeit->customerid;
$worker_id = $decodeit->workerid;
$workroom_id = $decodeit->workroomid;
// call the stored procedure
$wpdb->query("CALL Subs_FetchSubsToRenew();");
foreach( $wpdb->get_results("SELECT * FROM fetchedSubs;") as $key => $row) {
self::do_paypal_payout( $row->ID );
// $to = ''; // Testing Email
// $subject = 'Test from cron';
// $message = 'The cron job is running for ' . $row->ID;
// wp_mail( $to, $subject, $message );
}
}
public function do_paypal_payout( $workroom_id ) {
global $wpdb;
$message = "If you received this message, your payout function is working.\n";
$message .= "Query:\n";
$message .= $workroom_id;
$message .= "\n";
$message .= "Ready for PAYPAL\n";
$message .= "--------------------------------------\n";
//Paypal_Payout_Helper::do_paypal_payout( $workroom_id );
$today = gmdate("Y-m-d\TH:i:s\Z");
$message .= "BEGIN PAYPAL\n";
update_post_meta( $workroom_id, 'last_paydate', $today );
// echo "> ";
// echo $workroom_id . " : ";
// calculate payout: QUERY amount due from workroom based on # of days from 1st query
$to_be_paid = get_post_meta( $workroom_id, 'renewal_amt' );
// calculate payout
$product_id = get_post_meta( $workroom_id, 'product_id', true );
$price = get_post_meta( $product_id, '_price', true );
// echo "price" . $price . " : ";
$percentage = get_post_meta( $product_id, 'workers_0_payout-percent', true );
// echo "percentage" . $percentage . " : ";
if ( $percentage > 1 ) {
$percentage = $percentage / 100;
}
$to_be_paid = floor( $price * $percentage );
// echo "$" . $to_be_paid . " : ";
// apply payout when appropriate: worker id, workroom id, amount, process payment through PayPal
$worker_id = get_post_meta( $product_id, 'workers_0_worker', true );
$worker_data = get_userdata( $worker_id );
$worker_email = $worker_data->user_email;
$worker_email = ''; /* Email for Recipient of Funds */
/*
$transfers = get_post_meta( $workroom_id, 'transfers', true );
if (!$transfers) {
$transfers = 666;
}
echo "xferz : " . $transfers . " : ";
*/
$withdrawalID = $workroom_id . "-" . $today;
// echo "wID = " . $withdrawalID . " : ";
// INSERT PAYPAL API SHENANIGANS HERE
// Set your secret key: remember to change this to your live secret key in production
$payLoad = array();
// Source email
$ppemail = ''; /* Email for Source of Funds */
//prepare the receivers
$receiverList = array();
$counter = 0;
$receiverList["receiver"][$counter]["amount"] = $to_be_paid;
$receiverList["receiver"][$counter]["email"] = $worker_email;
$receiverList["receiver"][$counter]["paymentType"] = "SERVICE"; //this could be SERVICE or PERSONAL (which makes it free!)
$receiverList["receiver"][$counter]["invoiceId"] = $withdrawalID; //NB that this MUST be unique otherwise paypal will reject it and get shitty. However it is a totally optional field
// echo var_dump($receiverList) . " : ";
//prepare the call
$payLoad["actionType"] = "PAY";
$payLoad["cancelUrl"] = "http://www.example.com"; //this is required even though it isnt used
$payLoad["returnUrl"] = "http://www.example.com"; //this is required even though it isnt used
$payLoad["currencyCode"] = "AUD";
$payLoad["receiverList"] = $receiverList;
$payLoad["feesPayer"] = "EACHRECEIVER"; //this could be SENDER or EACHRECEIVER
//$payLoad["fundingConstraint"]=array("allowedFundingType"=>array("fundingTypeInfo"=>array("fundingType"=>"BALANCE")));//defaults to ECHECK but this takes ages and ages, so better to reject the payments if there isnt enough money in the account and then do a manual pull of bank funds through; more importantly, echecks have to be accepted/rejected by the user and i THINK balance doesnt
$payLoad["sender"]["email"] = $ppemail; //the paypal email address of the where the money is coming from
//define API signature credentials
$ppuserid = ""; /* Facilitator User ID */
$pppass = ""; /* PayPal Passcode */
$ppsig = "";/* PayPal Signature */
$ppappid = ""; /* PayPal App ID */
//run the Pay call
$message .= "PAY CALL RESPONSE\n";
$Pay_API_Endpoint = "https://svcs.sandbox.paypal.com/AdaptivePayments/Pay";
$payLoad["requestEnvelope"] = array( "errorLanguage"=>urlencode( "en_US" ),"detailLevel"=>urlencode( "ReturnAll" ) );//add some debugging info the payLoad and setup the requestEnvelope
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $Pay_API_Endpoint);
curl_setopt( $ch, CURLOPT_VERBOSE, 1 );
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 );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array(
'X-PAYPAL-REQUEST-DATA-FORMAT: JSON',
'X-PAYPAL-RESPONSE-DATA-FORMAT: JSON',
'X-PAYPAL-SECURITY-USERID: '. $ppuserid,
'X-PAYPAL-SECURITY-PASSWORD: '. $pppass,
'X-PAYPAL-SECURITY-SIGNATURE: '. $ppsig,
'X-PAYPAL-APPLICATION-ID: '. $ppappid
) );
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $payLoad ) );//
$payResponse = curl_exec( $ch );
$payResponse = json_decode( $payResponse, 1 );
//analyse the output
$payKey = $payResponse["payKey"];
$paymentExecStatus = $payResponse["paymentExecStatus"];
$correlationId = $payResponse["responseEnvelope"]["correlationId"];
$paymentInfoList = isset( $payResponse["paymentInfoList"] ) ? $response["paymentInfoList"] : null;
if ( $paymentExecStatus<>"ERROR" ) {
foreach($paymentInfoList["paymentInfo"] as $paymentInfo) {//they will only be in this array if they had a paypal account
$receiverEmail = $paymentInfo["receiver"]["email"];
$receiverAmount = $paymentInfo["receiver"]["amount"];
$withdrawalID = $paymentInfo["receiver"]["invoiceId"];
$transactionId = $paymentInfo["transactionId"];//what shows in their paypal account
$senderTransactionId = $paymentInfo["senderTransactionId"];//what shows in our paypal account
$senderTransactionStatus = $paymentInfo["senderTransactionStatus"];
$pendingReason = isset( $paymentInfo["pendingReason"] ) ? $paymentInfo["pendingReason"] : null;
}
// indicate success
// echo "paymentExecStatus != ERROR : ";
// echo var_dump($paymentInfo);
$message .= "Success:\n";
} else {
//deal with it
// echo var_dump($response);
// die ( "paymentExecStatus = ERROR" );
$message .= "FAIL:\n";
}
$message .= print_r($payResponse, true);
$message .= "\n";
$message .= "--------------------------------------\n";
//run the Execute call
$message .= "EXECUTE CALL RESPONSE\n";
$Ex_API_Endpoint = "https://svcs.sandbox.paypal.com/AdaptivePayments/ExecutePayment";
$exPayLoad["payKey"] = $payKey;
$exPayLoad["requestEnvelope"] = array( "errorLanguage"=>urlencode( "en_US" ),"detailLevel"=>urlencode( "ReturnAll" ) );//add some debugging info the payLoad and setup the requestEnvelope
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $Ex_API_Endpoint);
curl_setopt( $ch, CURLOPT_VERBOSE, 1 );
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 );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array(
'X-PAYPAL-REQUEST-DATA-FORMAT: JSON',
'X-PAYPAL-RESPONSE-DATA-FORMAT: JSON',
'X-PAYPAL-SECURITY-USERID: '. $ppuserid,
'X-PAYPAL-SECURITY-PASSWORD: '. $pppass,
'X-PAYPAL-SECURITY-SIGNATURE: '. $ppsig,
'X-PAYPAL-APPLICATION-ID: '. $ppappid
) );
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $exPayLoad ) );//
$response = curl_exec( $ch );
$response = json_decode( $response, 1 );
//analyse the output
$paymentExecStatus = $response["paymentExecStatus"];
$correlationId = $response["responseEnvelope"]["correlationId"];
$paymentInfoList = isset( $response["paymentInfoList"] ) ? $response["paymentInfoList"] : null;
if ( $paymentExecStatus<>"ERROR" ) {
foreach($paymentInfoList["paymentInfo"] as $paymentInfo) {//they will only be in this array if they had a paypal account
$receiverEmail = $paymentInfo["receiver"]["email"];
$receiverAmount = $paymentInfo["receiver"]["amount"];
$withdrawalID = $paymentInfo["receiver"]["invoiceId"];
$transactionId = $paymentInfo["transactionId"];//what shows in their paypal account
$senderTransactionId = $paymentInfo["senderTransactionId"];//what shows in our paypal account
$senderTransactionStatus = $paymentInfo["senderTransactionStatus"];
$pendingReason = isset( $paymentInfo["pendingReason"] ) ? $paymentInfo["pendingReason"] : null;
}
// indicate success
// echo "paymentExecStatus != ERROR : ";
// echo var_dump($paymentInfo);
$message .= "Success:\n";
} else {
//deal with it
// echo var_dump($response);
// die ( "paymentExecStatus = ERROR" );
$message .= "FAIL:\n";
}
$message .= print_r($response, true);
$message .= "\n";
$message .= "--------------------------------------\n";
$message .= "END PAYPAL\n";
$message .= "--------------------------------------\n";
$message .= "\n";
// on every pay, update the subscriptions with a new paydate (workroom helper?)
$today = gmdate("Y-m-d\TH:i:s\Z");
$wpdb->update(
$wpdb->prepare(
$wpdb->prefix.'',
array(
'workroom_id' => $workroom_id,
'last_paydate' => $today
),
array('workroom_id' => $workroom_id)
)
);
// testing call with emails
$to = ''; // Testing Email
$subject = 'Test from payout';
wp_mail( $to, $subject, $message );
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment