Free Premium Themes & Plugins for those who Can't Afford High Prices!!!
- 100%

AffiliateWP REST API Extended

  • Quality checked by our Team
  • Auto Update: Yes
  • Unlimited Domain Usage
  • Lifetime Free Updates
  • Version: 1.2.1
  • Last Update: Nov 17, 2023

Original price was: $149.00.Current price is: $0.00.

Added to wishlistRemoved from wishlist 0
Add to compare

REST API Extended Installation and Usage

How to Install and Use the REST API Extended Add-on for AffiliateWP

The REST API Extended add-on adds Create, Update, and Delete operations, giving developers and external applications complete control over data in the AffiliateWP databases.

In this article, we’ll show you how to install and set up the REST API Extended add-on for AffiliateWP.

  1. Installing the REST API Extended Add-on
  2. Managing Affiliates
  3. Managing Creatives
  4. Managing Payouts
  5. Managing Referrals
  6. Managing Visits
  7. Example: WP-to-WP

1. Installing the REST API Extended Add-on

Once you’ve got AffiliateWP installed and your license is verified, you’ll be able to quickly install and activate the Affiliate Landing Pages add-on.

After installing the REST API Extended add-on, the next step is to configure the REST API Extended settings. To do this, navigate to AffiliateWP » Settings » REST API and select the checkboxes for the types of endpoints you’d like to enable.

Your site now has a complete CRUD REST API for interacting with your affiliate data.

If you have not yet used the read-only REST API provided by the core AffiliateWP plugin, or you are unsure of how to authenticate with the REST API, please review the  overview documentation for the base API.

2. Managing Affiliates

REST API Extended adds three endpoints, one each for creatingediting, and deleting affiliates on top of the two read-only endpoints already available in AffiliateWP core.

All five endpoints leverage the same two route patterns:

  1. affiliates – When sent a GET request, a list of affiliates are returned and can be filtered with additional arguments. When sent a POST or PUT request, a new affiliate can be created.
  2. affiliates/[ID] – When sent a GETPATCH, or DELETE request, a single affiliate can be retrieved, edited, or deleted, respectively.

Both routes can also accept generic OPTIONS requests, which can be very helpful for discovering information about available endpoints, accepted request types and arguments, and item schema.

Whether you’re planning to read, write, edit, or delete affiliates, this add-on makes it possible.

All requests must be authenticated using API keys, which are generated and managed via the AffiliateWP → Tools → API Keys tab. Check out the REST API – Authentication article for more information.


Creating an Affiliate

Affiliates can be created by sending a POST or PUT request to the affiliates route:

https://example.com/wp-json/affwp/v1/affiliates

The create endpoint accepts any of the following affwp_add_affiliate() arguments:

  • user_id – (integer) Every affiliate shares a 1:1 relationship with an existing WordPress user account. If no suitable user ID is available, the create_user argument can be passed to try creating an affiliate and a user account in the same step.
  • username – (string) Optional. Used to set the user_login when creating a new user account. If not provided, the payment_email will be used to generate the user_login of the generated WordPress user.
  • create_user – (boolean)  Used to create a new user account, in lieu of user_id. Must be accompanied by a unique payment_email value, which is used when registering the user account.
  • rate – (integer) Affiliate rate to use. If not specified, the global default will be used.
  • rate_type – (string) Rate type. Default accepted types are’percentage’ or ‘flat’. If not specified, the global default will be used.
  • payment_email – (string) Affiliate payment email. If omitted, the user account email will be used on retrieval. Required when using create_user.
  • status – (string) Affiliate status. Accepts ‘active’, ‘inactive’, ‘pending’, or ‘rejected’. Default is ‘pending’.
  • notes – (string) Affiliate notes.

Creating an affiliate with user_id:

Method: PUT/POST
Endpoint: https://example.com/wp-json/affwp/v1/affiliates/?user_id=5&rate=25&rate_type=percentage

The new affiliate would be associated with user_id 5 and given a commission rate of 25 percent.

