Use PayPal for pay-per-post on WordPress.

Note: This article has been marked for a quality review and will soon be updated.

As you may know I like WordPress – it’s a great platform for building websites on. As you may not know is, I like PayPal – it’s an easy to way to safely make quick payments online. Now you may be asking what the hell I’m on about, have I been paid by WP and PayPal to go on about their services? Nope. Today I want to share with you an easy way to integrate these two fantastic services, to allow users of your site to pay each time they want to post on your site. For this we will be using the PayPal API, and a rather special page indeed which will allow your users to post from outside of the admin panel. If you didn’t know, there is already a tutorial on doing so entitled – Publishing to WordPress from outside the admin panel, so go ahead and check that out, and then come back over here.

So first let’s think about the theory behind this. We want users to go to our post-page, and then be asked to buy a token to post 1 article; we then want to send the user to PayPal, for them to pay us, and then be sent back to our site, where the same post-page now shows them everything they need to post an article. Sound good? Almost there, we need to make sure we prepare for something – say for instance the user has user paid, and there is a power-cut at their house, in that case they will have just lost the money they paid us, and will be rather angry that there is no way to get it back; so essentially we are covering for the user closing their browser without posting, having paid us. And for that we are going to enlist the help of the cookie monster! Nah, just kidding, we’ll stick to just one cookie for now – which will be placed on the user’s machine to tell our site that they have paid, and when they have posted we can alter the cookie to reflect that. So let’s go ahead and start with our posting page, place this code above your form.

<?php
if($_POST['payment_status']=="Completed"){
  $paid = true;
}else if($_COOKIE['activeToken']=="true") {
  $paid = true;
}else {
  $paid = false;
}

