Git Product home page Git Product logo

paypal-recurring2's Introduction

paypal-recurring

This package makes integration of PayPal's recurring payments easier in your next project using node.js.

This package is a fork of paypal-recurring

Installation

npm install paypal-recurring2

Introduction

Integrating PayPal's recurring payments into your application to get paid can be confusing, but it only takes two steps to convert a user into a paying recurring customer of yours.

Enter your own API credentials in the demo application (./examples/express) and run it by entering this in your terminal:

make demo

Obtaining API credentials

To obtain your credentials for production first login with your Paypal account then go to this page. Credentials for testing are in in this seemingly unrelated page.

If you want to read up on PayPal's API documentation for recurring billing, visit this page.

Introduction & converting users into customers

Your user visits your node.js-driven website where you already have setup your environment by installing this package and passed your API credentials to the constructor of the class.

By calling the authenticate() method, you'll get an unique URL from PayPal that you redirect your user to. Now at PayPal's website, your user either logs in to an existing account or creates a new one and then gets to accept your recurring payment agreement.

PayPal then sends the user back to your website along with a unique token + customer id appended to the url as query strings. With this token and the payerid, you run the createSubscription-method and your user is now turned into a paying subscriber of yours.

You can then use the PROFILEID that createSubscription returns on success to either fetch subscription information and remotely pause/cancel subscriptions from within your app in the future by using the .getSubscription() & .modifySubscription() -methods.

Documentation

Constructor

The constructor takes two arguments: credentials & enviroment. Username, password and signature for the credentials are all your PayPal API credentials