Example response:

{
  "affiliate_id": 30,
  "user_id": 5,
  "rate": "25",
  "rate_type": "percentage",
  "payment_email": "",
  "status": "pending",
  "earnings": 0,
  "unpaid_earnings": 0,
  "referrals": 0,
  "visits": 0,
  "date_registered": "2017-01-26 07:27:52",
  "id": 30
}

Creating an affiliate and a user with create_user:

Method: PUT/POST
Endpoint: https://example.com/wp-json/affwp/v1/affiliates/?create_user=1&[email protected]

The new affiliate would be associated with the new user (ID 10) and given a payment email of [email protected].

Example response:

{
  "affiliate_id": 31,
  "user_id": 10,
  "rate": "",
  "rate_type": "",
  "payment_email": "[email protected]",
  "status": "pending",
  "earnings": 0,
  "unpaid_earnings": 0,
  "referrals": 0,
  "visits": 0,
  "date_registered": "2017-01-26 07:27:52",
  "id": 31
}

Editing an Existing Affiliate

Single affiliates can be updated by sending a POST or PATCH request to the affiliates/[id] route:

https://example.com/wp-json/affwp/v1/affiliates/[id]

The edit endpoint accepts any of the following affwp_update_affiliate() arguments:

  • account_email – (string) New account email for the associated user account.
  • payment_email – (string) New payment email.
  • rate – (integer) Affiliate rate to use
  • rate_type – (string) Rate type.
  • status – (string) Affiliate status. Accepts ‘active’, ‘inactive’, ‘pending’, or ‘rejected’.
  • notes – (string) Affiliate notes.

Updating an Affiliate

In this example, we’ll update an affiliate’s status from pending to active.

Method: POST/PATCH
Endpoint: https://example.com/wp-json/affwp/v1/affiliates/31?status=active

Response:

{
  "affiliate_id": 31,
  "user_id": 10,
  "rate": "",
  "rate_type": "",
  "payment_email": "[email protected]",
  "status": "active",
  "earnings": 0,
  "unpaid_earnings": 0,
  "referrals": 0,
  "visits": 0,
  "date_registered": "2017-01-26 07:27:52",
  "id": 31
}

Deleting an Affiliate

An affiliate can be deleted by sending a DELETE request to the affiliates/[id] route:

https://example.com/wp-json/affwp/v1/affiliates/[id]

The delete endpoint accepts no additional arguments. When an affiliate as been successfully deleted, a key/value pair of deleted: true will be included in the response, along with a copy of the old affiliate response.

Example request:

Method: DELETE
Endpoint: https://example.com/wp-json/affwp/v1/affiliates/31

Response:

{
  "deleted": true,
  "previous": {
    "affiliate_id": 31,
    "user_id": 10,
    "rate": "",
    "rate_type": "",
    "payment_email": "[email protected]",
    "status": "active",
    "earnings": 0,
    "unpaid_earnings": 0,
    "referrals": 0,
    "visits": 0,
    "date_registered": "2017-01-26 07:27:52",
    "id": 31
  }
}

3. Managing Creatives

REST API Extended adds three endpoints, one each for creatingediting, and deleting creatives on top of the two read-only endpoints already available in AffiliateWP core.

All five endpoints leverage the same two route patterns:

  1. creatives – When sent a GET request, a list of creatives are returned and can be filtered with additional arguments. When sent a POST or PUT request, a new creative can be created.
  2. creatives/[id] – When sent a GETPATCH, or DELETE request, a single creative can be retrieved, edited, or deleted, respectively.

Both routes can also accept generic OPTIONS requests, which can be very helpful for discovering information about available endpoints, accepted request types and arguments, and item schema.

Whether you’re planning to read, write, edit, or delete creatives, this add-on makes it possible.

All requests must be authenticated using API keys, which are generated and managed via the AffiliateWP → Tools → API Keys tab. Check out the REST API – Authentication article for more information.


Creating a Creative

Creatives can be created by sending a POST or PUT request to the creatives route:

