phpwordpressmollie

Check if Mollie payment is paid


I have been stuck on this for weeks now so I'm dropping my question here, hopefully someone can help me. I have a website where people can sell their car. You buy an advertisement and you can upload your vehicle. I have integrated Mollie Payment API so people can pay with iDeal, but it doesn't seem to read the payment status.

When the payment has been successful, my system doesn't give out an advertisement. How can I check if the payment has been successful and then automatically give out an advertisement if the order has been paid?

This is the code that processes the payments:

<?php
namespace AutoListingsFrontend;

require_once __DIR__ . "/../mollie-api-php/vendor/autoload.php";
require_once __DIR__ . "/../mollie-api-php/examples/functions.php";

class Checkout {
/**
 * Hold our entire Purchase data
 */

public $purchase_data = array();

public function __construct() {
    add_action( 'init', array( $this, 'process_purchase' ) );

    add_action( 'auto_listings_mark_as_pending', array( $this, 'pending_payment' ) );
    add_action( 'auto_listings_send_to_gateway', array( $this, 'send_to_gateway' ) );

    add_action( 'auto_listings_payment_successful', array( $this, 'payment_successful' ), 10, 2 );
    add_action( 'auto_listings_insert_payment_note', array( $this, 'insert_payment_note' ), 10, 2 );
    add_action( 'auto_listings_update_payment_status', array( $this, 'update_payment_status' ), 10, 2 );

    //add_action( 'auto_listings_gateway_paypal', 'auto_listings_process_paypal_purchase' );
}

public function sanitize_post_data() {
    // simple sanitizing
    foreach ( $_POST as $key => $value ) {
        $key = str_replace( 'auto-listings-', '', $key );

        if( $key == 'user-id' ) {
            $sanitized[ $key ] = absint( $value );
        } else {
            $sanitized[ $key ] = sanitize_text_field( $value );
        }

    }
    return $sanitized;
}

/**
 * Process Purchase Form
 *
 * Handles the purchase form process.
 */
public function process_purchase() {
    do_action( 'auto_listings_pre_process_purchase' );

    // Check if there is $_POST
    if ( empty( $_POST ) ) return false;

    if ( ! isset( $_POST['auto-listings-gateway'] ) || empty( $_POST['auto-listings-gateway'] ) )
        return false;
    if ( ! isset( $_POST['auto-listings-package'] ) || empty( $_POST['auto-listings-package'] ) )
        return false;
    if ( ! isset( $_POST['auto-listings-user-id'] ) || empty( $_POST['auto-listings-user-id'] ) )
        return false;

    $data = $this->sanitize_post_data();

    // Verify there is a user_ID
    if ( $data['user-id'] > 0 ) {
        // Get the logged in user data
        $user = get_userdata( $data['user-id'] );
        // Verify data
        if ( ! $user ) {
            return false;
        }
    }

    // Setup user information
    $user_info = array(
        'id'            => $user->ID,
        'email'         => $user->user_email,
        'first_name'    => $user->first_name,
        'last_name'     => $user->last_name,
    );

    // Setup package information
    $package_info = auto_listings_get_package( $data['package'] );

    // Set up the unique purchase key.
    $key = strtolower( md5( $user_info['id'] . date( 'Y-m-d H:i:s' ) . uniqid( 'auto', true ) ) );

    // Setup purchase information
    $purchase_data = array(
        'package'       => stripslashes_deep( $package_info ),
        'purchase_key'  => $key,
        'user'      => stripslashes_deep( $user_info ),
        'date'          => date( 'Y-m-d H:i:s', current_time( 'timestamp' ) ),
        'gateway'       => $data['gateway'],
    );

    // If the total amount in the cart is 0, send to the manual gateway.
    if ( ! $purchase_data['package']['price'] ) {
        $purchase_data['gateway'] = 'manual';
    }

    // Allow the purchase data to be modified before it is sent to the gateway
    $this->purchase_data = apply_filters(
        'auto_listings_purchase_data_before_gateway',
        $purchase_data,
        $data
    );

    // Send info to create the pending payment
    // Send info to the gateway for payment processing
    do_action( 'auto_listings_mark_as_pending' );

    do_action( 'auto_listings_send_to_gateway' );
}

/**
 * Sends all the payment data to the specified gateway.
*/
public function send_to_gateway() {

    $this->purchase_data['gateway_nonce'] = wp_create_nonce( 'auto-listings-gateway' );

    // $gateway must match the ID used when registering the gateway
    do_action( 'auto_listings_gateway_' . $this->purchase_data['gateway'], $this->purchase_data );
}

/**
 * Insert Pending Payment
 *
 * @param array $payment_data Payment data to process
 * @return int|bool Payment ID if payment is inserted, false otherwise
 */
public function pending_payment() {
    if ( empty( $this->purchase_data ) ) {
        return false;
    }

    $payment_title = $this->purchase_data['user']['email'];

    if ( $purchase_data['gateway'] = 'ideal' ) {
    /*
  * Initialize the Mollie API library with your API key.
  *w
  * See: https://www.mollie.com/dashboard/developers/api-keys
  */

     $mollie = new \Mollie\Api\MollieApiClient();
     $mollie->setApiKey("MOLLIE_APIKEY"); // change to LIVE key when done

     $packages = auto_listings_get_packages();

     foreach ( $packages as $package_id => $package ){

     $orderId = $payment->id;
     $prijs = '';

     if(isset($_POST["auto-listings-purchase"])) {

         $package_id = $_POST['auto-listings-package'];

         if($package_id == "3769") {
             $prijs = "10.00";
         } elseif ($package_id == "3767") {
             $prijs = "40.00";
         } else {
             echo "Something went wrong. Please contact our staff via: info@vagplace.nl.";
         }
     }

     // Create Mollie payment
     $payment = $mollie->payments->create([
            "amount" => [
                    "currency" => "EUR",
                    "value" => $prijs,
            ],
            "description" => "VAGplace order: ".$orderId,
            "redirectUrl" => "https://vagplace.nl/mijn-autos/?payment=success&gateway=ideal&order_id=".$orderId,
            "webhookUrl"  => "https://vagplace.nl/mollie-webhook",
            "method"      => \Mollie\Api\Types\PaymentMethod::IDEAL,
            "metadata" => [
        "order_id" => $orderId,
    ],
     ]);

     database_write($orderId, $payment->status);

/*
 * Send the customer off to complete the payment.
 * This request should always be a GET, thus we enforce 303 http response code
 */
     header("Location: " . $payment->getCheckoutUrl(), true, 303);

     }
 }

    $payment_post = array(
        'post_title'    => $payment_title,
        'post_status'   => 'pending',
        'post_date'     => $this->purchase_data['date'],
        'post_type'     => 'package-payment',
        'post_content'  => '',
        'meta_input'    => array(
            '_al_payment_data' => stripslashes_deep( $this->purchase_data ),
            '_al_payment_package_status' => 'pending',
            '_al_payment_user_id' => $this->purchase_data['user']['id'],
        ),
    );

    $payment_id = wp_insert_post( $payment_post );

    if ( ! empty( $payment_id ) ) {
        $this->purchase_data['payment_id'] = $payment_id;
    }

    // Return false if no payment was inserted
    return false;
}

/**
 * Add a note to a payment
 *
 * @param int $payment_id The payment ID to store a note for
 * @param string $note The note to store
 * @return int The new note ID
 */
public function insert_payment_note( $payment_id = 0, $note = '' ) {
    if ( empty( $payment_id ) )
        return false;

    $existing_data = get_post_meta( $payment_id, '_al_payment_data', true );

    do_action( 'auto_listings_pre_insert_payment_note', $payment_id, $note );

    $commentdata = array(
        'comment_post_ID' => $payment_id, // to which post the comment will show up
        'comment_author' => '', //fixed value - can be dynamic
        'comment_author_email' => $existing_data['user']['email'], //fixed value - can be dynamic
        'comment_author_url' => '', //fixed value - can be dynamic
        'comment_content' => $note['heading'] . ' - ' . $note['content'], //fixed value - can be dynamic
        'comment_type' => '', //empty for regular comments, 'pingback' for pingbacks, 'trackback' for trackbacks
        'comment_parent' => 0, //0 if it's not a reply to another comment; if it's a reply, mention the parent comment ID here
        'user_id' => get_current_user_id() ? get_current_user_id() : 1, //passing current user ID or any predefined as per the demand
    );

    //Insert new comment and get the comment ID
    $note_id = wp_new_comment( $commentdata );

    return $note_id;
}

/**
 * Updates a payment status.
 *
 * @param  int    $payment_id Payment ID
 * @param  string $new_status New Payment Status (default: publish)
 * @return bool               If the payment was successfully updated
 */
public function update_payment_status( $payment_id = 0, $new_status = 'publish' ) {

    if ( empty( $payment_id ) ) {
        return false;
    }

    if ( empty( $data ) ) {
        return false;
    }

    //Trying to verify payment
    //$payment = $mollie->payments->get($payment->id);
    $payment = $mollie->payments->get($_POST["id"]);
$orderId = $payment->metadata->order_id;

    if ($payment->isPaid())
    {
        echo "Payment received.";
    }

    $post_arr = array(
      'ID'          => $payment_id,
        'post_status'   => $new_status,
    );

    $updated = wp_update_post( $post_arr );

    return $updated;
}

/**
 * What to do when a payment completes successfully
 *
 * @param  array    $data payment success data, sent from gateway
 * @return bool     If the payment was successfully updated
 */

public function payment_successful( $data ) {

    $start_time = current_time( 'timestamp', $gmt = 0 );
    $end_time   = null;
    if( $data['package_id']['duration'] > 0 ) {
        $end_time   = strtotime( '+' . $data['package_id']['duration'] . ' days', date( 'Y-m-d H:i:s', $start_time ) );
    }

    update_post_meta( $data['payment_id'], '_al_payment_package_time_start', $start_time );
    update_post_meta( $data['payment_id'], '_al_payment_package_time_end', $end_time );
    update_post_meta( $data['payment_id'], '_al_payment_package_status', 'active' );
    update_post_meta( $data['payment_id'], '_al_payment_package_listings', $data['package_id']['listings'] );
    update_post_meta( $data['payment_id'], '_al_payment_package_listings_used', '0' );
}

}


Solution

  • Solved. I used the Mollie Webhook to check the status of the payment: https://github.com/mollie/mollie-api-php/blob/master/examples/payments/webhook.php.