if(!$paid){ ?>

// User hasn't paid

<?php }else {  ?>

So what do we have here? Well at the top we can see we are checking to see if a posted variable is equal to “Completed” – this is something that PayPal gives us when the user has completed their transaction. We then set the $paid variable equal to true. Next we check a cookie to see if it’s value is “true”, and once again if this is true, we set $paid equal to true. And finally if neither of the above conditions validates we simply set the variable equal to false. Next we have an if statement which runs if $paid is equal to false – using the handy ! just before the variable. Now, after the else { statement is where you will want to put your form for posting an article, but not before you enter our crazy AJAX/Cookie-goodness code which follows.

<script type="text/javascript">
  $(document).ready(function(){
    var dataString = "cval=true";
    $.ajax({
      type: "POST",
      url: "<?php bloginfo('template_url') ?>/scripts/cookie.php",
      data: dataString,
    });
  });
</script>

// Your HTML goes here

<?php } ?>

Woah what the frick is that?! I hear you shouting. Right well let’s go from the top. First off we can see that we are using JavaScript, and also jQuery – so make sure it’s included, and we are also waiting for the DOM to have fully loaded everything before beginning our code. Then inside of this code we are setting up a variable named dataString and setting it’s value to “cval=true” – more on this soon. Then we create an AJAX call using jQuery which will POST to a URL which is in our theme folder in the scripts sub-folder, to a file named “cookie.php” the data in the variable dataString. Make sense? Hopefully it does. Now you might be thinking, but wait a moment, I don’t have a file called cookie.php, and even more annoying is that I don’t even have a folder called scripts in my theme directory. Well don’t worry – go ahead and create a new file called cookie.php in your theme directory, and if you tend to store scripts in another directory like me, go ahead and move it into that directory – just be sure to update the URL there – and if you didn’t know that handy bit of code that reads <?php bloginfo('template_url') ?> just spits out the URL of your theme’s directory. Now, copy and paste the following code into your new file.

<?php
$expire = 60 * 60 * 24 * 60 + time();
setcookie('activeToken', $_POST['cval'], $expire,'/');
?>

So what does that code do? Well the first line sets up a variable named $expire which holds the value of the date two months from today using some basic maths. Then we use the PHP function setcookie() to create a cookie in the format setcookie(name,value>,expiry date,directory) – now you might be wondering what that final “directory” bit is about – put simply that is the location where your cookie can be read from – if you leave out this parameter you won’t be able to access your cookie, except from the cookie.php page you created it on – not ideal.

Now we have a good thing going now, but we need to think about when the user has submitted the form, and posted an article – we need to alter the cookie to tell our site that the user has used up the token he bought – simply by using the same JavaScript code that we used above, but changing “cval=true” to “cval=false”. Now if you submit your main form using AJAX you can simply add this function in the success: parameter, otherwise you might want to do any number of other things – using jQuery’s submit() function like so.

$("#myform").submit(function(){
  var dataString = "cval=false";
  $.ajax({
    type: "POST",
    url: "<?php bloginfo('template_url') ?>/scripts/cookie.php",
    data: dataString,
  });
});

Or you could stick the code on the page to which new post data is posted (new-post.php). Either way, you just have to ensure, that when the submit button is clicked – the cookie is set to false.

Now we’ve done nearly everything without having touched PayPal – the subject of the next section of the article; but before we begin I want to eradicate any preconceptions you may have about working with PayPal. Many people think it will be rather difficult to use PayPal in the way I am going to describe – that because you are dealing with people’s money there is a greater margin for error. But this isn’t the case – because at the end of the day, PayPal is the one going all the ground-work, and if it doesn’t like what you are doing – it’s going to tell you, so don’t worry – and just go crazy! So go ahead and replace that comment we created earlier “//User hasn’t paid” with the following code – kindly provided by PayPal.

<form action="https://www.paypal.com/cgi-bin/webscr?return=<?php the_permalink(); ?>&cpp_header_image=http://example.com/myHeaderImage.jpg&cbt=Return and post an article&rm=2" method="post">
<!-- Identify your business so that you can collect the payments. -->
<input type="hidden" name="business" value="name@example.com">
<!-- Specify a Buy Now button. -->
<input type="hidden" name="cmd" value="_xclick">
<!-- Specify details about the item that buyers will purchase. -->
<input type="hidden" name="item_name" value="Job Post Token">
<input type="hidden" name="amount" value="1000"> <input type="hidden" name="currency_code" value="USD">
<!-- Display the payment button. -->
<button value="Buy Posting Token"><span>Buy Posting Token</span></button>
<img alt="" border="0" width="1" height="1" src="https://www.paypal.com/en_US/i/scr/pixel.gif" >
</form>

So above, we have a form with a heck of a lot of information in it, but if we break it down, it’s actually rather simple. Firstly we set up the form and tell it to post to PayPal’s website – we also specify a number of variables to post along with it – the values of which are highlighted in bold. Firstly we have return – where the user will be returned to, once payment has been completed, for this we use the page’s URL, helpfully provided to us by WordPress. Then we send it something called cpp_header_image – a 90x750px image which will be used in the header – using an image of your own will make the user feel more comfortable, and looks more professional. Then a variable called – cbt – which is the text used on the button which will send users back to the return URL specified above. The last variable is to do with PayPal posting values back to our page – including that of the handy payment_status – so don’t change that.

The next value highlighted in bold is an email address – this is where you should enter the email address of the PayPal account holder to which all transactions will be credited. Next is the value “1000” – which is the amount you wish to charge your users to post – in this case $1000 – may be a little pricy – you decide. The currency is also set below and is currently set to US Dollars. PayPal provides a full list of variables for you to use, which is worth checking out for further customisation.

And that, ladies and gentlemen, is that! So now hopefully you can see just how easy it is to integrate PayPal with WordPress. As always if you have any questions/problems with the tutorial, leave a comment and let me know what you think.

Edit
For those of you who wish to make visitors to your site pay per viewing of each post you would need the following code structure alongside the code above.

<?php
if($_POST['payment_status']=="Completed"){
  $paid = true;
}else if($_COOKIE['activeToken']=="true") {
  $paid = true;
}else {
  $paid = false;
}

if($paid){ ?>

// User had paid, therefore enter the WordPress loop for the post

if(have_posts()) : while(have_posts()) : the_post();

//etc

<?php }else { ?>

//User hasn't paid, so display the payment options

<?php } ?>

Check out the codex for more information on the loop.


Posted

in

by

Comments

24 responses to “Use PayPal for pay-per-post on WordPress.”

  1. Philip avatar
    Philip

    thanks a lot Tom,
    this is a great article, i’l take a deep look…
    what about security?

    thanks a lot,
    Philip

    1. Tom avatar

      Hi Philip, PayPal handles all the security in terms of the financial transaction, and the cookie ensures the user won’t loose what they have paid for. I hope that answers your question.

  2. Philip avatar
    Philip

    Hi Tom,
    I try to build a page to do something similar,
    i use wp_insert_post and insert_attachment functions,
    everything is working fine i have build a paypal form but i can’t understand how to handle the cookie.php

    i use the cval=true part of your example before the paypal form
    and the cval=false part after the and before the post form.

    i’m correct?

    thanks a lot,
    very helpful tutorial,
    Philip

    1. Tom avatar

      cookie.php sets up a cookie on the client’s machine, this simply ensures they don’t loose their post when they close their browser. You could disable this functionality, but you would have to warn your users that closing their window would cancel not give them a refund.

  3. Philip avatar
    Philip

    Thanks for your reply Tom,
    i have understand what the cookie does but i can’t understand where to put the javascript parts of your code,

    in my custom write page i use it like this:

    From the top of the page template
    1. wp_insert_post code
    2. if payment complete or no
    3. javascript with cval=true
    4. paypal form
    5. else
    6. javascript with cval=false
    7. post form

    1. Tom avatar

      The position of the script is unimportant as it only executes when the page is fully loaded because of the $(document).ready() function, so I’d suggest popping in the head of your page.

  4. Ahmad avatar
    Ahmad

    is this only for users?
    i want it for visitors does it work?

    1. Tom avatar

      Hi Ahmad, for visitors you would have to set up a session variable and only display the post if the variable contained the correct value, so you would display the link to PayPal and upon redirection to your post page you would display it using an if…else statement. Hope that answers your question.

      1. Emmanuel K avatar
        Emmanuel K

        Hi Tom,

        Greate article! Could you please give an example of how can I do that?

        Cheers
        Emmanuel

        1. Tom avatar

          Hey man, what kind of example were you after, an example?

          1. Emmanuel K avatar
            Emmanuel K

            you stated to one of the comments above for allowing visitors to pay per post: “for visitors you would have to set up a session variable and only display the post if the variable contained the correct value, so you would display the link to PayPal and upon redirection to your post page you would display it using an if…else statement…”

            an example would be really appriciated, I’m still on the process of learning PHP while developing at the same time :-S

            Cheers,
            Emmanuel

          2. Tom avatar

            I’ve updated the post Emmanuel, let me know if that helps.

          3. Emmanuel K avatar
            Emmanuel K

            Tom you’re a legend, thanks a mill! seriously, you just made my day!

            Cheers,
            Emmanuel

          4. Tom avatar

            Glad I could help!

  5. Sam C avatar
    Sam C

    Hi, excellent tutorial. It’s great to follow.
    I have a question however: Would it be able to change the price/cost per post, to a dynamic variable that takes its value from the word count of the post. So that the User submitting the post pays ‘per word’ as opposed to ‘per post’. E.G, 10 words = 10 Cents

    I’d really appreciate some help with this. I’m new to coding, if someone could give me an idea how to do this, or even show me i’d really appreciate it. Thanks guys!

    Sam

    1. Tom avatar

      Hi Sam, you would simply use the handy PHP function str_word_count() on the post’s content and set up a variable to pass to PayPal.

      So you would change this line ‘<input type=”hidden” name=”amount” value=”1000″>’ to something like:

      ‘<input type=”hidden” name=”amount” value=”<?php echo (str_word_count($content) / 10) * 0.1; ?>”>’ – for 10 cents per 10 words.

  6. Sam C avatar
    Sam C

    Hi Tom,
    Thanks for the quick reply.
    Unfortunately, as I was trying to install this script into my php file I constantly got the ‘syntax error’ message. It directed me to the end line of my file and i couldn’t figure out the problem.

    I’ve yet to try the php script in your reply, as I’m not able to get the main bit from your article correct.

    I know these are vague problems but if you could get back to me i’d gladly and quickly provide details to questions and send you my php file if neccessary.

    Thanks loads! I really need this script to work 🙂 There isn’t much else out there like it.

    Thanks again, Sam.

    1. Tom avatar

      What’s the last line of your file?

  7. Sam C avatar
    Sam C

    I’ve tried both the above and it results in the error, but so does ?>
    Is the script supposed to replace the submission form with the paybutton? and the reveal it upon payment/credits?

    1. Tom avatar

      Hmm I’ll send you an email so we can get this fixed!

  8. Aaron avatar

    Hi Tom,
    Just looking through the code and both times you reference “” Should the opening <php tag not have a question mark in it? May be this is why its not working for me. Cheers.

    1. Tom avatar

      Oops! Yep you do indeed need the question mark! Updated, thanks!

  9. Jordan Coeyman avatar

    Would this method be usable with a different payment system (Amazon EasyPay for example)?

    1. Tom avatar

      The basic concept behind it certainly applies across the board no matter what payment processor you are using, however you’d have to check out the appropriate API for specific changes.