https://example.com/wp-json/affwp/v1/creatives

The create endpoint accepts any of the following affwp_add_creative() arguments:

  • name – (integer) Name label for the creative.
  • description – (string) Description of the creative.
  • url – (string) URL to point the creative to.
  • text – (string) Text to display with the creative.
  • image – (string) Image URL to associate with the creative.
  • status – (string) Creative status. Accepts ‘active’ or ‘inactive’. Default ‘active’.

Creating a creative:

Method: PUT/POST
Endpoint: https://example.com/wp-json/affwp/v1/creatives/?name=New+Creative&text=REST

The new creative, named “New Creative” would contain text “REST”.

Example response:

{
  "creative_id": 20,
  "name": "New Creative",
  "description": "",
  "url": "",
  "text": "REST",
  "image": "",
  "status": "",
  "date": "2017-01-26 09:25:05",
  "id": 20
}

Editing an Existing Creative

Single creatives can be updated by sending a POST or PATCH request to the creatives/[id] route:

https://example.com/wp-json/affwp/v1/creatives/[id]

The edit endpoint accepts any of the following affwp_update_creative() arguments:

  • name – (integer) Name label for the creative.
  • description – (string) Description of the creative.
  • url – (string) URL to point the creative to.
  • text – (string) Text to display with the creative.
  • image – (string) Image URL to associate with the creative.
  • status – (string) Creative status. Accepts ‘active’ or ‘inactive’.

Updating a Creative

In this example, we’ll update a creative’s status from active to inactive.

Method: POST/PATCH
Endpoint: https://example.com/wp-json/affwp/v1/creatives/20?status=inactive

Response:

{
  "creative_id": 20,
  "name": "Creative",
  "description": "",
  "url": "http://affiliate.dev",
  "text": "AffiliateWP Plugin Testing",
  "image": "",
  "status": "inactive",
  "date": "2017-01-26 09:25:05",
  "id": 20
}

Deleting a Creative

A can be deleted by sending a DELETE request to the creatives/[id] route:

https://example.com/wp-json/affwp/v1/creatives/[id]

The delete endpoint accepts no additional arguments. When a creative as been successfully deleted, a key/value pair of deleted: true will be included in the response, along with a copy of the old creative response.

Example request:

Method: DELETE
Endpoint: https://example.com/wp-json/affwp/v1/creatives/20

Response:

{
  "deleted": true,
  "previous": {
    "creative_id": 20,
    "name": "Creative",
    "description": "",
    "url": "http://affiliate.dev",
    "text": "AffiliateWP Plugin Testing",
    "image": "",
    "status": "inactive",
    "date": "2017-01-26 09:25:05",
    "id": 20
  }
}

3. Managing Payouts

REST API Extended adds three endpoints, one each for creatingediting, and deletingpayouts on top of the two read-only endpoints already available in AffiliateWP core.

All five endpoints leverage the same two route patterns:

  1. payouts – When sent a GET request, a list of payouts are returned and can be filtered with additional arguments. When sent a POST or PUT request, a new payout can be created.
  2. payouts/[id] – When sent a GETPATCH, or DELETE request, a single payout can be retrieved, edited, or deleted, respectively.

Both routes can also accept generic OPTIONS requests, which can be very helpful for discovering information about available endpoints, accepted request types and arguments, and item schema.

All requests must be authenticated using API keys, which are generated and managed via the AffiliateWP → Tools → API Keys tab. Check out the REST API – Authentication article for more information.


Creating a Payout

Payouts can be created by sending a POST or PUT request to the payouts route:

https://example.com/wp-json/affwp/v1/payouts

The create endpoint accepts any of the following affwp_add_payout() arguments:

  • affiliate_id – (integer) ID of the affiliate to associate the payout with. This field is required.
  • referrals – (array|string) Array or comma-separated list of referral IDs to include in the payout.
  • amount – (float) Payout amount (typically derived from referral amounts).
  • payout_method – (string) Payout method.
  • status – (string) Accepts ‘paid’ or ‘failed’. Default ‘paid’.