The default environment uses the PayPal Sandbox API to allow testing. When going live, pass true as a second parameter to the constructor (previously you should have passed "production", but this isn't valid anymore, please pass true). This will create real subscriptions, so use with care.

// Require the module and setup our instance of the class
var Paypal = require('paypal-recurring2'),
    paypal = new Paypal({
      username:  "[email protected]",
      password:  "****",
      signature: "****",
    }
    //, true // USE WITH CARE!
    );

.authenticate(options, callback)

(first step in the payment flow)

This method generates a unique url to authenticate the user through PayPal by calling the SetExpressCheckout action in the PayPal API.
You should redirect your user to the url that this method returns to allow the user to either login to an existing account or create a new one with PayPal.

This method takes two arguments - options (object) and callback (fn).

The options object must contain at least RETURNURL, CANCELURL, PAYMENTREQUEST_0_AMT & L_BILLINGAGREEMENTDESCRIPTION0 for this API operation to be valid.

Your callback will be passed three arguments upon API response; error, data & url.

Example usage of .authenticate():

// Authenticate a future subscription of ~10 USD
paypal.authenticate({
  RETURNURL:                      "https://localhost/purchase/success",
  CANCELURL:                      "https://localhost/purchase/fail",
  PAYMENTREQUEST_0_AMT:           10,
  L_BILLINGAGREEMENTDESCRIPTION0: "A description of this subscription"
}, function(err, data, url) {
  // Redirect the user if everything went well with
  // a HTTP 302 according to PayPal's guidelines
  if (!err) { res.redirect(302, url); }
});

This is what the actual API request will look like when calling authenticate as above:

USER:                           "***",
PWD:                            "***",
SIGNATURE:                      "***",
VERSION:                        94,
METHOD:                         "SetExpressCheckout",
ADDROVERRIDE:                   0,
ALLOWNOTE:                      0,
BUYEREMAILOPTINENABLE:          1,
NOSHIPPING:                     1,
SURVEYENABLE:                   0,
RETURNURL:                      "https://localhost/purchase/success",
CANCELURL:                      "https://localhost/purchase/fail",
PAYMENTREQUEST_0_AMT:           10,
L_BILLINGAGREEMENTDESCRIPTION0: "A description of this subscription",
L_BILLINGTYPE0:                 "RecurringPayments"

Note: Some of the parameters above are not explicitly specified in the arguments and are set as default inside the SetExpressCheckout method to suit most online subscription businesses. Override any of the defaults by including that key/value in the options hash.

Please visit this page for official PayPal API documentation of the SetExpressCheckout action to learn how you can customize the API call to suit your business.

.createSubscription(token, payerid, options, callback)

(final step in the payment flow)

After calling .authenticate() the user is now back on your server at the RETURNURL you specified with both token and payerid appended to the URL as querystrings.

You now call the .createSubscription()-method, passing both the token and the payerid to setup the actual recurring billing profile between you and the customer, which runs the CreateRecurringPaymentsProfile on the PayPal API.

This method takes four arguments: token (string), payerid (string), options (object) & callback (fn)

The options object must contain at least AMT, DESC, BILLINGPERIOD & BILLINGFREQUENCY for this API operation to be valid.

The start date of the payment profile is automatically set and converted into ISO/UTC format & timezone before being sent to the PayPal API. If you like to change the first billing date of your customer, just pass along a date object in the options object like PROFILESTARTDATE: new Date() and you should be fine.

Your callback function will be passed two arguments upon API response; error & data.

Example usage of .createSubscription():

// Create a subscription of 10 USD every month
paypal.createSubscription('token','payerid',{
  AMT:              10,
  DESC:             "A description of this subscription",
  BILLINGPERIOD:    "Month",
  BILLINGFREQUENCY: 1,
}, function(err, data) {
  if (!err) {
    res.send("You are now one of our customers!");
    console.log("New customer with PROFILEID: " + data.PROFILEID)
  }
});

**This is what the actual API request will look when calling .createSubscription() as above: **

USER:             "***",
PWD:              "***",
SIGNATURE:        "***",
VERSION:          94,
METHOD:           "CreateRecurringPaymentsProfile",
TOKEN:            "***",
PAYERID:          "***",
INITAMT:          0,
PROFILESTARTDATE: "2013-02-11T18:25:25.000Z",
AMT:              10,
DESC:             "A description of this purchase",
BILLINGPERIOD:    "Month",
BILLINGFREQUENCY: 1

Please visit this page for official PayPal API documentation of the CreateRecurringPaymentsProfile action to learn how you can customize the API call to suit your business.

.getSubscription(profileid, callback)

To fetch information about a payment profile of one of your customers, call the .getSubscription method with the PROFILEID that was returned when you invoked .createSubscription.

This method takes two arguments: profileid (string) & callback (fn).

Your callback function will be passed two arguments upon API response; error & data.

paypal.getSubscription('subscriptionid', function(err, data) {
  if (!err) { console.log(data)}
});

Please visit this page for official PayPal API documentation of the GetRecurringPaymentsProfileDetails action.

.modifySubscription(profileid, action, callback)

To remotely modify subscriptions - cancel, suspend and reactivate subscriptions you can use the .modifySubscription-method.

It takes four arguments: profileid (string), action (string), note (string) & callback (fn).

Action may be either cancel, suspend or reactivate.
The note argument is optional and can be left out if you doesn't need to send an note along with the payment profile status change to your customer.

Your callback function will be passed two arguments upon API response; error & data.

paypal.modifySubscription('subscriptionid', 'Cancel' , function(err, data) {
  if (!err) { res.send "Your subscription was cancelled" }
});

Please visit this page for official PayPal API documentation of the ManageRecurringPaymentsProfileStatus action.

Pitfalls

Different subtotals/descriptions

If your description and/or subtotal differs between what you enter when calling authenticate & createSubscription, PayPal may deny your API call.

Trial periods

If you want to provide a proper free trial period before any billing is done, avoid using any of the billing fields (TRIALBILLINGPERIOD etc) when calling the createSubscription method.

Instead, make sure to set the PROFILESTARTDATE ahead in time according to when you want the first billing to occur:

var d = new Date()
d.setMonth(d.getMonth()+1)

Development

Feel free to go wild if you are missing any features in this package. Just make sure to write proper tests and that they pass:

make test

Changelog

v1.1.0:

  • The class does now validates API results to keep you from writing if (response["ACK"] === "Success") to manually validate every API action.
  • Every API action is now tunneled through the makeAPIrequest()-method to make it easy to debug/unit test the class when integrating with your own code.

License

MIT license. See the LICENSE file for details.
Copyright (c) 2013 Jay Bryant. All rights reserved.

paypal-recurring2's People

Contributors

fiatjaf avatar jaybryant avatar

Stargazers

 avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

paypal-recurring2's Issues

Missing Token

Im getting the error "Missing token" when I call the authenticate function for the first time

getSubscription failing with error 500

In fact, getSubscription doesn't return anything and the callback is never called, but doing the call directly through makeAPIrequest gives me this:

coffee> params
{ USER: 'myuser',
  PWD: 'mypassword',
  SIGNATURE: 'mysignature',
  VERSION: 94,
  METHOD: 'GetRecurringPaymentsProfileDetails',
  PROFILEID: 'avalidprofileid' }
coffee> paypal.makeAPIrequest(params, console.log.bind console)
coffee> 
coffee> # here more than a minute passes while I wait for the response
coffee> 
coffee> { '<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">\n<html><head>\n<title>500 Internal Server Error</title>\n</head><body>\n<h1>Internal Server Error</h1>\n<p>The server encountered an internal error or\nmisconfiguration and was unable to complete\nyour request.</p>\n<p>Please contact the server administrator,\n [email protected] and inform them of the time the error occurred,\nand anything you might have done that may have\ncaused the error.</p>\n<p>More information about this error may be available\nin the server error log.</p>\n<hr>\n<address>Apache Server at <a href': '"mailto:[email protected]">api-3t.sandbox.paypal.com</a> Port 443</address>\n</body></html>\n' } null

The error string in a readable format:

\n\n<title>500 Internal Server Error</title>\n\n

Internal Server Error

\n

The server encountered an internal error or\nmisconfiguration and was unable to complete\nyour request.

\n

Please contact the server administrator,\n [email protected] and inform them of the time the error occurred,\nand anything you might have done that may have\ncaused the error.

\n

More information about this error may be available\nin the server error log.

\n
\nApache Server at api-3t.sandbox.paypal.com Port 443\n\n

This API endpoint does not work anymore? What is happening? According to https://developer.paypal.com/docs/classic/api/merchant/GetRecurringPaymentsProfileDetails_API_Operation_NVP/ everything should be ok.

Missing token / Security header is not valid

When making the call to paypal.authenticate I get this response:

{ TIMESTAMP: '2015-06-24T16:41:57Z',
  CORRELATIONID: '3638a82437065',
  ACK: 'Failure',
  VERSION: '94',
  BUILD: '17159089',
  L_ERRORCODE0: '10002',
  L_SHORTMESSAGE0: 'Security error',
  L_LONGMESSAGE0: 'Security header is not valid',
  L_SEVERITYCODE0: 'Error' }

Which is translated into a "Missing token" error.

Why is my security header not valid? How can I fix it?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.