├── .gitignore ├── LICENSE ├── README.md ├── composer.json ├── demoapp ├── README ├── _shared.php ├── accountlist.php ├── index.php ├── login.php ├── logout.php ├── openaccount.php └── user.php ├── iframe_demoapp ├── checkout.php └── list_accounts.php └── wepay.php /.gitignore: -------------------------------------------------------------------------------- 1 | vendor/ 2 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright (C) 2013-2015 WePay, Inc. 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | WePay SDK for PHP 2 | ============= 3 | 4 | WePay's API allows you to easily add payments into your application. 5 | 6 | For full documentation, see [WePay's developer documentation](https://www.wepay.com/developer) 7 | 8 | Installation 9 | ------------ 10 | 11 | Using [Composer]: 12 | ```bash 13 | composer require wepay/php-sdk=^0.3 14 | ``` 15 | 16 | And include it in your scripts: 17 | 18 | ```php 19 | require_once 'vendor/autoload.php'; 20 | ``` 21 | 22 | 23 | Usage 24 | ----- 25 | 26 | In addition to the samples below, we have included a very basic demo application in the `demoapp` directory. See its README file for additional information. 27 | 28 | ### Configuration ### 29 | 30 | For all requests, you must initialize the SDK with your Client ID and Client Secret, into either Staging or Production mode. All API calls made against WePay's staging environment mirror production in functionality, but do not actually move money. This allows you to develop your application and test the checkout experience from the perspective of your users without spending any money on payments. Our [full documentation](https://www.wepay.com/developer) contains additional information on test account numbers you can use in addition to "magic" amounts you can use to trigger payment failures and reversals (helpful for testing IPNs). 31 | 32 | **Note:** Staging and Production are two completely independent environments and share NO data with each other. This means that in order to use staging, you must register at [stage.wepay.com](https://stage.wepay.com/developer) and get a set of API keys for your Staging application, and must do the same on Production when you are ready to go live. API keys and access tokens granted on stage *can not* be used on Production, and vice-versa. 33 | 34 | ```php 35 | access_token; 73 | } else { 74 | // Unable to obtain access token 75 | } 76 | } 77 | ``` 78 | 79 | Full details on the access token response are [here](https://www.wepay.com/developer/reference/oauth2#token). 80 | 81 | **Note:** If you only need access for yourself (e.g., for a personal storefront), the application settings page automatically creates an access token for you. Simply copy and paste it into your code rather than manually going through the authentication flow. 82 | 83 | ### Making API Calls ### 84 | 85 | With the `$access_token` from above, get a new SDK object: 86 | 87 | ```php 88 | $wepay = new WePay($access_token); 89 | ``` 90 | 91 | Then you can make a simple API call. This will list the user's accounts available to your application: 92 | 93 | ```php 94 | // (continued from above) 95 | try { 96 | $accounts = $wepay->request('account/find'); 97 | 98 | foreach ($accounts as $account) { 99 | // Please never blend your views with your business logic like this! 100 | echo "account_uri\">$account->name: $account->description
"; 101 | } 102 | } catch (WePayException $e) { 103 | // Something went wrong - normally you would log 104 | // this and give your user a more informative message 105 | echo $e->getMessage(); 106 | } 107 | ``` 108 | 109 | For more details on which API calls are available, their parameters and responses, and which permissions they require, 110 | please see [our documentation](https://www.wepay.com/developer/reference). For some more detailed examples, look in the 111 | `demoapp` directory and check the README. Dropping the entire directory in a web-accessible location and adding your 112 | API keys should allow you to be up and running in just a few seconds. 113 | 114 | ### Risk Headers ### 115 | 116 | You can supply WePay with risk-related information on every API call by passing the WePay-Risk-Token and Client-IP values to the `request` function: 117 | 118 | ``` 119 | $checkout = $wepay->request('checkout/create', array( 120 | 'account_id' => 1723052, 121 | 'amount' => 50, 122 | 'currency': 'USD', 123 | 'short_description': 'Selling 42 Pens', 124 | 'type': 'goods' 125 | ), '123e4567-e89b-12d3-a456-426655440000', '100.166.99.123'); 126 | ``` 127 | 128 | Detailed information regarding the Risk Headers can be found at the [WePay API Documentation](https://developer.wepay.com/reference/risk_headers). 129 | 130 | Security 131 | -------- 132 | 133 | ### Connections require TLS 1.2 ### 134 | 135 | According to updated PCI requirements, SSL (v2, v3) and early TLS (1.0, 1.1) are no longer considered “strong 136 | cryptography” and cannot be used as a security control after 2016-06-30. Because of this, WePay will be updating its API 137 | endpoints to only allow TLS 1.2 connections over the coming months. 138 | 139 | WePay SDK for PHP version 0.3.0 is _possibly_ backwards-incompatible depending on how new or old your PHP stack is, 140 | hence the [Semantic Versioning](http://semver.org) bump. 141 | 142 | Using the [PHP cURL extension](https://secure.php.net/manual/en/intro.curl.php), PHP will make outbound requests via the 143 | system’s cURL installation. For licensing reasons, the PHP cURL extension uses NSS instead of OpenSSL. 144 | 145 | * [PHP (Zend Engine) 5.5.19+ or 5.6.3+ is required](https://secure.php.net/manual/en/curl.constants.php). 146 | * The PHP cURL extension requires cURL `7.34.0` (or newer) on the underlying system. 147 | * The PHP cURL extension must be compiled with NSS `3.15.1` (or newer). 148 | * HHVM 3.0 (or newer) and/or Hacklang (any version) has [the same cURL and cURL extension requirements as for 149 | PHP](https://twitter.com/SaraMG/status/631654826426798081). 150 | 151 | 152 | ### SSL Certificate ### 153 | 154 | If making an API call causes the following problem: 155 | 156 | > Uncaught exception 'Exception' with message 'cURL error while making API call to WePay: SSL certificate problem, verify that the CA cert is OK. Details: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed' 157 | 158 | You can read the solution here: https://support.wepay.com/entries/21095813-problem-with-ssl-certificate-verification 159 | 160 | [Composer]: http://getcomposer.org 161 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "wepay/php-sdk", 3 | "description": "WePay APIv2 SDK for PHP", 4 | "keywords": ["wepay", "payment", "sdk"], 5 | "license": "Apache-2.0", 6 | "authors": [ 7 | { 8 | "name": "WePay", 9 | "email": "api@wepay.com" 10 | } 11 | ], 12 | "support": { 13 | "issues": "https://github.com/wepay/PHP-SDK/issues" 14 | }, 15 | "require": { 16 | "php": ">=5.3.0", 17 | "ext-curl": "*" 18 | }, 19 | "autoload": { 20 | "classmap": [ 21 | "wepay.php" 22 | ] 23 | }, 24 | "extra": { 25 | "branch-alias": { 26 | "dev-master": "0.2.x-dev" 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /demoapp/README: -------------------------------------------------------------------------------- 1 | After registering your application at wepay.com (or stage.wepay.com), you 2 | need to make two updates to this application: 3 | 4 | 1 - set your client_id and client_secret in _shared.php 5 | 2 - set the redirect_uri in login.php 6 | 7 | That should be enough to start making API calls against WePay's API. While 8 | this is by no means a production-ready example, it should provide you a 9 | couple ideas on how to get running. 10 | 11 | It also defaults to requesting all possible scope fields in the 12 | authentication request. We suggest limiting the request to the minimum 13 | your application requires, which will maximize the chance the user 14 | grants permissions to your application. You can customize this in 15 | login.php. 16 | 17 | If you have any questions, please contact the API team: api@wepay.com 18 | 19 | - WePay 20 | -------------------------------------------------------------------------------- /demoapp/_shared.php: -------------------------------------------------------------------------------- 1 | 4 |

WePay Demo App: Account List

5 | Back 6 |
7 | 8 | request('account/find'); 12 | foreach ($accounts as $account) { 13 | echo "account_uri) . "\">"; 14 | echo htmlspecialchars($account->name); 15 | echo ": "; 16 | echo htmlspecialchars($account->description) . "
"; 17 | } 18 | } 19 | catch (WePayException $e) { 20 | // Something went wrong - normally you would log 21 | // this and give your user a more informative message 22 | echo $e->getMessage(); 23 | } 24 | -------------------------------------------------------------------------------- /demoapp/index.php: -------------------------------------------------------------------------------- 1 | 4 | 5 |

WePay Demo App

6 | 7 | 8 | Log in with WePay 9 | 10 | 11 | 12 | User info 13 |
14 | Open new account 15 |
16 | Account list 17 |
18 | Log out 19 | 20 | 21 | -------------------------------------------------------------------------------- /demoapp/login.php: -------------------------------------------------------------------------------- 1 | access_token; 34 | // If desired, you can also store $info->user_id somewhere 35 | header('Location: index.php'); 36 | } 37 | else { 38 | // Unable to obtain access token 39 | echo 'Unable to obtain access token from WePay.'; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /demoapp/logout.php: -------------------------------------------------------------------------------- 1 | 4 |

WePay Demo App: Open Account

5 | Back 6 |
7 | 8 | request('account/create', array( 14 | 'name' => $_POST['account_name'], 15 | 'description' => $_POST['account_description'], 16 | )); 17 | // WePay sanitizes its own data, but displaying raw POST data on your own site is a XSS security hole. 18 | $name = htmlspecialchars($_POST['account_name']); 19 | $desc = htmlspecialchars($_POST['account_description']); 20 | $account_uri = htmlspecialchars($account->account_uri); 21 | echo "Created account $name for '$desc'! View on WePay at $account_uri. See all of your accounts here."; 22 | } 23 | catch (WePayException $e) { 24 | // Something went wrong - normally you would log 25 | // this and give your user a more informative message 26 | echo $e->getMessage(); 27 | } 28 | } 29 | else { 30 | echo 'Account name and description are both required.'; 31 | } 32 | } 33 | ?> 34 | 35 |
36 |
37 | Account Info 38 | 39 |
40 | 41 | 42 |

43 | 44 |
45 | 46 | 47 |

48 | 49 | 50 |
51 |
52 | -------------------------------------------------------------------------------- /demoapp/user.php: -------------------------------------------------------------------------------- 1 | 4 |

WePay Demo App: User Info

5 | Back 6 |
7 | 8 | request('user'); 12 | echo '
'; 13 | foreach ($user as $key => $value) { 14 | echo "
" . htmlspecialchars($key) . "
"; 15 | echo "
" . htmlspecialchars($value) . "
"; 16 | } 17 | echo '
'; 18 | } 19 | catch (WePayException $e) { 20 | // Something went wrong - normally you would log 21 | // this and give your user a more informative message 22 | echo $e->getMessage(); 23 | } 24 | -------------------------------------------------------------------------------- /iframe_demoapp/checkout.php: -------------------------------------------------------------------------------- 1 | request('/checkout/create', array( 31 | 'account_id' => $account_id, // ID of the account that you want the money to go to 32 | 'amount' => 100, // dollar amount you want to charge the user 33 | 'currency' => "USD", // the currency used 34 | 'short_description' => "this is a test payment", // a short description of what the payment is for 35 | 'type' => "goods", // the type of the payment - choose from 'goods', 'service', 'donation', 'event', or 'personal' 36 | 'hosted_checkout' => ['mode' => "iframe"], // user 'hosted_checkout' parameter if you want the checkout to be in an iframe, use 'payment_method' parameter instead if you want to use payment information your platform has previously aquired 37 | ) 38 | ); 39 | } catch (WePayException $e) { // if the API call returns an error, get the error message for display later 40 | $error = $e->getMessage(); 41 | } 42 | 43 | ?> 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 |

Checkout:

52 | 53 |

The user will checkout here:

54 | 55 | 56 |

ERROR:

57 | 58 |
59 | 60 | 62 | 63 | 66 | 67 | 68 | 69 | 70 | 71 | -------------------------------------------------------------------------------- /iframe_demoapp/list_accounts.php: -------------------------------------------------------------------------------- 1 | request('/account/find'); 31 | } catch (WePayException $e) { // if the API call returns an error, get the error message for display later 32 | $error = $e->getMessage(); 33 | } 34 | 35 | ?> 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 |

List all accounts:

44 | 45 |

The following is a list of all accounts that this user owns

46 | 47 | 48 |

ERROR:

49 | 50 |

You do not have any accounts. Go to https://stage.wepay.com to open an account.

51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 |
Account IDAccount NameAccount Description
account_id); ?>name); ?>description); ?>
70 | 71 | 72 | 73 | 74 | -------------------------------------------------------------------------------- /wepay.php: -------------------------------------------------------------------------------- 1 | 4 | * 5 | * Permission is hereby granted, free of charge, to any person obtaining a 6 | * copy of this software and associated documentation files (the "Software"), 7 | * to deal in the Software without restriction, including without limitation 8 | * the rights to use, copy, modify, merge, publish, distribute, sublicense, 9 | * and/or sell copies of the Software, and to permit persons to whom the 10 | * Software is furnished to do so, subject to the following conditions: 11 | * 12 | * The above copyright notice and this permission notice shall be included in 13 | * all copies or substantial portions of the Software. 14 | * 15 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 18 | * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 20 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 21 | * DEALINGS IN THE SOFTWARE. 22 | */ 23 | 24 | class WePay 25 | { 26 | /** 27 | * Version number - sent in user agent string 28 | */ 29 | const VERSION = '0.3.1'; 30 | 31 | /** 32 | * Scope fields 33 | * Passed into Wepay::getAuthorizationUri as array 34 | */ 35 | const SCOPE_MANAGE_ACCOUNTS = 'manage_accounts'; // Open and interact with accounts 36 | const SCOPE_COLLECT_PAYMENTS = 'collect_payments'; // Create and interact with checkouts 37 | const SCOPE_VIEW_USER = 'view_user'; // Get details about authenticated user 38 | const SCOPE_PREAPPROVE_PAYMENTS = 'preapprove_payments'; // Create and interact with preapprovals 39 | const SCOPE_MANAGE_SUBSCRIPTIONS = 'manage_subscriptions'; // Subscriptions 40 | const SCOPE_SEND_MONEY = 'send_money'; // For withdrawals 41 | 42 | /** 43 | * Application's client ID 44 | */ 45 | private static $client_id; 46 | 47 | /** 48 | * Application's client secret 49 | */ 50 | private static $client_secret; 51 | 52 | 53 | /** 54 | * API Version 55 | * https://www.wepay.com/developer/reference/versioning 56 | */ 57 | private static $api_version; 58 | 59 | /** 60 | * @deprecated Use WePay::getAllScopes() instead. 61 | */ 62 | public static $all_scopes = array( 63 | self::SCOPE_MANAGE_ACCOUNTS, 64 | self::SCOPE_COLLECT_PAYMENTS, 65 | self::SCOPE_PREAPPROVE_PAYMENTS, 66 | self::SCOPE_VIEW_USER, 67 | self::SCOPE_SEND_MONEY, 68 | self::SCOPE_MANAGE_SUBSCRIPTIONS 69 | ); 70 | 71 | /** 72 | * Determines whether to use WePay's staging or production servers 73 | */ 74 | private static $production = null; 75 | 76 | /** 77 | * cURL handle 78 | */ 79 | private static $ch = NULL; 80 | 81 | /** 82 | * Authenticated user's access token 83 | */ 84 | private $token; 85 | 86 | /** 87 | * Pass WePay::getAllScopes() into getAuthorizationUri if your application desires full access 88 | */ 89 | public static function getAllScopes() 90 | { 91 | return array( 92 | self::SCOPE_MANAGE_ACCOUNTS, 93 | self::SCOPE_MANAGE_SUBSCRIPTIONS, 94 | self::SCOPE_COLLECT_PAYMENTS, 95 | self::SCOPE_PREAPPROVE_PAYMENTS, 96 | self::SCOPE_VIEW_USER, 97 | self::SCOPE_SEND_MONEY 98 | ); 99 | } 100 | 101 | /** 102 | * Generate URI used during oAuth authorization 103 | * Redirect your user to this URI where they can grant your application 104 | * permission to make API calls 105 | * 106 | * @link https://www.wepay.com/developer/reference/oauth2 107 | * 108 | * @param array $scope List of scope fields for which your application wants access. 109 | * @param string $redirect_uri Where user goes after logging in at WePay (domain must match application settings). 110 | * @param array $options `user_name,user_email` which will be pre-filled on login form, state to be returned 111 | * in query string of redirect_uri. The default value is an empty array. 112 | * @return string URI to which you must redirect your user to grant access to your application 113 | */ 114 | public static function getAuthorizationUri(array $scope, $redirect_uri, array $options = array()) 115 | { 116 | // This does not use WePay::getDomain() because the user authentication 117 | // domain is different than the API call domain 118 | if (self::$production === null) { 119 | throw new RuntimeException('You must initialize the WePay SDK with WePay::useStaging() or WePay::useProduction()'); 120 | } 121 | 122 | $domain = self::$production ? 'https://www.wepay.com' : 'https://stage.wepay.com'; 123 | $uri = $domain . '/v2/oauth2/authorize?'; 124 | $uri .= http_build_query(array( 125 | 'client_id' => self::$client_id, 126 | 'redirect_uri' => $redirect_uri, 127 | 'scope' => implode(',', $scope), 128 | 'state' => empty($options['state']) ? '' : $options['state'], 129 | 'user_name' => empty($options['user_name']) ? '' : $options['user_name'], 130 | 'user_email' => empty($options['user_email']) ? '' : $options['user_email'], 131 | 'user_country' => empty($options['user_country']) ? '' : $options['user_country'], 132 | ), '', '&'); 133 | 134 | return $uri; 135 | } 136 | 137 | private static function getDomain() 138 | { 139 | if (self::$production === true) { 140 | return 'https://wepayapi.com/v2/'; 141 | } elseif (self::$production === false) { 142 | return 'https://stage.wepayapi.com/v2/'; 143 | } else { 144 | throw new RuntimeException('You must initialize the WePay SDK with WePay::useStaging() or WePay::useProduction()'); 145 | } 146 | } 147 | 148 | /** 149 | * Exchange a temporary access code for a (semi-)permanent access token 150 | * @param string $code 'code' field from query string passed to your redirect_uri page 151 | * @param string $redirect_uri Where user went after logging in at WePay (must match value from getAuthorizationUri) 152 | * @return StdClass|false 153 | * user_id 154 | * access_token 155 | * token_type 156 | */ 157 | public static function getToken($code, $redirect_uri) 158 | { 159 | $params = (array( 160 | 'client_id' => self::$client_id, 161 | 'client_secret' => self::$client_secret, 162 | 'redirect_uri' => $redirect_uri, 163 | 'code' => $code, 164 | 'state' => '', // do not hardcode 165 | )); 166 | $result = self::make_request('oauth2/token', $params); 167 | return $result; 168 | } 169 | 170 | /** 171 | * Configure SDK to run against WePay's production servers 172 | * @param string $client_id Your application's client id 173 | * @param string $client_secret Your application's client secret 174 | * @return void 175 | * @throws RuntimeException 176 | */ 177 | public static function useProduction($client_id, $client_secret, $api_version = null) 178 | { 179 | if (self::$production !== null) { 180 | throw new RuntimeException('API mode has already been set.'); 181 | } 182 | self::$production = true; 183 | self::$client_id = $client_id; 184 | self::$client_secret = $client_secret; 185 | self::$api_version = $api_version; 186 | } 187 | 188 | /** 189 | * Configure SDK to run against WePay's staging servers 190 | * @param string $client_id Your application's client id 191 | * @param string $client_secret Your application's client secret 192 | * @return void 193 | * @throws RuntimeException 194 | */ 195 | public static function useStaging($client_id, $client_secret, $api_version = null) 196 | { 197 | if (self::$production !== null) { 198 | throw new RuntimeException('API mode has already been set.'); 199 | } 200 | self::$production = false; 201 | self::$client_id = $client_id; 202 | self::$client_secret = $client_secret; 203 | self::$api_version = $api_version; 204 | } 205 | 206 | /** 207 | * Returns the current environment. 208 | * @return string "none" (not configured), "production" or "staging". 209 | */ 210 | public static function getEnvironment() 211 | { 212 | if (self::$production === null) { 213 | return 'none'; 214 | } elseif (self::$production) { 215 | return 'production'; 216 | } else { 217 | return 'staging'; 218 | } 219 | } 220 | 221 | /** 222 | * Set Api Version 223 | * https://www.wepay.com/developer/reference/versioning 224 | * 225 | * @param string $version Api Version to send in call request header 226 | */ 227 | public static function setApiVersion($version) 228 | { 229 | self::$api_version = $version; 230 | } 231 | 232 | /** 233 | * Create a new API session 234 | * @param string $token - access_token returned from WePay::getToken 235 | */ 236 | public function __construct($token) 237 | { 238 | if ($token && !is_string($token)) { 239 | throw new InvalidArgumentException('$token must be a string, ' . gettype($token) . ' provided'); 240 | } 241 | $this->token = $token; 242 | } 243 | 244 | /** 245 | * Clean up cURL handle 246 | */ 247 | public function __destruct() 248 | { 249 | if (self::$ch) { 250 | curl_close(self::$ch); 251 | self::$ch = NULL; 252 | } 253 | } 254 | 255 | /** 256 | * create the cURL request and execute it 257 | */ 258 | private static function make_request($endpoint, $values, $headers = array()) 259 | { 260 | self::$ch = curl_init(); 261 | $headers = array_merge(array("Content-Type: application/json"), $headers); // always pass the correct Content-Type header 262 | 263 | // send Api Version header 264 | if (!empty(self::$api_version)) { 265 | $headers[] = "Api-Version: " . self::$api_version; 266 | } 267 | 268 | curl_setopt(self::$ch, CURLOPT_USERAGENT, 'WePay v2 PHP SDK v' . self::VERSION . ' Client id:' . self::$client_id); 269 | curl_setopt(self::$ch, CURLOPT_RETURNTRANSFER, true); 270 | curl_setopt(self::$ch, CURLOPT_HTTPHEADER, $headers); 271 | curl_setopt(self::$ch, CURLOPT_TIMEOUT, 30); // 30-second timeout, adjust to taste 272 | curl_setopt(self::$ch, CURLOPT_POST, !empty($values)); // WePay's API is not strictly RESTful, so all requests are sent as POST unless there are no request values 273 | 274 | // Force TLS 1.2 connections 275 | curl_setopt(self::$ch, CURLOPT_SSL_VERIFYPEER, true); 276 | curl_setopt(self::$ch, CURLOPT_SSL_VERIFYHOST, 2); 277 | curl_setopt(self::$ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2); 278 | 279 | $uri = self::getDomain() . $endpoint; 280 | curl_setopt(self::$ch, CURLOPT_URL, $uri); 281 | 282 | if (!empty($values)) { 283 | curl_setopt(self::$ch, CURLOPT_POSTFIELDS, json_encode($values)); 284 | } 285 | 286 | $raw = curl_exec(self::$ch); 287 | if ($errno = curl_errno(self::$ch)) { 288 | // Set up special handling for request timeouts 289 | if ($errno == CURLE_OPERATION_TIMEOUTED) { 290 | throw new WePayServerException("Timeout occurred while trying to connect to WePay"); 291 | } 292 | throw new Exception('cURL error while making API call to WePay: cURL Errno - ' . $errno . ', ' . curl_error(self::$ch), $errno); 293 | } 294 | 295 | $result = json_decode($raw); 296 | $httpCode = curl_getinfo(self::$ch, CURLINFO_HTTP_CODE); 297 | 298 | if ($httpCode >= 400) { 299 | if (!isset($result->error_code)) { 300 | throw new WePayServerException("WePay returned an error response with no error_code, please alert api@wepay.com. Original message: $result->error_description", $httpCode, $result, 0); 301 | } 302 | if ($httpCode >= 500) { 303 | throw new WePayServerException($result->error_description, $httpCode, $result, $result->error_code); 304 | } 305 | switch ($result->error) { 306 | case 'invalid_request': 307 | throw new WePayRequestException($result->error_description, $httpCode, $result, $result->error_code); 308 | case 'access_denied': 309 | default: 310 | throw new WePayPermissionException($result->error_description, $httpCode, $result, $result->error_code); 311 | } 312 | } 313 | 314 | return $result; 315 | } 316 | 317 | /** 318 | * Make API calls against authenticated user 319 | * @param string $endpoint - API call to make (ex. 'user', 'account/find') 320 | * @param array $values - Associative array of values to send in API call 321 | * @param string $risk_token - WePay-supplied risk token associated with this API call 322 | * @param string $client_ip - Client's IP address associated with this API call 323 | * @return StdClass 324 | * @throws WePayException on failure 325 | * @throws Exception on catastrophic failure (non-WePay-specific cURL errors) 326 | */ 327 | public function request($endpoint, array $values = array(), $risk_token = null, $client_ip = null) 328 | { 329 | $headers = array(); 330 | 331 | if ($this->token) { // if we have an access_token, add it to the Authorization header 332 | $headers[] = "Authorization: Bearer $this->token"; 333 | } 334 | 335 | if ($risk_token) { // if we have a risk_token, add it to the WePay-Risk-Token header 336 | $headers[] = "WePay-Risk-Token: " . $risk_token; 337 | } 338 | 339 | if ($client_ip) { // if we have a client_ip, add it to the Client-IP header 340 | $headers[] = "Client-IP: " . $client_ip; 341 | } 342 | 343 | $result = self::make_request($endpoint, $values, $headers); 344 | 345 | return $result; 346 | } 347 | } 348 | 349 | /** 350 | * Different problems will have different exception types so you can 351 | * catch and handle them differently. 352 | * 353 | * WePayServerException indicates some sort of 500-level error code and 354 | * was unavoidable from your perspective. You may need to re-run the 355 | * call, or check whether it was received (use a "find" call with your 356 | * reference_id and make a decision based on the response) 357 | * 358 | * WePayRequestException indicates a development error - invalid endpoint, 359 | * erroneous parameter, etc. 360 | * 361 | * WePayPermissionException indicates your authorization token has expired, 362 | * was revoked, or is lacking in scope for the call you made 363 | */ 364 | class WePayException extends Exception 365 | { 366 | public function __construct($description = '', $http_code = FALSE, $response = FALSE, $code = 0, $previous = NULL) 367 | { 368 | $this->response = $response; 369 | 370 | if (!defined('PHP_VERSION_ID')) { 371 | $version = explode('.', PHP_VERSION); 372 | define('PHP_VERSION_ID', ($version[0] * 10000 + $version[1] * 100 + $version[2])); 373 | } 374 | 375 | if (PHP_VERSION_ID < 50300) { 376 | parent::__construct($description, $code); 377 | } else { 378 | parent::__construct($description, $code, $previous); 379 | } 380 | } 381 | } 382 | class WePayRequestException extends WePayException {} 383 | class WePayPermissionException extends WePayException {} 384 | class WePayServerException extends WePayException {} 385 | --------------------------------------------------------------------------------