Creating a payout:

Method: PUT/POST
Endpoint: https://example.com/wp-json/affwp/v1/payouts/?affilite_id=30&referrals=10,15,20

The new payout, with payout_id 15 would cover referrals 10, 15, and 20 for affiliate_id 30.

Example response:

{
  "payout_id": 15,
  "affiliate_id": 30,
  "referrals": "10,15,20",
  "amount": 27.87,
  "payout_method": "manual",
  "status": "paid",
  "date": "2017-01-26 12:55:13",
  "owner": 1,
  "id": 15
}

Editing an Existing Payout

Single payouts can be updated by sending a POST or PATCH request to the payouts/[id] route:

https://example.com/wp-json/affwp/v1/payouts/[id]

The edit endpoint accepts any of the following arguments:

  • affiliate_id – (integer) ID of the affiliate to associate the payout with. This field is required.
  • referrals – (array|string) Array or comma-separated list of referral IDs to include in the payout.
  • amount – (float) Payout amount (typically derived from referral amounts).
  • payout_method – (string) Payout method.
  • status – (string) Accepts ‘paid’ or ‘failed’. Default ‘paid’.

Updating a Payout

In this example, we’ll update a payout’s status from failed to paid.

Method: POST/PATCH
Endpoint: https://example.com/wp-json/affwp/v1/payouts/15?status=paid

Response:

{
  "payout_id": 15,
  "affiliate_id": 30,
  "referrals": "10,15,20",
  "amount": 30,
  "payout_method": "manual",
  "status": "paid",
  "date": "2017-01-26 12:55:13",
  "owner": 1,
  "id": 15
}

Deleting a Payout

A payout can be deleted by sending a DELETE request to the payouts/[id] route:

https://example.com/wp-json/affwp/v1/payouts/[id]

The delete endpoint accepts no additional arguments. When a payout as been successfully deleted, a key/value pair of deleted: true will be included in the response, along with a copy of the old payout response.

Example request:

Method: DELETE
Endpoint: https://example.com/wp-json/affwp/v1/payouts/15

Response:

{
  "deleted": true,
  "previous": {
    "payout_id": 6751,
    "affiliate_id": 5454,
    "referrals": "35878,35877,35876",
    "amount": 30,
    "payout_method": "manual",
    "status": "paid",
    "date": "2017-01-26 12:55:13",
    "owner": 1,
    "id": 6751
  }
}

5. Managing Referrals

REST API Extended adds three endpoints, one each for creatingediting, and deletingreferrals on top of the two read-only endpoints already available in AffiliateWP core.

All five endpoints leverage the same two route patterns:

  1. referrals – When sent a GET request, a list of referrals are returned and can be filtered with additional arguments. When sent a POST or PUT request, a new referral can be created.
  2. referrals/[id] – When sent a GETPATCH, or DELETE request, a single referral can be retrieved, edited, or deleted, respectively.

Both routes can also accept generic OPTIONS requests, which can be very helpful for discovering information about available endpoints, accepted request types and arguments, and item schema.

All requests must be authenticated using API keys, which are generated and managed via the AffiliateWP → Tools → API Keys tab. Check out the REST API – Authentication article for more information.


Creating a Referral

Referrals can be created by sending a POST or PUT request to the referrals route:

https://example.com/wp-json/affwp/v1/referrals

The create endpoint accepts any of the following affwp_add_referral() arguments:

  • affiliate_id – (integer) ID of the affiliate to associate the referral with. This field is required. See user_id and user_name.
  • user_id – (integer) User ID used to retrieve the associated affiliate ID if affiliate_id is not sent.
  • user_name – (string) Username used to retrieve the associated affiliate ID if affiliate_id is not sent.
  • amount – (float) Final, calculated referral amount, not the transaction or sales amount.
  • currency – (string) Referral amount currency.
  • description – (string) Referral description.
  • reference – (string) Referral reference. Usually this contains product information such as product IDs.
  • context – (string) Context under which the referral was created. Usually this is the integration slug.
  • status – (string) Accepts ‘paid’, ‘unpaid’, ‘pending’, or ‘rejected’. Default ‘pending’.

Creating a referral:

Method: PUT/POST
Endpoint: https://example.com/wp-json/affwp/v1/referrals/?affilite_id=30&amount=15

The above would create a new referral associated with affiliate ID 30 at an amount of $15 with status ‘pending’.

Example response:

{
  "referral_id": 450,
  "affiliate_id": 30,
  "visit_id": 0,
  "description": "",
  "status": "pending",
  "amount": "15.00",
  "currency": "USD",
  "custom": "",
  "context": "",
  "campaign": "",
  "reference": "",
  "products": "",
  "date": "2017-01-26 22:28:54",
  "payout_id": "0",
  "id": 450
}

Editing an Existing Referral

Single referrals can be updated by sending a POST or PATCH request to the referrals/[id] route:

https://example.com/wp-json/affwp/v1/referrals/[id]

The edit endpoint accepts any of the following affwp_process_update_referral() arguments:

  • affiliate_id – (integer) ID of the affiliate to associate the referral with.
  • visit_id – (integer) ID of the visit to associate the referral with.
  • amount – (float) Updated referral amount.
  • currency – (string) Updated referral amount currency.
  • description – (string) Updated referral description.
  • reference – (string) Referral reference. Usually this contains product information such as product IDs.
  • context – (string) Context under which the referral was created. Usually this is the integration slug.
  • status – (string) Accepts ‘paid’, ‘unpaid’, ‘pending’, or ‘rejected’.

Updating a Referral

In this example, we’ll update a referral’s status from  pending to paid.

Method: POST/PATCH
Endpoint: https://example.com/wp-json/affwp/v1/referrals/450?status=paid

Response:

{
  "referral_id": 450,
  "affiliate_id": 30,
  "visit_id": 0,
  "description": "",
  "status": "paid",
  "amount": "",
  "currency": "",
  "custom": "",
  "context": "",
  "campaign": "",
  "reference": "",
  "products": "",
  "date": "2017-01-26 22:28:54",
  "payout_id": "0",
  "id": 450
}

Deleting a Referral

A referral can be deleted by sending a DELETE request to the referrals/[id] route:

https://example.com/wp-json/affwp/v1/referrals/[id]

The delete endpoint accepts no additional arguments. When a referral as been successfully deleted, a key/value pair of deleted: true will be included in the response, along with a copy of the old referral response.

Example request:

Method: DELETE
Endpoint: https://example.com/wp-json/affwp/v1/referrals/450

Response:

{
  "deleted": true,
  "previous": {
    "referral_id": 35879,
    "affiliate_id": 5454,
    "visit_id": 0,
    "description": "",
    "status": "paid",
    "amount": "",
    "currency": "",
    "custom": "",
    "context": "",
    "campaign": "",
    "reference": "",
    "products": "",
    "date": "2017-01-26 22:28:54",
    "payout_id": "0",
    "id": 35879
  }
}

6. Managing Visits

REST API Extended adds three endpoints, one each for creatingediting, and deleting visits on top of the two read-only endpoints already available in AffiliateWP core.

All five endpoints leverage the same two route patterns:

  1. visits – When sent a GET request, a list of visits are returned and can be filtered with additional arguments. When sent a POST or PUT request, a new referral can be created.
  2. visits/[id] – When sent a GETPATCH, or DELETE request, a single visit can be retrieved, edited, or deleted, respectively.

Both routes can also accept generic OPTIONS requests, which can be very helpful for discovering information about available endpoints, accepted request types and arguments, and item schema.

All requests must be authenticated using API keys, which are generated and managed via the AffiliateWP → Tools → API Keys tab. Check out the REST API – Authentication article for more information.


Creating a Visit

Visits can be created by sending a POST or PUT request to the visits route:

https://example.com/wp-json/affwp/v1/visits

The create endpoint accepts any of the following arguments:

  • affiliate_id – (integer) ID of the affiliate to associate with the visit. This field is required.
  • referral_id – (integer) ID of the referral to associate with the visit.
  • url – (string) Visit URL.
  • referrer – (string) Referring URL
  • campaign – (string) Associated campaign.
  • ip – (string) IP address of the visitor.

Creating a visit:

Method: PUT/POST
Endpoint: https://example.com/wp-json/affwp/v1/visits/?affilite_id=30&url=https%3A%2F%2Faffiliatewp.com

The above would create a new visit associated with affiliate ID 30 that has a stored URL of https://affiliatewp.com.

Example response:

{
  "visit_id": 541,
  "affiliate_id": 30,
  "referral_id": 0,
  "url": "https://affiliatewp.com",
  "referrer": "",
  "campaign": "",
  "ip": "",
  "date": "2017-01-26 23:05:21",
  "id": 541
}

Editing an Existing Visit

Single visits can be updated by sending a POST or PATCH request to the visits/[id] route:

https://example.com/wp-json/affwp/v1/visits/[id]

The edit endpoint accepts any of the following arguments:

  • visit_id – (integer) ID of the visit. This field is required.
  • referral_id – (integer) ID of the referral to associate with the visit.
  • affiliate_id – (integer) ID of the affiliate to associate with the visit.
  • url – (string) Visit URL.
  • referrer – (string) Referring URL
  • campaign – (string) Associated campaign.
  • ip – (string) IP address of the visitor.

Updating a Visit

In this example, we’ll update a visit’s associated campaign:

Method: POST/PATCH
Endpoint: https://example.com/wp-json/affwp/v1/visits/541?campaign=spring-sale

Response:

{
  "visit_id": 541,
  "affiliate_id": 30,
  "referral_id": 0,
  "url": "https://affiliatewp.com",
  "referrer": "",
  "campaign": "spring-sale",
  "ip": "",
  "date": "2017-01-26 23:05:21",
  "id": 541
}

Deleting a Visit

A visit can be deleted by sending a DELETE request to the visits/[id] route:

https://example.com/wp-json/affwp/v1/visits/[id]

The delete endpoint accepts no additional arguments. When a visit as been successfully deleted, a key/value pair of deleted: true will be included in the response, along with a copy of the old visit response.

Example request:

Method: DELETE
Endpoint: https://example.com/wp-json/affwp/v1/visits/541

Response:

{
  "deleted": true,
  "previous": {
    "visit_id": 541,
    "affiliate_id": 30,
    "referral_id": 0,
    "url": "https://affiliatewp.com",
    "referrer": "",
    "campaign": "spring-sale",
    "ip": "",
    "date": "2017-01-26 23:05:21",
    "id": 541
  }
}

7. Example: WP-to-WP

Overview

The AffiliateWP REST API provides a powerful set of tools for interacting with the plugin and its data from afar.

One of the most common use cases (and the basis of some of our most popular requested features) have to do with being able to interact with AffiliateWP running on one WordPress-powered site via another WordPress-powered site.

The following examples cover how to send requests from one WordPress site to another WordPress site running AffiliateWP. We’ll cover how to build requests and analyze responses, as well as give a primer on what kind of experience to expect when interacting with the AffiliateWP REST API endpoints.

What you need to know

The following examples assume you have a baseline of knowledge about how WordPress handles sending remote requests and retrieving responses.

If you’re unfamiliar with the HTTP API or REST API, we recommend checking out the HTTP API article in the official plugin developer handbook as well as the REST API handbook.

Information Discovery

As outlined in the Managing Affiliates[ 1], Creatives[2], Payouts[3], Referrals[4], and Visits[5] sections, the REST API Extended add-on brings full CRUD (Create, Read, Update, and Delete) capabilities when interacting with AffiliateWP from afar.

For the most part, remote responses are structured consistently across object types. That said, depending on endpoint used, certain fields specific to the given object types will be required in various circumstances.

The easiest way to determine which fields are required or which parameters are accepted is to send an OPTIONS request to the endpoint; the response from the OPTIONS request should tell you everything you need to know.

For instance, the following is a section of the response of an OPTIONS request sent to the /v1/creatives/ endpoint with REST API Extended activated:

{
  "namespace": "affwp/v1",
  "methods": [
    "GET",
    "POST",
    "PUT",
    "PATCH"
  ],
  "endpoints": [
    {
      "methods": [
        "POST",
        "PUT",
        "PATCH"
      ],
      "args": {
        "name": {
          "required": false,
          "description": "Name of the creative.",
          "type": "string"
        },
        "description": {
          "required": false,
          "description": "Description for the creative.",
          "type": "string"
        },
        "url": {
          "required": false,
          "description": "URL the creative points to.",
          "type": "string"
        },
        "text": {
          "required": false,
          "description": "Text for the creative.",
          "type": "string"
        },
        "image": {
          "required": false,
          "description": "ID of the media library image associated with the creative",
          "type": "integer"
        },
        "status": {
          "required": false,
          "description": "The creative status.",
          "type": "string"
        },
        "date": {
          "required": false,
          "description": "The date the creative was created.",
          "type": "string"
        }
      }
    }
  ],

You can see that the available request methods for this endpoint are clearly listed and available arguments for each defined and listed within the hierarchy below. Other useful information passed back in an OPTIONS request includes schema information – defining the fields that will be present in a single object, and more.

Building Requests

Now that you have a good basis in what you need to know and how to find out more information, let’s build some sample requests.

Authenticating

If you remember from the REST API v1 Overview article, all requests sent need to include an Authorization header built using the Basic Auth scheme. The Basic Auth header in AffiliateWP is achieved using the public key and token values. The following is an example of a Basic Auth header:

Authorization : Basic N2Q4NTM1OWM4NzlkYWNjOWE2ZmMxZjgxYjQ2ZDYyZDE6YmE3YjUwZGUyMjZkOGI2YzRkNjQyMjA1YjcwNDUwMjY=

“Authorization” is the key, and “Basic N2Q4NTM…” is the value. The value is built by encoding the combination of the public key and token values, separated by a colon, and concatenating “Basic ” on the front. For example:

"Basic " . base64_encode( "{$public_key}:{$token}" );

When using WordPress HTTP API functions, the Authorization header should be sent as follows:

wp_remote_*( 'request_url', array(<br>    'headers' => array(<br>        'Authorization' => 'Basic hash_value'<br>    )<br>) );

For more information on how the AffiliateWP REST API authenticates, check out the REST API – Authentication article.

Example Request: Create an affiliate

As noted in the Managing Affiliates section, a user_id is required when creating an affiliate. Alternatively, the create_user argument can be sent along with a payment_email value to create a user and an affiliate in the same step.

The following is the WordPress code needed to remotely create an affiliate when you already have a valid user_id:

$request_url = add_query_arg( array( 
    'user_id' => 5 
), 

'https://example.com/wp-json/affwp/v1/affiliates' );

$response = wp_remote_post( $request_url, array(
    'headers' => array(
        'Authorization' => 'Basic hash_value'
    )
) );

In the above snippet, note that the user_id value is passed via $request_url vs via the ‘body’ argument, which is supported for POST requests. This is done for consistency with other endpoints’ examples, namely those leveraging the PUT or PATCH methods, which don’t support sending parameters via the request body.

Example Request: Create a payout

Similarly to creating affiliates, new payouts also require certain fields, specifically affiliate_id and referrals values.

The following is the code needed to remotely create a new payout, given a valid affiliate_id and list of referral IDs:

$request_url = add_query_arg( array(
    'affiliate_id'  => 2,
    'referrals'     => '2,3,4',
    'payout_method' => 'REST',
), 

'https://example.com/wp-json/affwp/v1/payouts' );

$response = wp_remote_post( $request_url, array(
    'headers' => array(
        'Authorization' => 'Basic hash_value'
    )
) );

Note that the payout_method value is not necessarily needed, just nice to provide context that the payout was generated via REST.

Example Request: Updating a referral

When updating an object via REST, it’s worth noting that since the ID of the object you’re modifying is actually part of the endpoint, that primary key’s value doesn’t also need to be sent with the request.

The following is an example for how to update a referral’s status from unpaid to paid:

$request_url = add_query_arg( array( 
'status' => 'paid', 

'https://example.com/wp-json/affwp/v1/referrals/3' );

$response = wp_remote_request( $request_url, array(
    'method'  => 'PATCH',
    'headers' => array(
        'Authorization' => 'Basic hash_value'
    )
) );

Note that instead of wp_remote_post() as before, this request uses wp_remote_request() with the ‘method’ => ‘PATCH’ argument passed. This tells the REST API that you’re specifically sending a PATCH request.

Also note that the referral ID of 3 is passed as part of the endpoint rather than in the URL like status is.

Analyzing Responses

In addition to crafting requests, it’s important to have a good handle on how responses are structured and to be familiar with how to validate that a request was successful within the WordPress sphere.

In the first two examples under “Building Requests” we talked about crafting requests for creating new affiliates and payouts.

When examining a response, one of the simplest ways to confirm it was successful is to look at the response code:

$response_code = wp_remote_retrieve_response_code( $response );

if ( 201 === $response_code ) {
    // success
}

In the case of AffiliateWP’s  creation and update endpoints, successful requests will send back responses with status code 201. For successful  deletion requests, response codes will be the default 200.

Responses sent back for successful deletion requests will also include a deleted: true key:value pair, along with a copy the former object:

{
  "deleted": true,
  "previous": {
    "affiliate_id": 35,
    "user_id": 11,
    "rate": "",
    "rate_type": "",
    "payment_email": "[email protected]",
    "status": "active",
    "earnings": 0,
    "unpaid_earnings": 0,
    "referrals": 0,
    "visits": 0,
    "date_registered": "2017-01-31 07:31:05",
    "id": 35
  }
}

All together now

Now that we’ve covered how to craft requests and analyze responses, let’s look at how to craft a create affiliate request, then examine and proceed with parsing the retrieved information on success:

$request_url = add_query_arg( array( 
   'user_id' => 5 ), 

'https://example.com/wp-json/affwp/v1/affiliates' );

// Send the request, storing the return in $response.
$response = wp_remote_post( $request_url, array(
    'headers' => array(
        'Authorization' => 'Basic hash_value'
    )
) );

// Check for the requisite response code. If 201, retrieve the response body and continue.
if ( 201 === wp_remote_retrieve_response_code( $response ) ) {
    $body = wp_remote_retrieve_body( $response );
    // do something successful
} else {
    // maybe display an error message
}

Wrap up

In this article we’ve covered a lot of information. The major points covered were:

  • How to build Authorization headers for requests
  • Fundamentals for crafting remote requests
  • Fundamentals for examining responses

In closing, it’s worth mentioning that all of the examples in this article are working examples, given that the Authorization header values have been crafted correctly.

One major point not covered here is API key security. It’s easy enough to hard-code API keys and offload crafting the Authorization header values to a helper function, but if you’re planning to distribute your code, precautions should be taken to ensure you don’t accidentally distribute your keys as well.

If you’re working on the front-end with JavaScript, one common method for mitigating unintended exposure of secret keys is to offload the sending of remote requests and parsing of responses to Ajax handlers, allowing PHP to handle the business end of the request.

User Reviews

0.0 out of 5
0
0
0
0
0
Write a review

There are no reviews yet.

Be the first to review “AffiliateWP REST API Extended”

Your email address will not be published. Required fields are marked *

AffiliateWP REST API Extended
AffiliateWP REST API Extended

Original price was: $149.00.Current price is: $0.00.

ThemesGala.com
Logo
Compare items
  • Total (0)
Compare
0