├── .github └── workflows │ ├── launch-release-after-closed-pr.yml │ └── release.yml ├── .gitignore ├── LICENSE ├── README.md ├── README.txt ├── SCMerchantClient ├── Config.php ├── Enum │ └── OrderStatus.php ├── Exception │ ├── ApiError.php │ └── GenericError.php ├── Http │ ├── CreateOrderRequest.php │ ├── CreateOrderResponse.php │ └── OrderCallback.php ├── SCMerchantClient.php └── Utils.php ├── SP_LICENSE ├── assets ├── images │ ├── card_phone_top.svg │ └── spectrocoin-logo.svg ├── js │ └── block-checkout.js └── style │ └── settings.css ├── changelog.md ├── composer.json ├── composer.lock ├── includes ├── SpectroCoinAuthHandler.php ├── SpectroCoinBlocksIntegration.php └── SpectroCoinGateway.php ├── phpunit.xml ├── spectrocoin.php └── tests ├── SCMerchantClient ├── ConfigTest.php ├── Enum │ └── OrderStatusTest.php ├── Exception │ └── ExceptionTest.php ├── Http │ ├── CreateOrderRequestTest.php │ ├── CreateOrderResponseTest.php │ └── OrderCallbackTest.php ├── SCMerchantClientTest.php └── UtilsTest.php └── bootstrap.php /.github/workflows/launch-release-after-closed-pr.yml: -------------------------------------------------------------------------------- 1 | name: Launch release.yml after closed PR 2 | 3 | on: 4 | pull_request: 5 | types: 6 | - closed 7 | 8 | jobs: 9 | Launch_tag_creation_workflow: 10 | if: github.event.pull_request.merged == true 11 | runs-on: ubuntu-latest 12 | 13 | steps: 14 | - name: Checkout code 15 | uses: actions/checkout@v4 16 | 17 | - name: Trigger tag creation in the base repo 18 | run: | 19 | echo "Triggering the tag creation workflow in the base repository." 20 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Create tag and release 2 | 3 | permissions: 4 | contents: write 5 | 6 | on: 7 | workflow_run: 8 | workflows: ["Launch release.yml after closed PR"] 9 | types: 10 | - completed 11 | workflow_dispatch: 12 | 13 | jobs: 14 | create_tag_and_release: 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - name: Checkout code 19 | uses: actions/checkout@v4 20 | with: 21 | fetch-depth: 0 22 | 23 | - name: Set up Git 24 | run: | 25 | git config --global user.email "actions@github.com" 26 | git config --global user.name "GitHub Actions" 27 | 28 | - name: Install GitHub CLI 29 | run: sudo apt-get install gh 30 | 31 | - name: Fetch Latest PR Info and Check for Existing Tag 32 | id: check_tag 33 | env: 34 | GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} 35 | run: | 36 | # Fetch the latest merged PR title and body using GitHub CLI 37 | PR_TITLE=$(gh pr list --state merged --limit 1 --json title --jq '.[0].title') 38 | PR_BODY=$(gh pr list --state merged --limit 1 --json body --jq '.[0].body') 39 | TAG_NAME=$(echo "$PR_TITLE" | sed 's/ /_/g') # Replace spaces with underscores 40 | 41 | # Check if the tag already exists 42 | if git rev-parse "$TAG_NAME" >/dev/null 2>&1; then 43 | echo "Tag '$TAG_NAME' already exists. Exiting workflow." 44 | echo "TAG_EXISTS=true" >> $GITHUB_ENV 45 | exit 0 46 | else 47 | echo "TAG_EXISTS=false" >> $GITHUB_ENV 48 | echo "PR_TITLE: $PR_TITLE" 49 | echo "PR_BODY: $PR_BODY" 50 | echo "TAG_NAME: $TAG_NAME" 51 | 52 | # Create the tag and push it 53 | git tag "$TAG_NAME" 54 | git push origin "$TAG_NAME" 55 | 56 | # Create a release using GitHub CLI with the tag name and PR details 57 | RELEASE_OUTPUT=$(gh release create "$TAG_NAME" --title "$PR_TITLE" --notes "$PR_BODY") 58 | RELEASE_URL=$(echo "$RELEASE_OUTPUT" | grep -oP 'https://github.com/[^ ]+/releases/tag/[^ ]+') 59 | echo "Release URL: $RELEASE_URL" 60 | UPLOAD_URL=$(gh release view "$TAG_NAME" --json uploadUrl --jq '.uploadUrl') 61 | echo "UPLOAD_URL: $UPLOAD_URL" 62 | echo "UPLOAD_URL=$UPLOAD_URL" >> $GITHUB_ENV 63 | fi 64 | 65 | - name: Install PHP dependencies 66 | run: composer install --prefer-dist 67 | 68 | - name: Generate .env file in tests directory from GitHub secrets 69 | run: | 70 | echo "PROJECT_ID=${{ secrets.PROJECT_ID }}" > tests/.env 71 | echo "CLIENT_ID=${{ secrets.CLIENT_ID }}" >> tests/.env 72 | echo "CLIENT_SECRET=${{ secrets.CLIENT_SECRET }}" >> tests/.env 73 | 74 | - name: Run unit tests 75 | run: XDEBUG_MODE=coverage vendor/bin/phpunit --testdox --coverage-text 76 | 77 | - name: Create spectrocoin.zip (excluding tests directory and phpunit.xml) 78 | if: ${{ env.TAG_EXISTS == 'false' }} 79 | run: | 80 | mkdir spectrocoin-accepting-bitcoin # Create folder for release package 81 | # Copy only necessary files, excluding unwanted ones 82 | find . -maxdepth 1 \ 83 | -not -path './spectrocoin-accepting-bitcoin' \ 84 | -not -path '.' \ 85 | -not -path './.git' \ 86 | -not -path './.github' \ 87 | -not -path './README.txt' \ 88 | -not -path './README.md' \ 89 | -not -path './changelog.md' \ 90 | -not -path './phpunit.xml' \ 91 | -not -path './.gitignore' \ 92 | -not -path './tests' \ 93 | -exec cp -r {} spectrocoin-accepting-bitcoin/ \; 94 | zip -r spectrocoin.zip spectrocoin-accepting-bitcoin # Create zip file 95 | shell: bash 96 | 97 | - name: Upload spectrocoin.zip as release asset 98 | if: ${{ env.TAG_EXISTS == 'false' }} 99 | uses: actions/upload-release-asset@v1 100 | env: 101 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 102 | with: 103 | upload_url: ${{ env.UPLOAD_URL }} 104 | asset_path: spectrocoin.zip 105 | asset_name: spectrocoin.zip 106 | asset_content_type: application/zip 107 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .vscode/launch.json 2 | /vendor 3 | .phpunit.result.cache 4 | /.phpunit.cache 5 | /coverage-html 6 | /coverage-report 7 | .env -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | {description} 294 | Copyright (C) {year} {fullname} 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | {signature of Ty Coon}, 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | 341 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SpectroCoin Wordpress Crypto Payment Plugin 2 | 3 | Integrate cryptocurrency payments seamlessly into your Wordpress store with the [SpectroCoin Crypto Payment Plugin](https://spectrocoin.com/plugins/accept-bitcoin-wordpress-woocommerce.html). This extension facilitates the acceptance of a variety of cryptocurrencies, enhancing payment options for your customers. Easily configure and implement secure transactions for a streamlined payment process on your Wordpress website. 4 | 5 | ## Installation 6 | 7 | We strongly recommend downloading the plugin from [Wordpress](https://wordpress.org/plugins/spectrocoin-accepting-bitcoin/). In case you are downloading it from github, please follow the installation steps below.
8 | 1. Download latest release from github. 9 | 2. Extract and upload plugin folder to your Wordpress _/wp-content/plugins/_ directory.
10 | OR
11 | From Wordpress admin dashboard navigate tp **Plugins** -> **Add New** -> **Upload Plugin**. -> Upload _spectrocoin.zip<_.
12 | 3. Go to **Plugins** -> **Installed Plugins** -> Locate installed plugin and click **Activate** -> **Settings**. 13 | 14 | ## Setting up 15 | 16 | 1. **[Sign up](https://auth.spectrocoin.com/signup)** for a SpectroCoin Account. 17 | 2. **[Log in](https://auth.spectrocoin.com/login)** to your SpectroCoin account. 18 | 3. On the dashboard, locate the **[Business](https://spectrocoin.com/en/merchants/projects)** tab and click on it. 19 | 4. Click on **[New project](https://spectrocoin.com/en/merchants/projects/new)**. 20 | 5. Fill in the project details and select desired settings (settings can be changed). 21 | 6. Click **"Submit"**. 22 | 7. Copy and paste the "Project id". 23 | 8. Click on the user icon in the top right and navigate to **[Settings](https://test.spectrocoin.com/en/settings/)**. Then click on **[API](https://test.spectrocoin.com/en/settings/api)** and choose **[Create New API](https://test.spectrocoin.com/en/settings/api/create)**. 24 | 9. Add "API name", in scope groups select **"View merchant preorders"**, **"Create merchant preorders"**, **"View merchant orders"**, **"Create merchant orders"**, **"Cancel merchant orders"** and click **"Create API"**. 25 | 10. Copy and store "Client id" and "Client secret". Save the settings. 26 | 27 | **Note:** Keep in mind that if you want to use the business services of SpectroCoin, your account has to be verified. 28 | 29 | ## Test order creation on localhost 30 | 31 | We gently suggest trying out the plugin in a server environment, as it will not be capable of receiving callbacks from SpectroCoin if it will be hosted on localhost. To successfully create an order on localhost for testing purposes, change these 3 lines in CreateOrderRequest.php: 32 | ```php 33 | $this->callbackUrl = isset($data['callbackUrl']) ? Utils::sanitizeUrl($data['callbackUrl']) : null; 34 | $this->successUrl = isset($data['successUrl']) ? Utils::sanitizeUrl($data['successUrl']) : null; 35 | $this->failureUrl = isset($data['failureUrl']) ? Utils::sanitizeUrl($data['failureUrl']) : null; 36 | ``` 37 | __To__ 38 | ```php 39 | $this->callbackUrl = "https://localhost.com/"; 40 | $this->successUrl = "https://localhost.com/"; 41 | $this->failureUrl = "https://localhost.com/"; 42 | ``` 43 | Don't forget to change it back when migrating website to public. 44 | 45 | ## Testing Callbacks 46 | 47 | Order callbacks in the SpectroCoin plugin allow your WordPress site to automatically process order status changes sent from SpectroCoin. These callbacks notify your server when an order’s status transitions to PAID, EXPIRED, or FAILED. Understanding and testing this functionality ensures your store handles payments accurately and updates order statuses accordingly. 48 | 49 | 1. Go to your SpectroCoin project settings and enable **Test Mode**. 50 | 2. Simulate a payment status: 51 | - **PAID**: Sends a callback to mark the order as **Completed** in WordPress. 52 | - **EXPIRED**: Sends a callback to mark the order as **Failed** in WordPress. 53 | 3. Ensure your `callbackUrl` is publicly accessible (local servers like `localhost` will not work). 54 | 4. Check the **Order History** in SpectroCoin for callback details. If a callback fails, use the **Retry** button to resend it. 55 | 5. Verify that: 56 | - The **order status** in WordPress has been updated accordingly. 57 | - The **callback status** in the SpectroCoin dashboard is `200 OK`. 58 | 59 | ## Debugging 60 | 61 | If you get "Something went wrong. Please contact us to get assistance." message during checkout process, please navigate to **"WooCommerce"** -> **"Status"** -> **"Logs"** and check **"plugin-spectrocoin"** log file for more information. If the logs are not helpful or not displayed, please contact us and provide the log file details so that we can assist. 62 | 63 | ## Contact 64 | 65 | This client has been developed by SpectroCoin.com If you need any further support regarding our services you can contact us via: 66 | 67 | E-mail: merchant@spectrocoin.com
68 | Skype: [spectrocoin_merchant](https://join.skype.com/invite/iyXHU7o08KkW)
69 | [Web](https://spectrocoin.com)
70 | [X (formerly Twitter)](https://twitter.com/spectrocoin)
71 | [Facebook](https://www.facebook.com/spectrocoin/) 72 | -------------------------------------------------------------------------------- /README.txt: -------------------------------------------------------------------------------- 1 | 2 | === SpectroCoin Payment Extension for WooCommerce === 3 | Contributors: spectrocoin 4 | Donate link: https://spectrocoin.com/en/ 5 | Tags: woocommerce bitcoin plugin, crypto payments, accept cryptocurrencies, bitcoin payment gateway, spectrocoin payment gateway 6 | Requires at least: 6.2 7 | Tested up to: 6.7.2 8 | Stable tag: 2.0.1 9 | WC requires at least: 7.4 10 | WC tested up to: 9.6.2 11 | License: GPLv2 or later 12 | License URI: http://www.gnu.org/licenses/gpl-2.0.html 13 | 14 | SpectroCoin Payments for WooCommerce is a Wordpress plugin that allows to accept cryptocurrencies at WooCommerce-powered online stores. 15 | 16 | == Description == 17 | 18 | Welcome to the world of seamless cryptocurrency transactions on your WooCommerce site! With SpectroCoin's innovative WordPress payment plugin, you can now accept a wide range of cryptocurrencies, including BTC, ETH, USDT, and over 25 other popular digital assets, right on your online store. 19 | 20 | Why is this the perfect solution for WooCommerce users? If you are already using WooCommerce, integrating our plugin is the recommended method for venturing into the world of crypto payments. It opens up a whole new realm of possibilities, allowing customers to make secure and hassle-free purchases on your site. 21 | 22 | Plugin is now compatible with the new block-based cart, checkout, and order confirmation functionality introduced in WooCommerce 8.3. 23 | 24 | == Benefits == 25 | 26 | 1. Accept Multiple Cryptocurrencies: Easily add BTC, ETH, USDT, and 25+ other cryptocurrencies to your WooCommerce site. 27 | 2. Seamlessly integrate the plugin into your existing WooCommerce store without any hassle. 28 | 3. Attract customers from around the world with secure crypto payment options. 29 | 4. Avoid price volatility by settling payments in EUR, USD, GBP, or 20+ supported fiat currencies. 30 | 5. Ensure safe and secure crypto transactions for you and your customers. 31 | 6. Offer a wide range of payment methods to appeal to tech-savvy customers. 32 | 7. Embrace the growing trend of crypto payments, building trust among your audience. 33 | 8. Receive prompt assistance from SpectroCoin's exceptional customer support team. 34 | 35 | == Installation == 36 | 37 | 1. Install WooCommerce plugin and configure your store (if you haven't done so already - http://wordpress.org/plugins/woocommerce/). 38 | 39 | 2. Download SpectroCoin plugin or upload SpectroCoin plugin directory to the `/wp-content/plugins/` directory. 40 | 41 | 3. From Wordpress admin dashboard, navigate to **Plugins** -> **Add New** -> **Upload Plugin**. -> Upload the `spectrocoin.zip` file. 42 | 43 | 4. Activate the plugin through the WordPress dashboard -> Plugins -> Activate. 44 | When page reloads click on "Settings". 45 | 46 | 5. Enter your Client ID, Client Secret, and Project ID (see How to get API credentials below). 47 | 48 | == How to get API credentials == 49 | 50 | 1. **Sign up** for a SpectroCoin Account. 51 | 52 | 2. **Log in** to your SpectroCoin account. 53 | 54 | 3. On the dashboard, locate the **Business** tab and click on it. 55 | 56 | 4. Click on **New project** and fill in the project details. 57 | 58 | 5. Submit the project and copy the "Project ID". 59 | 60 | 6. Navigate to **Settings** -> **API** and create a new API by providing an API name. Select the following scope groups: 61 | - "View merchant preorders" 62 | - "Create merchant preorders" 63 | - "View merchant orders" 64 | - "Create merchant orders" 65 | - "Cancel merchant orders" 66 | 67 | 7. Copy and store the Client ID and Client Secret securely. 68 | 69 | == Testing & Callbacks == 70 | 71 | Order callbacks notify your server when an order’s status transitions to PAID, EXPIRED, or FAILED. 72 | 73 | 1. Enable **Test Mode** in your SpectroCoin project settings. 74 | 75 | 2. Simulate payment statuses: 76 | - **PAID**: Updates the order as **Completed**. 77 | - **EXPIRED**: Updates the order as **Failed**. 78 | 79 | 3. Ensure your `callbackUrl` is publicly accessible (local servers like `localhost` will not work). 80 | 81 | 4. Check the **Order History** and callback logs on SpectroCoin to verify callback success. 82 | 83 | == Debugging == 84 | 85 | For troubleshooting, navigate to **WooCommerce** -> **Status** -> **Logs** and check the **plugin-spectrocoin** log file. If additional support is needed, contact SpectroCoin and provide the log details. 86 | 87 | == Screenshots == 88 | 89 | 1. Plugin settings page. 90 | 2. SpectroCoin checkout option. 91 | 3. Plugin settings window. 92 | 4. Payment window example. 93 | 94 | == Remove plugin == 95 | 96 | 1. Navigate to WordPress dashboard -> Plugins -> Installed Plugins. 97 | 2. Search for SpectroCoin plugin and click "Deactivate". 98 | 3. Click "Delete". 99 | 100 | == Changelog == 101 | 102 | ### 2.0.0 (11/02/2025) 103 | - Major update with new OAuth authentication using Client ID and Client Secret. 104 | - Deprecated private key and merchant ID methods. 105 | - Improved API endpoints for performance and security. 106 | - Adherence to PSR-12 coding standards and enhanced plugin stability. 107 | 108 | == Contact == 109 | 110 | For support, contact us via: 111 | E-mail: merchant@spectrocoin.com 112 | Skype: [spectrocoin_merchant](https://join.skype.com/invite/iyXHU7o08KkW) 113 | [Web](https://spectrocoin.com) 114 | [X (formerly Twitter)](https://twitter.com/spectrocoin) 115 | [Facebook](https://www.facebook.com/spectrocoin/) 116 | -------------------------------------------------------------------------------- /SCMerchantClient/Config.php: -------------------------------------------------------------------------------- 1 | orderId = isset($data['orderId']) ? Utils::sanitize_text_field((string)$data['orderId']) : null; 34 | $this->description = isset($data['description']) ? Utils::sanitize_text_field((string)$data['description']) : null; 35 | $this->receiveAmount = isset($data['receiveAmount']) ? Utils::sanitize_text_field((string)$data['receiveAmount']) : null; 36 | $this->receiveCurrencyCode = isset($data['receiveCurrencyCode']) ? Utils::sanitize_text_field((string)$data['receiveCurrencyCode']) : null; 37 | $this->callbackUrl = isset($data['callbackUrl']) ? Utils::sanitizeUrl($data['callbackUrl']) : null; 38 | $this->successUrl = isset($data['successUrl']) ? Utils::sanitizeUrl($data['successUrl']) : null; 39 | $this->failureUrl = isset($data['failureUrl']) ? Utils::sanitizeUrl($data['failureUrl']) : null; 40 | 41 | $validation = $this->validate(); 42 | if (is_array($validation)) { 43 | $errorMessage = 'Invalid order creation payload. Failed fields: ' . implode(', ', $validation); 44 | throw new InvalidArgumentException($errorMessage); 45 | } 46 | } 47 | 48 | /** 49 | * Data validation for create order API request. 50 | * 51 | * @return bool|array True if validation passes, otherwise an array of error messages. 52 | */ 53 | private function validate(): bool|array 54 | { 55 | $errors = []; 56 | 57 | if (empty($this->getOrderId())) { 58 | $errors[] = 'orderId is required'; 59 | } 60 | if (empty($this->getDescription())) { 61 | $errors[] = 'description is required'; 62 | } 63 | if ($this->getReceiveAmount() === null || (float)$this->getReceiveAmount() <= 0) { 64 | $errors[] = 'receiveAmount must be greater than zero'; 65 | } 66 | if (empty($this->getReceiveCurrencyCode()) || strlen($this->getReceiveCurrencyCode()) !== 3) { 67 | $errors[] = 'receiveCurrencyCode must be 3 characters long'; 68 | } 69 | 70 | $urlFields = [ 71 | 'callbackUrl' => $this->getCallbackUrl(), 72 | 'successUrl' => $this->getSuccessUrl(), 73 | 'failureUrl' => $this->getFailureUrl(), 74 | ]; 75 | 76 | foreach ($urlFields as $fieldName => $url) { 77 | if (empty($url) || !filter_var($url, FILTER_VALIDATE_URL)) { 78 | $errors[] = "invalid $fieldName"; 79 | } else { 80 | $host = parse_url($url, PHP_URL_HOST); 81 | if ($host === false || strpos($host, '.') === false) { 82 | $errors[] = "invalid $fieldName"; 83 | } else { 84 | $hostParts = explode('.', $host); 85 | $tld = array_pop($hostParts); 86 | if (strlen($tld) < 2) { 87 | $errors[] = "invalid $fieldName"; 88 | } 89 | } 90 | } 91 | } 92 | 93 | return empty($errors) ? true : $errors; 94 | } 95 | 96 | /** 97 | * Convert CreateOrderRequest object to array. 98 | * 99 | * @return array 100 | */ 101 | public function toArray(): array 102 | { 103 | return [ 104 | 'orderId' => $this->getOrderId(), 105 | 'description' => $this->getDescription(), 106 | 'receiveAmount' => $this->getReceiveAmount(), 107 | 'receiveCurrencyCode' => $this->getReceiveCurrencyCode(), 108 | 'callbackUrl' => $this->getCallbackUrl(), 109 | 'successUrl' => $this->getSuccessUrl(), 110 | 'failureUrl' => $this->getFailureUrl() 111 | ]; 112 | } 113 | 114 | public function getOrderId() 115 | { 116 | return $this->orderId; 117 | } 118 | public function getDescription() 119 | { 120 | return $this->description; 121 | } 122 | public function getReceiveAmount() 123 | { 124 | return Utils::formatCurrency((float)$this->receiveAmount); 125 | } 126 | public function getReceiveCurrencyCode() 127 | { 128 | return $this->receiveCurrencyCode; 129 | } 130 | public function getCallbackUrl() 131 | { 132 | return $this->callbackUrl; 133 | } 134 | public function getSuccessUrl() 135 | { 136 | return $this->successUrl; 137 | } 138 | public function getFailureUrl() 139 | { 140 | return $this->failureUrl; 141 | } 142 | } 143 | -------------------------------------------------------------------------------- /SCMerchantClient/Http/CreateOrderResponse.php: -------------------------------------------------------------------------------- 1 | preOrderId = isset($data['preOrderId']) ? Utils::sanitize_text_field((string)$data['preOrderId']) : null; 36 | $this->orderId = isset($data['orderId']) ? Utils::sanitize_text_field((string)$data['orderId']) : null; 37 | $this->validUntil = isset($data['validUntil']) ? Utils::sanitize_text_field((string)$data['validUntil']) : null; 38 | $this->payCurrencyCode = isset($data['payCurrencyCode']) ? Utils::sanitize_text_field((string)$data['payCurrencyCode']) : null; 39 | $this->payNetworkCode = isset($data['payNetworkCode']) ? Utils::sanitize_text_field((string)$data['payNetworkCode']) : null; 40 | $this->receiveCurrencyCode = isset($data['receiveCurrencyCode']) ? Utils::sanitize_text_field((string)$data['receiveCurrencyCode']) : null; 41 | $this->payAmount = isset($data['payAmount']) ? Utils::sanitize_text_field((string)$data['payAmount']) : null; 42 | $this->receiveAmount = isset($data['receiveAmount']) ? Utils::sanitize_text_field((string)$data['receiveAmount']) : null; 43 | $this->depositAddress = isset($data['depositAddress']) ? Utils::sanitize_text_field((string)$data['depositAddress']) : null; 44 | $this->memo = isset($data['memo']) ? Utils::sanitize_text_field((string)$data['memo']) : null; 45 | $this->redirectUrl = isset($data['redirectUrl']) ? Utils::sanitizeUrl($data['redirectUrl']) : null; 46 | 47 | $validation = $this->validate(); 48 | if (is_array($validation)) { 49 | $errorMessage = 'Invalid order creation payload. Failed fields: ' . implode(', ', $validation); 50 | throw new InvalidArgumentException($errorMessage); 51 | } 52 | } 53 | 54 | /** 55 | * Validate the data for create order API response. 56 | * 57 | * @return bool|array True if validation passes, otherwise an array of error messages. 58 | */ 59 | public function validate(): bool|array 60 | { 61 | $errors = []; 62 | 63 | if (empty($this->getPreOrderId())) { 64 | $errors[] = 'preOrderId is empty'; 65 | } 66 | if (empty($this->getOrderId())) { 67 | $errors[] = 'orderId is empty'; 68 | } 69 | if (strlen($this->getReceiveCurrencyCode()) !== 3) { 70 | $errors[] = 'receiveCurrencyCode is not 3 characters long'; 71 | } 72 | if ($this->getReceiveAmount() === null || (float)$this->getReceiveAmount() <= 0) { 73 | $errors[] = 'receiveAmount is not a valid positive number'; 74 | } 75 | if (empty($this->getRedirectUrl()) || !filter_var($this->getRedirectUrl(), FILTER_VALIDATE_URL)) { 76 | $errors[] = "invalid redirectUrl"; 77 | } else { 78 | $host = parse_url($this->getRedirectUrl(), PHP_URL_HOST); 79 | if ($host === false || strpos($host, '.') === false) { 80 | $errors[] = "invalid redirectUrl"; 81 | } else { 82 | $hostParts = explode('.', $host); 83 | $tld = array_pop($hostParts); 84 | if (strlen($tld) < 2) { 85 | $errors[] = "invalid redirectUrl"; 86 | } 87 | } 88 | } 89 | 90 | return empty($errors) ? true : $errors; 91 | } 92 | 93 | public function getPreOrderId() 94 | { 95 | return $this->preOrderId; 96 | } 97 | public function getOrderId() 98 | { 99 | return $this->orderId; 100 | } 101 | public function getValidUntil() 102 | { 103 | return $this->validUntil; 104 | } 105 | public function getPayCurrencyCode() 106 | { 107 | return $this->payCurrencyCode; 108 | } 109 | public function getPayNetworkCode() 110 | { 111 | return $this->payNetworkCode; 112 | } 113 | public function getReceiveCurrencyCode() 114 | { 115 | return $this->receiveCurrencyCode; 116 | } 117 | public function getPayAmount() 118 | { 119 | return $this->payAmount; 120 | } 121 | public function getReceiveAmount() 122 | { 123 | return $this->receiveAmount; 124 | } 125 | public function getDepositAddress() 126 | { 127 | return $this->depositAddress; 128 | } 129 | public function getMemo() 130 | { 131 | return $this->memo; 132 | } 133 | public function getRedirectUrl() 134 | { 135 | return $this->redirectUrl; 136 | } 137 | } 138 | -------------------------------------------------------------------------------- /SCMerchantClient/Http/OrderCallback.php: -------------------------------------------------------------------------------- 1 | userId = isset($data['userId']) ? Utils::sanitize_text_field((string)$data['userId']) : null; 44 | $this->merchantApiId = isset($data['merchantApiId']) ? Utils::sanitize_text_field((string)$data['merchantApiId']) : null; 45 | $this->merchantId = isset($data['merchantId']) ? Utils::sanitize_text_field((string)$data['merchantId']) : null; 46 | $this->apiId = isset($data['apiId']) ? Utils::sanitize_text_field((string)$data['apiId']) : null; 47 | $this->orderId = isset($data['orderId']) ? Utils::sanitize_text_field((string)$data['orderId']) : null; 48 | $this->payCurrency = isset($data['payCurrency']) ? Utils::sanitize_text_field((string)$data['payCurrency']) : null; 49 | $this->payAmount = isset($data['payAmount']) ? Utils::sanitize_text_field((string)$data['payAmount']) : null; 50 | $this->receiveCurrency = isset($data['receiveCurrency']) ? Utils::sanitize_text_field((string)$data['receiveCurrency']) : null; 51 | $this->receiveAmount = isset($data['receiveAmount']) ? Utils::sanitize_text_field((string)$data['receiveAmount']) : null; 52 | $this->receivedAmount = isset($data['receivedAmount']) ? Utils::sanitize_text_field((string)$data['receivedAmount']) : null; 53 | $this->description = isset($data['description']) ? Utils::sanitize_text_field((string)$data['description']) : null; 54 | $this->orderRequestId = isset($data['orderRequestId']) ? Utils::sanitize_text_field((string)$data['orderRequestId']) : null; 55 | $this->status = isset($data['status']) ? Utils::sanitize_text_field((string)$data['status']) : null; 56 | $this->sign = isset($data['sign']) ? Utils::sanitize_text_field((string)$data['sign']) : null; 57 | $this->publicCertPath = $publicCertPath ?? Config::PUBLIC_SPECTROCOIN_CERT_LOCATION; 58 | 59 | $validation_result = $this->validate(); 60 | if (is_array($validation_result)) { 61 | $errorMessage = 'Invalid order callback payload. Failed fields: ' . implode(', ', $validation_result); 62 | throw new InvalidArgumentException($errorMessage); 63 | } 64 | 65 | if (!$this->validatePayloadSignature()) { // IŠTESTUOJAMUMAS SUNKĖJA, REIKIA KEISTI 66 | throw new Exception('Invalid payload signature.'); 67 | } 68 | } 69 | 70 | /** 71 | * Validate the input data. 72 | * 73 | * @return bool|array True if validation passes, otherwise an array of error messages. 74 | */ 75 | private function validate(): bool|array 76 | { 77 | $errors = []; 78 | 79 | if (empty($this->getUserId())) { 80 | $errors[] = 'userId is empty'; 81 | } 82 | if (empty($this->getMerchantApiId())) { 83 | $errors[] = 'merchantApiId is empty'; 84 | } 85 | if (empty($this->getMerchantId())) { 86 | $errors[] = 'merchantId is empty'; 87 | } 88 | if (empty($this->getApiId())) { 89 | $errors[] = 'apiId is empty'; 90 | } 91 | if (empty($this->getOrderId())) { 92 | $errors[] = 'orderId is empty'; 93 | } 94 | if (empty($this->getStatus())){ 95 | $errors[] = 'status is empty'; 96 | } 97 | if (strlen($this->getPayCurrency()) !== 3) { 98 | $errors[] = 'payCurrency is not 3 characters long'; 99 | } 100 | if (!is_numeric($this->getPayAmount()) || (float)$this->getPayAmount() <= 0) { 101 | $errors[] = 'payAmount is not a valid positive number'; 102 | } 103 | if (strlen($this->getReceiveCurrency()) !== 3) { 104 | $errors[] = 'receiveCurrency is not 3 characters long'; 105 | } 106 | if (!is_numeric($this->getReceiveAmount()) || (float)$this->getReceiveAmount() <= 0) { 107 | $errors[] = 'receiveAmount is not a valid positive number'; 108 | } 109 | if (!isset($this->receivedAmount)) { 110 | $errors[] = 'receivedAmount is not set'; 111 | } 112 | if (!is_numeric($this->getOrderRequestId()) || (float)$this->getOrderRequestId() <= 0) { 113 | $errors[] = 'orderRequestId is not a valid positive number'; 114 | } 115 | 116 | return empty($errors) ? true : $errors; 117 | } 118 | 119 | /** 120 | * Validate the payload signature. 121 | * 122 | * @return bool True if the signature is valid, otherwise false. 123 | */ 124 | public function validatePayloadSignature(): bool 125 | { 126 | $payload = [ 127 | 'merchantId' => $this->getMerchantId(), 128 | 'apiId' => $this->getApiId(), 129 | 'orderId' => $this->getOrderId(), 130 | 'payCurrency' => $this->getPayCurrency(), 131 | 'payAmount' => $this->getPayAmount(), 132 | 'receiveCurrency' => $this->getReceiveCurrency(), 133 | 'receiveAmount' => $this->getReceiveAmount(), 134 | 'receivedAmount' => $this->getReceivedAmount(), 135 | 'description' => $this->getDescription(), 136 | 'orderRequestId' => $this->getOrderRequestId(), 137 | 'status' => $this->getStatus(), 138 | ]; 139 | $data = http_build_query($payload); 140 | $decoded_signature = base64_decode($this->sign); 141 | $public_key = file_get_contents($this->publicCertPath); 142 | $public_key_pem = openssl_pkey_get_public($public_key); 143 | return openssl_verify($data, $decoded_signature, $public_key_pem, OPENSSL_ALGO_SHA1) === 1; 144 | } 145 | 146 | public function getUserId() { return $this->userId; } 147 | public function getMerchantApiId() { return $this->merchantApiId; } 148 | public function getMerchantId() { return $this->merchantId; } 149 | public function getApiId() { return $this->apiId; } 150 | public function getOrderId() { return $this->orderId; } 151 | public function getPayCurrency() { return $this->payCurrency; } 152 | public function getPayAmount() { return Utils::formatCurrency($this->payAmount); } 153 | public function getReceiveCurrency() { return $this->receiveCurrency; } 154 | public function getReceiveAmount() { return Utils::formatCurrency($this->receiveAmount); } 155 | public function getReceivedAmount() { return Utils::formatCurrency($this->receivedAmount); } 156 | public function getDescription() { return $this->description; } 157 | public function getOrderRequestId() { return $this->orderRequestId; } 158 | public function getStatus() { return $this->status; } 159 | public function getSign() { return $this->sign; } 160 | } 161 | ?> 162 | -------------------------------------------------------------------------------- /SCMerchantClient/SCMerchantClient.php: -------------------------------------------------------------------------------- 1 | project_id = $project_id; 48 | $this->client_id = $client_id; 49 | $this->client_secret = $client_secret; 50 | 51 | $this->http_client = new Client(); 52 | } 53 | 54 | /** 55 | * Creates a new order. 56 | * 57 | * This method builds an order payload using the provided order data and the project identifier, 58 | * then sends a POST request to the merchant API to create the order. It handles JSON encoding, 59 | * response decoding, and error handling. Depending on the outcome, it returns a CreateOrderResponse, 60 | * an ApiError, or a GenericError. 61 | * 62 | * @param array $order_data The data required for creating the order. 63 | * @param array $access_token_data The access token data (must include the 'access_token' key) used for authorization. 64 | * 65 | * @return CreateOrderResponse|ApiError|GenericError|null The response object containing order details or an error object if an error occurs. 66 | */ 67 | public function createOrder(array $order_data, array $access_token_data) 68 | { 69 | try { 70 | $create_order_request = new CreateOrderRequest($order_data); 71 | } catch (InvalidArgumentException $e) { 72 | return new GenericError($e->getMessage(), $e->getCode()); 73 | } 74 | 75 | $order_payload = $create_order_request->toArray(); 76 | $order_payload['projectId'] = $this->project_id; 77 | 78 | try { 79 | $response = $this->http_client->request('POST', Config::MERCHANT_API_URL . '/merchants/orders/create', [ 80 | RequestOptions::HEADERS => [ 81 | 'Authorization' => 'Bearer ' . $access_token_data['access_token'], 82 | 'Content-Type' => 'application/json' 83 | ], 84 | RequestOptions::BODY => json_encode($order_payload) 85 | ]); 86 | 87 | $body = json_decode($response->getBody()->getContents(), true); 88 | 89 | if (json_last_error() !== JSON_ERROR_NONE) { 90 | throw new RuntimeException('Failed to parse JSON response: ' . json_last_error_msg()); 91 | } 92 | 93 | $responseData = [ 94 | 'preOrderId' => $body['preOrderId'] ?? null, 95 | 'orderId' => $body['orderId'] ?? null, 96 | 'validUntil' => $body['validUntil'] ?? null, 97 | 'payCurrencyCode' => $body['payCurrencyCode'] ?? null, 98 | 'payNetworkCode' => $body['payNetworkCode'] ?? null, 99 | 'receiveCurrencyCode' => $body['receiveCurrencyCode'] ?? null, 100 | 'payAmount' => $body['payAmount'] ?? null, 101 | 'receiveAmount' => $body['receiveAmount'] ?? null, 102 | 'depositAddress' => $body['depositAddress'] ?? null, 103 | 'memo' => $body['memo'] ?? null, 104 | 'redirectUrl' => $body['redirectUrl'] ?? null 105 | ]; 106 | 107 | return new CreateOrderResponse($responseData); 108 | } catch (InvalidArgumentException $e) { 109 | return new GenericError($e->getMessage(), $e->getCode()); 110 | } catch (RequestException $e) { 111 | return new ApiError($e->getMessage(), $e->getCode()); 112 | } catch (Exception $e) { 113 | return new GenericError($e->getMessage(), $e->getCode()); 114 | } 115 | } 116 | 117 | /** 118 | * Retrieves the current access token data. 119 | * 120 | * This method performs a POST request to the authentication endpoint using the client credentials. 121 | * It decodes the JSON response to extract the access token and expiration information. If the response 122 | * is invalid or an error occurs, an ApiError is returned. 123 | * 124 | * @return array|ApiError|null An associative array containing the access token and expiration info if successful, 125 | * or an ApiError object if the request fails. 126 | */ 127 | public function getAccessToken() 128 | { 129 | try { 130 | $response = $this->http_client->post(Config::AUTH_URL, [ 131 | 'form_params' => [ 132 | 'grant_type' => 'client_credentials', 133 | 'client_id' => $this->client_id, 134 | 'client_secret' => $this->client_secret, 135 | ], 136 | ]); 137 | 138 | $access_token_data = json_decode((string) $response->getBody(), true); 139 | 140 | if (!isset($access_token_data['access_token'], $access_token_data['expires_in'])) { 141 | return new ApiError('Invalid access token response'); 142 | } 143 | return $access_token_data; 144 | } 145 | catch (RequestException $e) { 146 | return new ApiError($e->getMessage(), $e->getCode()); 147 | } 148 | } 149 | 150 | /** 151 | * Checks if the current access token is valid. 152 | * 153 | * This method determines whether the provided access token has expired by checking if an 'expires_at' 154 | * timestamp exists and comparing it with the current time. 155 | * 156 | * @param array $access_token_data An associative array containing access token details, including 'expires_at'. 157 | * @param int $current_time The current time as a Unix timestamp. 158 | * 159 | * @return bool True if the token is valid (i.e., the current time is less than the 'expires_at' timestamp), false otherwise. 160 | */ 161 | public function isTokenValid(array $access_token_data, int $current_time): bool 162 | { 163 | return isset($access_token_data['expires_at']) && $current_time < $access_token_data['expires_at']; 164 | } 165 | } 166 | -------------------------------------------------------------------------------- /SCMerchantClient/Utils.php: -------------------------------------------------------------------------------- 1 | ^]/', '', $value); 81 | 82 | return $value; 83 | } 84 | 85 | 86 | 87 | /** 88 | * Generate random string 89 | * @param int $length 90 | * @return string 91 | */ 92 | public static function generateRandomStr($length) : string 93 | { 94 | if (!is_int($length) || $length < 0) { 95 | throw new \InvalidArgumentException("Invalid length parameter. Must be a non-negative integer."); 96 | } 97 | 98 | // If length is 0, return an empty string. 99 | if ($length === 0) { 100 | return ""; 101 | } 102 | 103 | $random_str = substr(md5((string)rand(1, pow(2, 16))), 0, $length); 104 | return $random_str; 105 | } 106 | 107 | /** 108 | * 1. Checks for invalid UTF-8 characters. 109 | * 2. Converts single less-than characters (<) to entities. 110 | * 3. Strips all HTML and PHP tags. 111 | * 4. Removes line breaks, tabs, and extra whitespace. 112 | * 5. Strips percent-encoded characters. 113 | * 6. Removes any remaining invalid UTF-8 characters. 114 | * 115 | * @param string $str The text to be sanitized. 116 | * @return string The sanitized text. 117 | */ 118 | public static function sanitize_text_field(string $str): string { 119 | $str = mb_check_encoding($str, 'UTF-8') ? $str : ''; 120 | $str = preg_replace('/<(?=[^a-zA-Z\/\?\!\%])/u', '<', $str); 121 | $str = strip_tags($str); 122 | $str = preg_replace('/[\r\n\t ]+/', ' ', $str); 123 | $str = trim($str); 124 | $str = preg_replace('/%[a-f0-9]{2}/i', '', $str); 125 | $str = preg_replace('/[^\x20-\x7E]/', '', $str); 126 | return $str; 127 | } 128 | 129 | } 130 | ?> 131 | -------------------------------------------------------------------------------- /assets/images/card_phone_top.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /assets/images/spectrocoin-logo.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /assets/js/block-checkout.js: -------------------------------------------------------------------------------- 1 | const settings = window.wc.wcSettings.getSetting("spectrocoin_data", {}); 2 | const label = 3 | window.wp.htmlEntities.decodeEntities(settings.title) || 4 | window.wp.i18n.__("SpectroCoin", "spectrocoin-accepting-bitcoin"); 5 | const Content = () => { 6 | return window.wp.element.createElement( 7 | "div", 8 | {}, 9 | settings.checkout_icon && 10 | window.wp.element.createElement("img", { 11 | src: settings.checkout_icon, 12 | alt: window.wp.i18n.__( 13 | "SpectroCoin Logo", 14 | "spectrocoin-accepting-bitcoin" 15 | ), 16 | style: { marginBottom: "10px" }, 17 | }), 18 | window.wp.element.createElement( 19 | "div", 20 | {}, 21 | window.wp.htmlEntities.decodeEntities(settings.description || "") 22 | ) 23 | ); 24 | } 25 | 26 | const SpectroCoinBlockGateway = { 27 | name: "spectrocoin", 28 | label: label, 29 | content: Object(window.wp.element.createElement)(Content, null), 30 | edit: Object(window.wp.element.createElement)(Content, null), 31 | canMakePayment: () => true, 32 | ariaLabel: label, 33 | supports: { 34 | features: ["products"], // Update based on your gateway's supported features 35 | }, 36 | }; 37 | 38 | window.wc.wcBlocksRegistry.registerPaymentMethod(SpectroCoinBlockGateway); 39 | -------------------------------------------------------------------------------- /assets/style/settings.css: -------------------------------------------------------------------------------- 1 | .spectrocoin-plugin-settings { 2 | display: flex; 3 | gap: 15px; 4 | } 5 | 6 | .header { 7 | display: flex; 8 | max-height: 130px; 9 | } 10 | 11 | .header-flex { 12 | flex-basis: 50%; 13 | } 14 | 15 | .header-flex .header-image { 16 | float: right; 17 | } 18 | 19 | .spectrocoin-plugin-settings .flex-col { 20 | flex-basis: 50%; 21 | } 22 | 23 | .spectrocoin-plugin-settings .flex-col-2 { 24 | display: flex; 25 | justify-content: center; 26 | align-items: center; 27 | flex-wrap: wrap; 28 | } 29 | 30 | .spectrocoin-plugin-settings h3 { 31 | font-family: Red Hat Text, sans-serif; 32 | color: #102d6f; 33 | font-size: 1.8rem; 34 | } 35 | 36 | .spectrocoin-plugin-settings h4 { 37 | font-family: Red Hat Text, sans-serif; 38 | color: #102d6f; 39 | font-size: 1.4rem; 40 | line-height: 26px; 41 | } 42 | 43 | .spectrocoin-plugin-settings h5 { 44 | font-family: Red Hat Text, sans-serif; 45 | color: #102d6f; 46 | font-size: 1.1rem; 47 | line-height: 26px; 48 | } 49 | 50 | .spectrocoin-plugin-settings .contact-information { 51 | color: #102d6f; 52 | font-size: 14px; 53 | font-weight: 400; 54 | line-height: 22px; 55 | font-family: Red Hat Text, sans-serif; 56 | } 57 | 58 | .woocommerce-save-button { 59 | align-items: center; 60 | background: #4972f4; 61 | border-radius: 4px; 62 | border: 2px solid #4972f4; 63 | color: #fff; 64 | cursor: pointer; 65 | display: inline-flex; 66 | font-size: 16px; 67 | font-weight: 500; 68 | justify-content: center; 69 | outline: none; 70 | padding: 3px 23px; 71 | text-decoration: none; 72 | transition: all 0.1s, visibility 0s; 73 | } 74 | 75 | .woocommerce-save-button:hover { 76 | background: #6c8bf5 !important; 77 | border-color: #6c8bf5 !important; 78 | color: #fff; 79 | } 80 | 81 | .spectrocoin-plugin-settings .input-text, 82 | .spectrocoin-plugin-settings .select { 83 | border: 1px solid #e6e8f0 !important; 84 | font-size: 14px; 85 | border-radius: 4px; 86 | outline: none; 87 | width: 80% !important; 88 | transition: all 0.1s, visibility 0s; 89 | } 90 | 91 | .white-card { 92 | background-color: #fff; 93 | border-radius: 8px; 94 | box-shadow: 0 6px 10px #4972f40d; 95 | padding: 20px 15px; 96 | flex-basis: 100%; 97 | } 98 | 99 | .form-table tr { 100 | display: flex; 101 | flex-wrap: wrap; 102 | margin-bottom: 10px; 103 | } 104 | 105 | .form-table label { 106 | width: 80% !important; 107 | } 108 | 109 | .form-table th, 110 | .form-table td { 111 | padding: 0px !important; 112 | flex-basis: 100%; 113 | } 114 | 115 | .woocommerce-help-tip::after, 116 | .woocommerce-product-type-tip::after { 117 | position: static !important; 118 | } 119 | 120 | .woocommerce table.form-table th label .woocommerce-help-tip { 121 | position: static !important; 122 | } 123 | 124 | @media only screen and (max-width: 960px) { 125 | .spectrocoin-plugin-settings { 126 | flex-wrap: wrap; 127 | } 128 | .spectrocoin-plugin-settings .flex-col { 129 | flex-basis: 100% !important; 130 | } 131 | .spectrocoin-plugin-settings .input-text, 132 | .spectrocoin-plugin-settings .select { 133 | width: 100% !important; 134 | } 135 | .white-card { 136 | margin-top: 0px; 137 | } 138 | } 139 | 140 | .spectrocoin-logo { 141 | height: 100%; 142 | width: 230px; 143 | } 144 | 145 | .logo-link { 146 | height: 100%; 147 | display: block; 148 | } 149 | 150 | .contact-information { 151 | padding-top: 30px; 152 | padding-bottom: 20px; 153 | width: 100%; 154 | } 155 | -------------------------------------------------------------------------------- /changelog.md: -------------------------------------------------------------------------------- 1 | ## Changelog 2 | 3 | ### 2.0.1 (28/03/2025) 4 | 5 | _Added_ Minor code improvements to the main SCMerchantClient 6 | 7 | _Added_ PHPUnit tests with 100% coverage of only SCMerchantClient directory files 8 | 9 | _Tested_ Compatibility with latest WooCommerce(9.6.2) and Wordpress(6.7.2) versions. 10 | 11 | ### 2.0.0 (11/02/2025) 12 | 13 | This major update introduces several improvements, including enhanced security, updated coding standards, and a streamlined integration process. **Important:** Users must generate new API credentials (Client ID and Client Secret) in their SpectroCoin account settings to continue using the plugin. The previous private key and merchant ID functionality have been deprecated. 14 | 15 | _Added_ Temporary admin notice (will removed in few months) which tells to update client API credentials. 16 | 17 | _Updated_ SCMerchantClient was reworked to adhere to better coding standards. 18 | 19 | _Updated_ Order creation API endpoint has been updated for enhanced performance and security. 20 | 21 | _Removed_ Private key functionality and merchant ID requirement have been removed to streamline integration. 22 | 23 | _Added_ OAuth functionality introduced for authentication, requiring Client ID and Client Secret for secure API access. 24 | 25 | _Fixed_ Changed save button class to prevent conflicts with other buttons. 26 | 27 | _Updated_ Class and some method names have been updated based on PSR-12 standards. 28 | 29 | _Updated_ Composer class autoloading has been implemented. 30 | 31 | _Added_ _Config.php_ file has been added to store plugin configuration. 32 | 33 | _Added_ _Utils.php_ file has been added to store utility functions. 34 | 35 | _Added_ _GenericError.php_ file has been added to handle generic errors. 36 | 37 | _Added_ Strict types have been added to all classes. 38 | 39 | _Added_ php-stubs/woocommerce-stubs as composer.json dependency. 40 | 41 | ### Version 1.5.1 (07/31/2024): 42 | 43 | _Fixed_ dynamic string Internationalization 44 | 45 | _Removed_ "Test" order, now when test mode enabled, returned callback status will "PAID" or "EXPIRED", depends which is chosen in merchant project settings 46 | 47 | ### 1.5.0 (02/05/2024) 48 | 49 | _Added_ Compatibility with the new block-based checkout functionality introduced in WooCommerce 8.3. 50 | 51 | _Fixed_ Deprecated functions/methods/variables. 52 | 53 | _Removed_ Empty instructions variable, if needed, it will be added in future versions. 54 | 55 | _Fixed_ Compatibility with "High-Performance Order Storage" introduced in WooCommerce 8.2. 56 | 57 | _Added_ Test mode checkbox. When enabled, if order callback is received, then test order will be set to selected order status (by default - "Completed"). Also SpectroCoin payment option will be visible only for admin user. 58 | 59 | _Added_ Messages related with order processing to order notes. 60 | 61 | _Fixed_ "Failed" status with failed and expired orders. 62 | 63 | ### 1.4.1 (01/26/2024) 64 | 65 | _Removed_ Plugin dependency from plugin directory names 66 | 67 | _Fixed_ Fatal error for new installations 68 | 69 | ### 1.4.0 (01/03/2024) 70 | 71 | This update is significant to plugin's security and stability. The posibility of errors during checkout is minimized, reduced posibility of XSS and SQL injection attacks. 72 | 73 | _Migrated_ to GuzzleHttp since HTTPful is no longer maintained. In this case /vendor directory was added which contains GuzzleHttp dependencies. 74 | 75 | _Added_ Settings field sanitization. 76 | 77 | _Added_ Settings field validation. In this case we minimized possible error count during checkout, SpectroCoin won't appear in checkout until settings validation is passed. 78 | 79 | _Added_ Admin notice in admin plugin settings for all fields validation. 80 | 81 | _Added_ Escaping all output variables with appropriate functions. 82 | 83 | _Added_ "spectrocoin\_" prefix to functiton names. 84 | 85 | _Added_ "SpectroCoin\_" prefix to class names. 86 | 87 | _Added_ validation and sanitization when request payload is created. 88 | 89 | _Added_ validation and sanitization when callback is received. 90 | 91 | _Added_ components class "SpectroCoin_ValidationUtil" for specific validation functions. 92 | 93 | _Added_ logging to Wordpress log when errors occur. 94 | 95 | _Added_ logging to WooCommerce status log when errors occur. 96 | 97 | _Fixed_ is_available() function behaviour, when sometimes it returned false, even if all settings were correct. 98 | 99 | _Optimised_ the The whole $\_POST stack processing. Now only needed callback keys is being processed. 100 | 101 | _Updated_ hardcoded notice display from admin_options() function. 102 | 103 | _Updated_ spectrocoin_admin_error_notice() function, added additional parameter to allow hyperlink display. Also the notice will be displayed once and won't be displayed in other admin screens except SpectroCoin settings. 104 | 105 | ### 1.3.0 (10/04/2023) 106 | 107 | _Fixed_ hardcoded order statuses in plugin settings. 108 | 109 | _Added_ Custom order statuses created manually or using plugins will appear in SpectroCoin settings menu. 110 | 111 | _Added_ a new function, when during checkout, if error is occured, now client will see the error code and message instead of generic error message. 112 | 113 | _Added_ plugin checks the FIAT currency, if it is not supported by SpectroCoin, payment will not be available. 114 | 115 | _Added_ admin notice in admin plugin settings to notify that shop currency is not supported by SpectroCoin. 116 | 117 | ### 1.2.0 (09/10/2023) 118 | 119 | _Added_ plugin string internationalization, for plugin translation to various languages. 120 | 121 | _Added_ two additional links within admin window connecting to official wordpress.org website to easily rate, leave feedback and report bugs. 122 | 123 | _Updated_ style changes in settings window 124 | 125 | _For Developers_ Added documentation with parameters and return variables before every function 126 | 127 | ### 1.1.0 (07/31/2023) 128 | 129 | _Added_ a new option in admin menu, to display or not the SpectroCoin logo during checkout. 130 | 131 | ### 1.0.0 (07/31/2023) 132 | 133 | _Added_ a link to access SpectroCoin plugin settings directly from the plugin page. This enhancement provides users with easier access to the configuration options. 134 | 135 | _Implemented_ an "if" statement to handle compatibility with older PHP versions (PHP 8 and below) for the function openssl_free_key($public_key_pem). This change is necessary as PHP 8 136 | deprecates openssl_free_key and now automatically destroys the key instance when it goes out of scope. (Source https//stackoverflow.com/questions/69559775/php-openssl-free-key-deprecated) 137 | 138 | _Improved_ the WC_Gateway_Spectrocoin class, made changes to prevent deprecated messages related to the creation of dynamic properties. The properties (merchant_id, protected_id, private_key, and order_status) are now explicitly declared as protected, and getter functions are added to ensure better encapsulation. This update is particularly important for PHP version 8.2 and above. 139 | 140 | _Added_ a dependency on the WooCommerce plugin for the SpectroCoin plugin. The SpectroCoin plugin now requires WooCommerce to be installed and active on the site. If the user deletes or deactivates WooCommerce, a notice will be displayed, and the SpectroCoin plugin will be deactivated automatically. 141 | 142 | _Enhanced_ the style of the admin's payment settings window to match the design of SpectroCoin.com, providing a more cohesive user experience. 143 | 144 | _Added_ an informative message on the admin page, guiding users on how to obtain the mandatory credentials required for using the SpectroCoin plugin effectively. This addition helps users easily find the necessary information for setup and configuration. 145 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "require": { 3 | "guzzlehttp/guzzle": "^7.8", 4 | "dotenv-org/phpdotenv-vault": "^0.2.4" 5 | }, 6 | "require-dev": { 7 | "php-stubs/woocommerce-stubs": "^8.9", 8 | "brain/monkey": "2.*", 9 | "phpunit/phpunit": "^12.0" 10 | }, 11 | "autoload": { 12 | "psr-4": { 13 | "SpectroCoin\\SCMerchantClient\\": "SCMerchantClient/", 14 | "SpectroCoin\\Includes\\": "includes/" 15 | } 16 | }, 17 | "scripts": { 18 | "test": "XDEBUG_MODE=coverage vendor/bin/phpunit --testdox --coverage-text", 19 | "test-html-report": "XDEBUG_MODE=coverage vendor/bin/phpunit --coverage-html coverage-report" 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /includes/SpectroCoinAuthHandler.php: -------------------------------------------------------------------------------- 1 | encryptionKey = $this->generateEncryptionKey(); 20 | $this->accessTokenTransientKey = "spectrocoin_transient_key"; 21 | } 22 | 23 | /** 24 | * Generate encryption key using WordPress authentication keys 25 | * 26 | * @return string 27 | */ 28 | private function generateEncryptionKey(): string{ 29 | $this->encryptionKey = hash('sha256', AUTH_KEY . SECURE_AUTH_KEY . LOGGED_IN_KEY . NONCE_KEY); 30 | return $this->encryptionKey; 31 | } 32 | 33 | /** 34 | * Get saved auth token from Wordpress transient 35 | * 36 | * @return string|bool Encrypted auth token or false if not found 37 | */ 38 | public function getSavedAuthToken(): string|bool{ 39 | return get_transient($this->accessTokenTransientKey); 40 | } 41 | 42 | public function saveAuthToken($accessTokenData): void{ 43 | delete_transient($this->accessTokenTransientKey); 44 | $currentTime = time(); 45 | $accessTokenData['expires_at'] = $currentTime + $accessTokenData['expires_in']; 46 | $encryptedAccessTokenData = Utils::EncryptAuthData(json_encode($accessTokenData), $this->encryptionKey); 47 | set_transient($this->accessTokenTransientKey, $encryptedAccessTokenData, $accessTokenData['expires_in']); 48 | } 49 | 50 | /** 51 | * Get the value of encryptionKey 52 | */ 53 | public function getEncryptionKey() 54 | { 55 | return $this->encryptionKey; 56 | } 57 | 58 | /** 59 | * Get the value of accessTokenTransientKey 60 | */ 61 | public function getAccessTokenTransientKey() 62 | { 63 | return $this->accessTokenTransientKey; 64 | } 65 | } -------------------------------------------------------------------------------- /includes/SpectroCoinBlocksIntegration.php: -------------------------------------------------------------------------------- 1 | gateway = new SpectroCoinGateway(); 20 | } 21 | 22 | public function is_active(): bool { 23 | return $this->gateway->is_available(); 24 | } 25 | 26 | public function get_payment_method_script_handles(): array { 27 | wp_register_script( 28 | 'spectrocoin-blocks-integration', 29 | plugin_dir_url(__FILE__) . '../assets/js/block-checkout.js', 30 | ['wc-blocks-registry', 'wc-settings', 'wp-element', 'wp-html-entities', 'wp-i18n'], 31 | filemtime(plugin_dir_path(__FILE__) . '../assets/js/block-checkout.js'), 32 | true 33 | ); 34 | 35 | if (function_exists('wp_set_script_translations')) { 36 | wp_set_script_translations('spectrocoin-blocks-integration', 'spectrocoin-accepting-bitcoin'); 37 | } 38 | 39 | return ['spectrocoin-blocks-integration']; 40 | } 41 | 42 | public function get_payment_method_data(): array { 43 | return [ 44 | 'title' => $this->gateway->title, 45 | 'description' => $this->gateway->description, 46 | 'checkout_icon' => $this->gateway->isDisplayLogoEnabled() ? plugins_url('/assets/images/spectrocoin-logo.svg', __DIR__) : '', 47 | ]; 48 | } 49 | } 50 | ?> 51 | -------------------------------------------------------------------------------- /includes/SpectroCoinGateway.php: -------------------------------------------------------------------------------- 1 | id = 'spectrocoin'; 63 | $this->has_fields = false; 64 | $this->method_title = esc_html__('SpectroCoin', 'spectrocoin-accepting-bitcoin'); 65 | $this->method_description = esc_html__('Take payments via SpectroCoin. Accept more than 30 cryptocurrencies, such as ETH, BTC, and USDT.', 'spectrocoin'); 66 | 67 | $this->order_button_text = esc_html__('Pay with SpectroCoin', 'spectrocoin-accepting-bitcoin'); 68 | $this->supports = array('products'); 69 | $this->title = $this->get_option('title'); 70 | $this->description = $this->get_option('description'); 71 | $this->client_id = $this->get_option('client_id'); 72 | $this->project_id = $this->get_option('project_id'); 73 | $this->client_secret = $this->get_option('client_secret'); 74 | $this->order_status = $this->get_option('order_status'); 75 | $this->all_order_statuses = wc_get_order_statuses(); 76 | 77 | $this->auth_handler = new SpectroCoinAuthHandler(); 78 | 79 | add_action('woocommerce_update_options_payment_gateways_' . $this->id, array($this, 'process_admin_options')); 80 | $this->initializeSCClient(); 81 | $this->init_settings(); 82 | $this->wc_logger = new WC_Logger(); 83 | $this->form_fields = $this->generateFormFields(); 84 | 85 | add_action('admin_notices', array($this, 'renew_keys_notice')); // (REMOVE THIS WHEN UPDATE NOTICE IS NOT NEEDED) 86 | } 87 | 88 | /** 89 | * Function which is called when SpectroCoin settings is saved. 90 | */ 91 | public function process_admin_options(): bool 92 | { 93 | $saved = parent::process_admin_options(); 94 | if ($saved) { 95 | $this->reloadSettings(); 96 | $this->validateSettings(true); 97 | } 98 | 99 | return $saved; 100 | } 101 | 102 | /** 103 | * Initializes the SpectroCoin API client if credentials are valid. 104 | */ 105 | private function initializeSCClient(): void 106 | { 107 | $this->sc_merchant_client = new SCMerchantClient( 108 | $this->project_id, 109 | $this->client_id, 110 | $this->client_secret, 111 | ); 112 | add_action('woocommerce_api_' . $this->callback_name, array($this, 'callback')); 113 | 114 | } 115 | 116 | /** 117 | * Reloads settings from database. 118 | */ 119 | private function reloadSettings(): void 120 | { 121 | $this->title = $this->get_option('title'); 122 | $this->description = $this->get_option('description'); 123 | $this->project_id = $this->get_option('project_id'); 124 | $this->client_id = $this->get_option('client_id'); 125 | $this->client_secret = $this->get_option('client_secret'); 126 | $this->order_status = $this->get_option('order_status'); 127 | } 128 | 129 | /** 130 | * Check validity of credentials in settings. 131 | * @param bool $display_notice If true, then error notices will be displayed Default = true. 132 | * @return bool 133 | */ 134 | public function validateSettings(bool $display_notice = true): bool 135 | { 136 | $is_valid = true; 137 | 138 | if (empty($this->client_id)) { 139 | if ($display_notice) { 140 | $this->displayAdminErrorNotice('Client ID is empty'); 141 | $this->wc_logger->log('warning', 'SpectroCoin settings validation warning: Client ID is empty'); 142 | } 143 | $is_valid = false; 144 | } 145 | 146 | if (empty($this->project_id)) { 147 | if ($display_notice) { 148 | $this->displayAdminErrorNotice('Project ID is empty'); 149 | $this->wc_logger->log('warning', 'SpectroCoin settings validation warning: Project ID is empty'); 150 | } 151 | $is_valid = false; 152 | } 153 | 154 | if (empty($this->client_secret)) { 155 | if ($display_notice) { 156 | $this->displayAdminErrorNotice('Client Secret is empty'); 157 | $this->wc_logger->log('warning', 'SpectroCoin settings validation warning: Client Secret is empty'); 158 | } 159 | $is_valid = false; 160 | } 161 | 162 | $this->title = sanitize_text_field($this->get_option('title')); 163 | if (empty($this->title)) { 164 | if ($display_notice) { 165 | $this->displayAdminErrorNotice('Title cannot be empty'); 166 | $this->wc_logger->log('warning', 'SpectroCoin settings validation warning: Title cannot be empty'); 167 | } 168 | $is_valid = false; 169 | } 170 | 171 | $this->description = sanitize_textarea_field($this->get_option('description')); 172 | 173 | $this->enabled = sanitize_text_field($this->get_option('enabled')); 174 | if (!in_array($this->enabled, ['yes', 'no'])) { 175 | if ($display_notice) { 176 | $this->displayAdminErrorNotice('Invalid value for enabled status'); 177 | $this->wc_logger->log('warning', 'SpectroCoin settings validation warning: Invalid value for enabled status'); 178 | } 179 | $is_valid = false; 180 | } 181 | 182 | $this->order_status = sanitize_text_field($this->get_option('order_status')); 183 | if (!array_key_exists($this->order_status, $this->all_order_statuses)) { 184 | if ($display_notice) { 185 | $this->displayAdminErrorNotice('Invalid order status'); 186 | $this->wc_logger->log('warning', 'SpectroCoin settings validation warning: Invalid order status'); 187 | } 188 | $is_valid = false; 189 | } 190 | 191 | if (!in_array(sanitize_text_field($this->get_option('display_logo')), ['yes', 'no'])) { 192 | if ($display_notice) { 193 | $this->displayAdminErrorNotice('Invalid value for display logo status'); 194 | $this->wc_logger->log('warning', 'SpectroCoin settings validation warning: Invalid value for display logo status'); 195 | } 196 | $is_valid = false; 197 | } 198 | 199 | if (!in_array(sanitize_text_field($this->get_option('hide_from_checkout')), ['yes', 'no'])) { 200 | if ($display_notice) { 201 | $this->displayAdminErrorNotice('Invalid value for test mode'); 202 | $this->wc_logger->log('warning', 'SpectroCoin settings validation warning: Invalid value for test mode'); 203 | } 204 | $is_valid = false; 205 | } 206 | return $is_valid; 207 | } 208 | 209 | /** 210 | * Function to toggle the display of the SpectroCoin payment option 211 | * The payment method will be displayed when the following conditions are met: 212 | * 1. The SpectroCoin plugin is enabled. 213 | * 2. The SpectroCoin plugin is configured with valid credentials. 214 | * 3. The FIAT currency is accepted by SpectroCoin. Accepted currencies are: "EUR", "USD", "PLN", "CHF", "SEK", "GBP", "AUD", "CAD", "CZK", "DKK", "NOK". 215 | * 4. The "hide from checkout" admin option is disabled or the current user is an admin. 216 | * @return bool 217 | */ 218 | public function is_available(): bool 219 | { 220 | if (!function_exists('is_plugin_active')) { 221 | return false; 222 | } 223 | 224 | if (!is_plugin_active(explode("/", plugin_basename(__FILE__))[0] . '/spectrocoin.php')) { 225 | return false; 226 | } 227 | 228 | if ($this->enabled !== 'yes') { 229 | return false; 230 | } 231 | 232 | if (!$this->checkFiatCurrency()) { 233 | $currency = esc_html(get_woocommerce_currency()); 234 | $message = "{$currency} currency is not accepted by SpectroCoin. Please change your currency in the WooCommerce settings."; 235 | error_log("SpectroCoin Error: {$message}"); 236 | 237 | $settings_link = esc_url(admin_url('admin.php?page=wc-settings&tab=general')); 238 | $this->displayAdminErrorNotice("{$message} WooCommerce settings.", true); 239 | return false; 240 | } 241 | 242 | if (!$this->validateSettings(false)) { 243 | return false; 244 | } 245 | 246 | if ($this->sc_merchant_client === null) { 247 | $this->initializeSCClient(); 248 | } 249 | 250 | if ($this->sc_merchant_client === null) { 251 | return false; 252 | } 253 | 254 | if ($this->isHideFromCheckoutEnabled() && !current_user_can('manage_options')) { 255 | return false; 256 | } 257 | 258 | return true; 259 | } 260 | 261 | /** 262 | * Check if "display logo" admin option is enabled. 263 | * @return bool 264 | */ 265 | public function isDisplayLogoEnabled(): bool 266 | { 267 | if ($this->get_option('display_logo') == "yes") { 268 | return true; 269 | } 270 | return false; 271 | } 272 | 273 | /** 274 | * Check if "hide from checkout" admin option enabled. 275 | * @return bool 276 | */ 277 | public function isHideFromCheckoutEnabled(): bool 278 | { 279 | if ($this->get_option('hide_from_checkout') == "yes") { 280 | return true; 281 | } 282 | return false; 283 | } 284 | 285 | /** 286 | * Generate admin settings form. 287 | */ 288 | public function admin_options(): void 289 | { 290 | ?> 291 |
292 |
293 | ', 296 | esc_url('https://spectrocoin.com/'), 297 | esc_url(plugins_url('/../assets/images/spectrocoin-logo.svg', __FILE__)), 298 | esc_attr__('SpectroCoin logo', 'spectrocoin-accepting-bitcoin') 299 | ); 300 | ?> 301 |
302 |
303 | ', 306 | esc_url(plugins_url('/../assets/images/card_phone_top.svg', __FILE__)), 307 | esc_attr__('Header Image', 'spectrocoin-accepting-bitcoin') 308 | ); 309 | ?> 310 |
311 |
312 | 313 |
314 |
315 | 316 | generate_settings_html($this->form_fields); ?> 317 |
318 |
319 |
320 |
321 |

322 |

323 | 324 |

325 |

326 |

327 | 330 |

331 |
    332 |
  • 333 | 1. 334 | %s %s', esc_url('https://auth.spectrocoin.com/signup'), esc_html__('Sign up', 'spectrocoin-accepting-bitcoin'), esc_html__('for a SpectroCoin Account.', 'spectrocoin-accepting-bitcoin')); ?> 335 |
  • 336 |
  • 337 | 2. 338 | %s %s', esc_url('https://auth.spectrocoin.com/login'), esc_html__('Log in', 'spectrocoin-accepting-bitcoin'), esc_html__('to your SpectroCoin account.', 'spectrocoin-accepting-bitcoin')); ?> 339 |
  • 340 |
  • 341 | 3. 342 | %s %s', esc_html__('On the dashboard, locate the', 'spectrocoin-accepting-bitcoin'), esc_url('https://spectrocoin.com/en/merchants/projects'), esc_html__('Business', 'spectrocoin-accepting-bitcoin'), esc_html__('tab and click on it.', 'spectrocoin-accepting-bitcoin')); ?> 343 |
  • 344 |
  • 345 | 4. 346 | %s.', esc_html__('Click on', 'spectrocoin-accepting-bitcoin'), esc_url('https://spectrocoin.com/en/merchants/projects/new'), esc_html__('New project', 'spectrocoin-accepting-bitcoin')); ?> 347 |
  • 348 |
  • 349 | 5. 350 | 351 |
  • 352 |
  • 353 | 6. 354 | 355 |
  • 356 |
  • 357 | 7. 358 | 359 |
  • 360 |
  • 361 | 8. 362 | ' . 365 | esc_html__('Settings', 'spectrocoin-accepting-bitcoin') . 366 | '' . 367 | esc_html__('. Then click on ', 'spectrocoin-accepting-bitcoin') . 368 | '' . 369 | esc_html__('API', 'spectrocoin-accepting-bitcoin') . 370 | '' . 371 | esc_html__(' and choose ', 'spectrocoin-accepting-bitcoin') . 372 | '' . 373 | esc_html__('Create New API', 'spectrocoin-accepting-bitcoin') . 374 | '.'; 375 | ?> 376 |
  • 377 |
  • 378 | 9. 379 | 380 |
  • 381 |
  • 382 | 10. 383 | 384 |
  • 385 |
    386 |
  • 387 | 388 | 389 | 390 |
  • 391 |
392 |
393 | %1$s
%2$s %3$s · %5$s
', 396 | esc_html__('Accept Bitcoin through the SpectroCoin and receive payments in your chosen currency.', 'spectrocoin-accepting-bitcoin'), 397 | esc_html__('Still have questions? Contact us via', 'spectrocoin-accepting-bitcoin'), 398 | esc_html__('skype: spectrocoin_merchant', 'spectrocoin-accepting-bitcoin'), 399 | esc_url('mailto:merchant@spectrocoin.com'), 400 | esc_html('merchant@spectrocoin.com') 401 | ); 402 | ?> 403 |
404 | 405 | array( 416 | 'title' => esc_html__('Enable/Disable', 'spectrocoin-accepting-bitcoin'), 417 | 'type' => 'checkbox', 418 | 'label' => esc_html__('Enable SpectroCoin', 'spectrocoin-accepting-bitcoin'), 419 | 'default' => 'no' 420 | ), 421 | 'title' => array( 422 | 'title' => esc_html__('Title', 'spectrocoin-accepting-bitcoin'), 423 | 'type' => 'Text', 424 | 'description' => esc_html__('This controls the title which the user sees during checkout. Default is "Pay with SpectroCoin".', 'spectrocoin-accepting-bitcoin'), 425 | 'default' => esc_html__('Pay with SpectroCoin', 'spectrocoin-accepting-bitcoin'), 426 | 'desc_tip' => true, 427 | ), 428 | 'description' => array( 429 | 'title' => esc_html__('Description', 'spectrocoin-accepting-bitcoin'), 430 | 'type' => 'text', 431 | 'desc_tip' => true, 432 | 'description' => esc_html__('This controls the description which the user sees during checkout.', 'spectrocoin-accepting-bitcoin'), 433 | ), 434 | 'project_id' => array( 435 | 'title' => esc_html__('Project ID', 'spectrocoin-accepting-bitcoin'), 436 | 'type' => 'text', 437 | ), 438 | 'client_id' => array( 439 | 'title' => esc_html__('Client ID', 'spectrocoin-accepting-bitcoin'), 440 | 'type' => 'text' 441 | ), 442 | 'client_secret' => array( 443 | 'title' => esc_html__('Client Secret', 'spectrocoin-accepting-bitcoin'), 444 | 'type' => 'text', 445 | ), 446 | 'order_status' => array( 447 | 'title' => esc_html__('Order status', 'spectrocoin-accepting-bitcoin'), 448 | 'desc_tip' => true, 449 | 'description' => esc_html__('Order status after payment has been received. Custom order statuses will appear in the list.', 'spectrocoin-accepting-bitcoin'), 450 | 'type' => 'select', 451 | 'default' => 'wc-completed', 452 | 'options' => $this->all_order_statuses 453 | ), 454 | 'display_logo' => array( 455 | 'title' => esc_html__('Display logo', 'spectrocoin-accepting-bitcoin'), 456 | 'description' => esc_html__('This controls the display of SpectroCoin logo in the checkout page', 'spectrocoin-accepting-bitcoin'), 457 | 'desc_tip' => true, 458 | 'type' => 'checkbox', 459 | 'label' => esc_html__('Enable', 'spectrocoin-accepting-bitcoin'), 460 | 'default' => 'yes' 461 | ), 462 | 'hide_from_checkout' => array( 463 | 'title' => esc_html__('Hide from checkout', 'spectrocoin-accepting-bitcoin'), 464 | 'description' => esc_html__('When enabled SpectroCoin payment option will be visible only for admin user.', 'spectrocoin-accepting-bitcoin'), 465 | 'desc_tip' => true, 466 | 'type' => 'checkbox', 467 | 'label' => esc_html__('Enable', 'spectrocoin-accepting-bitcoin'), 468 | 'default' => 'no' 469 | ) 470 | ); 471 | } 472 | 473 | 474 | /** 475 | * Retrieves or refreshes the access token. 476 | * 477 | * This method attempts to retrieve the saved access token and checks its validity. 478 | * If the token is valid, it returns the token. If the token is invalid or not present, 479 | * it requests a new token from the SpectroCoin merchant client, saves it, and returns the new token. 480 | * 481 | * @return array|string The access token array, or an empty string if the token could not be retrieved. 482 | */ 483 | public function getOrRefreshAccessToken() : array|string 484 | { 485 | $encryption_key = $this->auth_handler->getEncryptionKey(); 486 | $encrypted_access_token_data = $this->auth_handler->getSavedAuthToken(); 487 | $current_time = time(); 488 | $token_data = null; 489 | 490 | if ($encrypted_access_token_data) { 491 | $decrypted_access_token_data = json_decode( 492 | Utils::DecryptAuthData($encrypted_access_token_data, $encryption_key), 493 | true 494 | ); 495 | if ($this->sc_merchant_client->isTokenValid($decrypted_access_token_data, $current_time)) { 496 | $token_data = $decrypted_access_token_data; 497 | } 498 | } 499 | 500 | if (!$token_data) { 501 | $new_token = $this->sc_merchant_client->getAccessToken(); 502 | if ($new_token instanceof ApiError || $new_token instanceof GenericError) { 503 | $this->wc_logger->log( 504 | 'error', 505 | "SpectroCoin error: Failed to get access token. Response message: {$new_token->getMessage()}" 506 | ); 507 | return ''; 508 | } 509 | $token_data = $new_token; 510 | } 511 | 512 | $this->auth_handler->saveAuthToken($token_data); 513 | return $token_data ?? ''; 514 | } 515 | 516 | 517 | /** 518 | * Process the payment and return the result. 519 | * @param int $order_id 520 | * @return array 521 | */ 522 | public function process_payment($order_id): array 523 | { 524 | $order = new WC_Order($order_id); 525 | $access_token_data = $this->getOrRefreshAccessToken(); 526 | if ($access_token_data === '') { 527 | $error_message = "SpectroCoin error: Failed to get access token"; 528 | $order->update_status('failed', __($error_message, 'spectrocoin-accepting-bitcoin')); 529 | $this->wc_logger->log('error', $error_message); 530 | return array( 531 | 'result' => 'failed', 532 | 'redirect' => '' 533 | ); 534 | } 535 | 536 | $order_data = [ 537 | 'orderId' => $order->get_id() . "-" . Utils::generateRandomStr(6), 538 | 'description' => "Order #{$order_id} from " . get_site_url(), 539 | 'receiveAmount' => $order->get_total(), 540 | 'receiveCurrencyCode' => $order->get_currency(), 541 | 'callbackUrl' => get_site_url(null, '?wc-api=' . $this->callback_name), 542 | 'successUrl' => $this->get_return_url($order), 543 | 'failureUrl' => $this->get_return_url($order) 544 | ]; 545 | 546 | $response = $this->sc_merchant_client->createOrder($order_data, $access_token_data); 547 | 548 | if ($response instanceof ApiError || $response instanceof GenericError) { 549 | $error_message = "SpectroCoin error: Failed to create payment for order {$order_id}. Response message: {$response->getMessage()}"; 550 | $order->update_status('failed', __($error_message, 'spectrocoin-accepting-bitcoin')); 551 | $this->wc_logger->log('error', $error_message); 552 | return array( 553 | 'result' => 'failed', 554 | 'redirect' => '' 555 | ); 556 | } 557 | 558 | $order->update_status('pending', __('Waiting for SpectroCoin payment', 'spectrocoin-accepting-bitcoin')); 559 | return array( 560 | 'result' => 'success', 561 | 'redirect' => $response->getRedirectUrl() 562 | ); 563 | } 564 | 565 | /** 566 | * Used to process callbacks from SpectroCoin 567 | * Callback is parsed to spectrocoin_process_callback method, which handles sanitization and validation. 568 | * If callback is valid, then order status is updated. 569 | * If callback is invalid, then error message is logged and order fails. 570 | */ 571 | public function callback(): void 572 | { 573 | try { 574 | global $woocommerce; 575 | $order_callback = $this->initCallbackFromPost(); 576 | 577 | if (!$order_callback) { 578 | $this->wc_logger->log('error', "Sent callback is invalid"); 579 | http_response_code(400); // Bad Request 580 | echo esc_html__('Invalid callback', 'spectrocoin-accepting-bitcoin'); 581 | exit; 582 | } 583 | 584 | $order_id = explode('-', ($order_callback->getOrderId()))[0]; 585 | $status = $order_callback->getStatus(); 586 | $order = wc_get_order($order_id); 587 | if ($order) { 588 | switch ($status) { 589 | case OrderStatus::New ->value: 590 | case OrderStatus::Pending->value: 591 | $order->update_status('pending'); 592 | break; 593 | case OrderStatus::Paid->value: 594 | $woocommerce->cart->empty_cart(); 595 | $order->payment_complete(); 596 | $order->update_status($this->order_status); 597 | break; 598 | case OrderStatus::Failed->value: 599 | $order->update_status('failed'); 600 | break; 601 | case OrderStatus::Expired->value: 602 | $order->update_status('failed'); 603 | break; 604 | } 605 | http_response_code(200); // OK 606 | echo esc_html__('*ok*', 'spectrocoin-accepting-bitcoin'); 607 | exit; 608 | } else { 609 | $this->wc_logger->log('error', "Order '{$order_id}' not found!"); 610 | http_response_code(404); // Not Found 611 | echo esc_html__("Order '{$order_id}' not found!", 'spectrocoin-accepting-bitcoin'); 612 | exit; 613 | } 614 | } catch (RequestException $e) { 615 | $this->wc_logger->log('error', "Callback API error: {$e->getMessage()}"); 616 | http_response_code(500); // Internal Server Error 617 | echo esc_html__('Callback API error', 'spectrocoin-accepting-bitcoin'); 618 | exit; 619 | } catch (InvalidArgumentException $e) { 620 | $this->wc_logger->log('error', "Error processing callback: {$e->getMessage()}"); 621 | http_response_code(400); // Bad Request 622 | echo esc_html__('Error processing callback', 'spectrocoin-accepting-bitcoin'); 623 | exit; 624 | } catch (Exception $e) { 625 | $this->wc_logger->log('error', "Error processing callback: {$e->getMessage()}"); 626 | http_response_code(500); // Internal Server Error 627 | echo esc_html__('Error processing callback', 'spectrocoin-accepting-bitcoin'); 628 | exit; 629 | } 630 | } 631 | 632 | /** 633 | * Initializes the callback data from POST request. 634 | * 635 | * @return OrderCallback|null Returns an OrderCallback object if data is valid, null otherwise. 636 | */ 637 | private function initCallbackFromPost(): ?OrderCallback 638 | { 639 | $expected_keys = ['userId', 'merchantApiId', 'merchantId', 'apiId', 'orderId', 'payCurrency', 'payAmount', 'receiveCurrency', 'receiveAmount', 'receivedAmount', 'description', 'orderRequestId', 'status', 'sign']; 640 | 641 | $callback_data = []; 642 | foreach ($expected_keys as $key) { 643 | if (isset($_POST[$key])) { 644 | $callback_data[$key] = $_POST[$key]; 645 | } 646 | } 647 | 648 | if (empty($callback_data)) { 649 | $this->wc_logger->log('error', "No data received in callback"); 650 | return null; 651 | } 652 | return new OrderCallback($callback_data); 653 | } 654 | 655 | /** 656 | * Check if currency is accepted by SpectroCoin 657 | * Function compares current currency with accepted currencies from Config class 658 | * @return bool 659 | */ 660 | private function checkFiatCurrency(): bool 661 | { 662 | $current_currency_iso_code = get_woocommerce_currency(); 663 | return in_array($current_currency_iso_code, Config::ACCEPTED_FIAT_CURRENCIES); 664 | } 665 | 666 | /** 667 | * Display error message in spectrocoin admin settings 668 | * @param string $message Error message 669 | * @param bool $allow_hyperlink Allow hyperlink in error message 670 | */ 671 | public static function displayAdminErrorNotice(string $message, bool $allow_hyperlink = false): void 672 | { 673 | static $displayed_messages = array(); 674 | 675 | $allowed_html = $allow_hyperlink ? array( 676 | 'a' => array( 677 | 'href' => array(), 678 | 'title' => array(), 679 | 'target' => array(), 680 | ), 681 | ) : array(); 682 | 683 | $processed_message = wp_kses($message, $allowed_html); 684 | 685 | $current_page = isset($_GET['section']) ? sanitize_text_field($_GET['section']) : ''; 686 | 687 | if (!empty($processed_message) && !in_array($processed_message, $displayed_messages) && $current_page == "spectrocoin") { 688 | array_push($displayed_messages, $processed_message); 689 | ?> 690 |
691 |

692 |

693 |
694 | 702 | project_id)){ // this prevents from displaying notice to new installations 716 | return; 717 | } 718 | if (empty($this->client_id) || empty($this->client_secret)) { 719 | self::$renew_notice_displayed = true; // prevent double notice display 720 | ?> 721 |
722 |

723 | 724 |

725 |

726 | 727 |

728 |

729 | 730 | 731 | 732 |

733 |

734 | 735 |

736 |
737 | 742 | 2 | 16 | 17 | 18 | ./tests 19 | 20 | 21 | 22 | 23 | 24 | SCMerchantClient 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /spectrocoin.php: -------------------------------------------------------------------------------- 1 | ' . esc_html__('Settings', 'spectrocoin-accepting-bitcoin') . ''; 133 | array_push($links, $custom_link); 134 | } 135 | return $links; 136 | } 137 | 138 | /** 139 | * Add custom links to plugin page 140 | */ 141 | function addCustomLinksRight(array $plugin_meta, string $file): array 142 | { 143 | if (strpos($file, 'spectrocoin') !== false) { 144 | $custom_links = [ 145 | 'community-support' => '' . esc_html__('Community support', 'spectrocoin-accepting-bitcoin') . '', 146 | 'rate-us' => '' . esc_html__('Rate us', 'spectrocoin-accepting-bitcoin') . '', 147 | ]; 148 | $plugin_meta = array_merge($plugin_meta, $custom_links); 149 | } 150 | return $plugin_meta; 151 | } 152 | 153 | /** 154 | * Enqueue admin styles 155 | */ 156 | function EnqueueAdminStyles(): void 157 | { 158 | $current_screen = get_current_screen(); 159 | if ($current_screen->base === 'woocommerce_page_wc-settings' && isset($_GET['section']) && $_GET['section'] === 'spectrocoin') { 160 | wp_enqueue_style('spectrocoin-payment-settings-css', esc_url(plugin_dir_url(__FILE__)) . 'assets/style/settings.css', [], '1.0.0'); 161 | } 162 | } 163 | 164 | function declareBlocksCompatibility(): void 165 | { 166 | if (class_exists(FeaturesUtil::class)) { 167 | FeaturesUtil::declare_compatibility('cart_checkout_blocks', __FILE__, true); 168 | } 169 | } 170 | 171 | add_action('woocommerce_blocks_loaded', '\SpectroCoin\registerOrderApprovalPaymentMethodType'); 172 | 173 | add_action('before_woocommerce_init', function () { 174 | if (class_exists(FeaturesUtil::class)) { 175 | FeaturesUtil::declare_compatibility('custom_order_tables', __FILE__, true); 176 | } 177 | }); 178 | 179 | function registerOrderApprovalPaymentMethodType(): void 180 | { 181 | if (!class_exists('Automattic\WooCommerce\Blocks\Payments\Integrations\AbstractPaymentMethodType')) { 182 | return; 183 | } 184 | 185 | add_action( 186 | 'woocommerce_blocks_payment_method_type_registration', 187 | function (PaymentMethodRegistry $payment_method_registry): void { 188 | $payment_method_registry->register(new SpectroCoinBlocksIntegration); 189 | } 190 | ); 191 | } 192 | 193 | add_action('plugins_loaded', '\SpectroCoin\spectrocoinInitPlugin'); 194 | add_action('admin_enqueue_scripts', '\SpectroCoin\EnqueueAdminStyles'); 195 | 196 | /** 197 | * Display Admin Notice from Transient 198 | */ 199 | add_action('admin_notices', function () { 200 | // Retrieve the error notice 201 | $notice = get_transient('spectrocoin_requirements_not_met'); 202 | 203 | if ($notice) { 204 | echo '
'; 205 | echo '

' . esc_html($notice) . '

'; 206 | echo '
'; 207 | 208 | // Clear the transient after displaying the notice 209 | delete_transient('spectrocoin_requirements_not_met'); 210 | } 211 | }); 212 | 213 | -------------------------------------------------------------------------------- /tests/SCMerchantClient/ConfigTest.php: -------------------------------------------------------------------------------- 1 | assertSame('https://spectrocoin.com/api/public', Config::MERCHANT_API_URL); 15 | } 16 | 17 | #[TestDox('Config::AUTH_URL should equal "https://spectrocoin.com/api/public/oauth/token"')] 18 | public function testAuthUrl(): void 19 | { 20 | $this->assertSame('https://spectrocoin.com/api/public/oauth/token', Config::AUTH_URL); 21 | } 22 | 23 | #[TestDox('Config::PUBLIC_SPECTROCOIN_CERT_LOCATION should equal "https://spectrocoin.com/files/merchant.public.pem"')] 24 | public function testPublicSpectrocoinCertLocation(): void 25 | { 26 | $this->assertSame('https://spectrocoin.com/files/merchant.public.pem', Config::PUBLIC_SPECTROCOIN_CERT_LOCATION); 27 | } 28 | 29 | #[TestDox('Config::ACCEPTED_FIAT_CURRENCIES should match the expected currencies')] 30 | public function testAcceptedFiatCurrencies(): void 31 | { 32 | $expected = ["EUR", "USD", "PLN", "CHF", "SEK", "GBP", "AUD", "CAD", "CZK", "DKK", "NOK"]; 33 | $this->assertSame($expected, Config::ACCEPTED_FIAT_CURRENCIES); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /tests/SCMerchantClient/Enum/OrderStatusTest.php: -------------------------------------------------------------------------------- 1 | assertSame($expected, $status); 17 | } 18 | 19 | public static function orderStatusProvider(): array{ 20 | 21 | return [ 22 | '1 is New' => [1, OrderStatus::New->value], 23 | '2 is Pending' => [2, OrderStatus::Pending->value], 24 | '3 is Paid' => [3, OrderStatus::Paid->value], 25 | '4 is Failed' => [4, OrderStatus::Failed->value], 26 | '5 is Expired' => [5, OrderStatus::Expired->value], 27 | ]; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /tests/SCMerchantClient/Exception/ExceptionTest.php: -------------------------------------------------------------------------------- 1 | assertSame('An error occurred', $exception->getMessage()); 20 | $this->assertSame(123, $exception->getCode()); 21 | } 22 | 23 | #[TestDox('Test error code of and message ApiError::class')] 24 | public function testApiErrorProperties(): void 25 | { 26 | $exception = new ApiError('API error occurred', 456); 27 | $this->assertSame('API error occurred', $exception->getMessage()); 28 | $this->assertSame(456, $exception->getCode()); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /tests/SCMerchantClient/Http/CreateOrderRequestTest.php: -------------------------------------------------------------------------------- 1 | assertSame($expected, $createOrderRequest->toArray()); 23 | } 24 | 25 | 26 | public static function validCreateOrderRequestProvider(): array 27 | { 28 | return [ 29 | 'Valid payload' => [ 30 | [ 31 | 'orderId' => 'ORD123', 32 | 'description' => 'Test order', 33 | 'receiveAmount' => '500.23', 34 | 'receiveCurrencyCode' => 'EUR', 35 | 'callbackUrl' => 'https://example.com/callback', 36 | 'successUrl' => 'https://example.com/success', 37 | 'failureUrl' => 'https://example.com/failure' 38 | ], 39 | [ 40 | 'orderId' => 'ORD123', 41 | 'description' => 'Test order', 42 | 'receiveAmount' => '500.23', 43 | 'receiveCurrencyCode' => 'EUR', 44 | 'callbackUrl' => 'https://example.com/callback', 45 | 'successUrl' => 'https://example.com/success', 46 | 'failureUrl' => 'https://example.com/failure' 47 | ], 48 | ], 49 | 'Valid payload with random payload order' => [ 50 | [ 51 | 'description' => 'Test order', 52 | 'callbackUrl' => 'https://example.com/callback', 53 | 'receiveCurrencyCode' => 'USD', 54 | 'failureUrl' => 'https://example.com/failure', 55 | 'orderId' => 'ORD123', 56 | 'receiveAmount' => '100.00', 57 | 'successUrl' => 'https://example.com/success', 58 | ], 59 | [ 60 | 'orderId' => 'ORD123', 61 | 'description' => 'Test order', 62 | 'receiveAmount' => '100.0', 63 | 'receiveCurrencyCode' => 'USD', 64 | 'callbackUrl' => 'https://example.com/callback', 65 | 'successUrl' => 'https://example.com/success', 66 | 'failureUrl' => 'https://example.com/failure' 67 | ], 68 | ], 69 | ]; 70 | } 71 | 72 | #[DataProvider('invalidCreateOrderRequestProvider')] 73 | #[TestDox('Test CreateOrderRequest initialization with invalid data')] 74 | public function testCreateOrderRequestWithInvalidData(array $order_data): void 75 | { 76 | $this->expectException(InvalidArgumentException::class); 77 | new CreateOrderRequest($order_data); 78 | } 79 | 80 | 81 | public static function invalidCreateOrderRequestProvider(): array 82 | { 83 | return [ 84 | 'No orderId' => [[ 85 | 'description' => 'Test order', 86 | 'receiveAmount' => '500.23', 87 | 'receiveCurrencyCode' => 'EUR', 88 | 'callbackUrl' => 'https://example.com/callback', 89 | 'successUrl' => 'https://example.com/success', 90 | 'failureUrl' => 'https://example.com/failure' 91 | ]], 92 | 'No description' => [[ 93 | 'orderId' => 'ORD123', 94 | 'receiveAmount' => '500.23', 95 | 'receiveCurrencyCode' => 'EUR', 96 | 'callbackUrl' => 'https://example.com/callback', 97 | 'successUrl' => 'https://example.com/success', 98 | 'failureUrl' => 'https://example.com/failure' 99 | ]], 100 | 'receiveAmount is 0' => [[ 101 | 'orderId' => 'ORD123', 102 | 'receiveAmount' => '0', 103 | 'receiveCurrencyCode' => 'EUR', 104 | 'callbackUrl' => 'https://example.com/callback', 105 | 'successUrl' => 'https://example.com/success', 106 | 'failureUrl' => 'https://example.com/failure' 107 | ]], 108 | 'receiveAmount is -1' => [[ 109 | 'orderId' => 'ORD123', 110 | 'receiveAmount' => '-1', 111 | 'receiveCurrencyCode' => 'EUR', 112 | 'callbackUrl' => 'https://example.com/callback', 113 | 'successUrl' => 'https://example.com/success', 114 | 'failureUrl' => 'https://example.com/failure' 115 | ]], 116 | 'No receiveAmount' => [[ 117 | 'orderId' => 'ORD123', 118 | 'receiveCurrencyCode' => 'EUR', 119 | 'callbackUrl' => 'https://example.com/callback', 120 | 'successUrl' => 'https://example.com/success', 121 | 'failureUrl' => 'https://example.com/failure' 122 | ]], 123 | 'No receiveCurrencyCode' => [[ 124 | 'orderId' => 'ORD123', 125 | 'receiveAmount' => '100.0', 126 | 'callbackUrl' => 'https://example.com/callback', 127 | 'successUrl' => 'https://example.com/success', 128 | 'failureUrl' => 'https://example.com/failure' 129 | ]], 130 | 'receiveCurrencyCode is less than 3 characters' => [[ 131 | 'orderId' => 'ORD123', 132 | 'receiveAmount' => '100.0', 133 | 'receiveCurrencyCode' => 'EU', 134 | 'callbackUrl' => 'https://example.com/callback', 135 | 'successUrl' => 'https://example.com/success', 136 | 'failureUrl' => 'https://example.com/failure' 137 | ]], 138 | 'receiveCurrencyCode is more than 3 characters' => [[ 139 | 'orderId' => 'ORD123', 140 | 'receiveAmount' => '100.0', 141 | 'receiveCurrencyCode' => 'EURO', 142 | 'callbackUrl' => 'https://example.com/callback', 143 | 'successUrl' => 'https://example.com/success', 144 | 'failureUrl' => 'https://example.com/failure' 145 | ]], 146 | 'Invalid callbackUrl with missing TLD' => [[ 147 | 'orderId' => 'ORD123', 148 | 'description' => 'Test order', 149 | 'receiveAmount' => '500.23', 150 | 'receiveCurrencyCode' => 'EUR', 151 | 'callbackUrl' => 'http://example', 152 | 'successUrl' => 'https://example.com/success', 153 | 'failureUrl' => 'https://example.com/failure' 154 | ]], 155 | 'Invalid callbackUrl with dot' => [[ 156 | 'orderId' => 'ORD123', 157 | 'description' => 'Test order', 158 | 'receiveAmount' => '500.23', 159 | 'receiveCurrencyCode' => 'EUR', 160 | 'callbackUrl' => 'http://example.', 161 | 'successUrl' => 'https://example.com/success', 162 | 'failureUrl' => 'https://example.com/failure' 163 | ]], 164 | 'Invalid successUrl with double dot in domain' => [[ 165 | 'orderId' => 'ORD123', 166 | 'description' => 'Test order', 167 | 'receiveAmount' => '500.23', 168 | 'receiveCurrencyCode' => 'EUR', 169 | 'callbackUrl' => 'https://example.com/callback', 170 | 'successUrl' => 'https://example..com', 171 | 'failureUrl' => 'https://example.com/failure' 172 | ]], 173 | 'Invalid failureUrl with invalid domain label' => [[ 174 | 'orderId' => 'ORD123', 175 | 'description' => 'Test order', 176 | 'receiveAmount' => '500.23', 177 | 'receiveCurrencyCode' => 'EUR', 178 | 'callbackUrl' => 'https://example.com/callback', 179 | 'successUrl' => 'https://example.com/success', 180 | 'failureUrl' => 'https://-example.com' 181 | ]], 182 | 'Empty callbackUrl' => [[ 183 | 'orderId' => 'ORD123', 184 | 'description' => 'Test order', 185 | 'receiveAmount' => '500.23', 186 | 'receiveCurrencyCode' => 'EUR', 187 | 'callbackUrl' => '', 188 | 'successUrl' => 'https://example.com/success', 189 | 'failureUrl' => 'https://example.com/failure' 190 | ]], 191 | 'Empty successUrl' => [[ 192 | 'orderId' => 'ORD123', 193 | 'description' => 'Test order', 194 | 'receiveAmount' => '500.23', 195 | 'receiveCurrencyCode' => 'EUR', 196 | 'callbackUrl' => 'https://example.com/callback', 197 | 'successUrl' => '', 198 | 'failureUrl' => 'https://example.com/failure' 199 | ]], 200 | 'Empty failureUrl' => [[ 201 | 'orderId' => 'ORD123', 202 | 'description' => 'Test order', 203 | 'receiveAmount' => '500.23', 204 | 'receiveCurrencyCode' => 'EUR', 205 | 'callbackUrl' => 'https://example.com/callback', 206 | 'successUrl' => 'https://example.com/success', 207 | 'failureUrl' => '' 208 | ]], 209 | ]; 210 | } 211 | } 212 | -------------------------------------------------------------------------------- /tests/SCMerchantClient/Http/CreateOrderResponseTest.php: -------------------------------------------------------------------------------- 1 | $createOrderResponse->getPreOrderId(), 25 | 'orderId' => $createOrderResponse->getOrderId(), 26 | 'validUntil' => $createOrderResponse->getValidUntil(), 27 | 'payCurrencyCode' => $createOrderResponse->getPayCurrencyCode(), 28 | 'payNetworkCode' => $createOrderResponse->getPayNetworkCode(), 29 | 'receiveCurrencyCode' => $createOrderResponse->getreceiveCurrencyCode(), 30 | 'payAmount' => $createOrderResponse->getPayAmount(), 31 | 'receiveAmount' => $createOrderResponse->getReceiveAmount(), 32 | 'depositAddress' => $createOrderResponse->getDepositAddress(), 33 | 'memo' => $createOrderResponse->getMemo(), 34 | 'redirectUrl' => $createOrderResponse->getRedirectUrl(), 35 | ]; 36 | $this->assertSame($expected, $proccesed_order_response_array); 37 | } 38 | 39 | public static function validCreateOrderResponseProvider(): array 40 | { 41 | return [ 42 | 'Valid response data' => [ 43 | [ 44 | 'preOrderId' => '07d9469e-aa78-4263-a12b-25da82390de3', 45 | 'orderId' => 'ORD123', 46 | 'validUntil' => '2023-01-01T00:00:00Z', 47 | 'payCurrencyCode' => null, 48 | 'payNetworkCode' => null, 49 | 'receiveCurrencyCode' => 'SOL', 50 | 'payAmount' => null, 51 | 'receiveAmount' => '0.5', 52 | 'depositAddress' => null, 53 | 'memo' => 'test', 54 | 'redirectUrl' => 'https://spectrocoin.com/en/payment/preorder/07d9469e-aa78-4263-a12b-25da82390de3', 55 | ], 56 | [ 57 | 'preOrderId' => '07d9469e-aa78-4263-a12b-25da82390de3', 58 | 'orderId' => 'ORD123', 59 | 'validUntil' => '2023-01-01T00:00:00Z', 60 | 'payCurrencyCode' => null, 61 | 'payNetworkCode' => null, 62 | 'receiveCurrencyCode' => 'SOL', 63 | 'payAmount' => null, 64 | 'receiveAmount' => '0.5', 65 | 'depositAddress' => null, 66 | 'memo' => 'test', 67 | 'redirectUrl' => 'https://spectrocoin.com/en/payment/preorder/07d9469e-aa78-4263-a12b-25da82390de3', 68 | ], 69 | ], 70 | 'Valid response data with no "validUntil", "payCurrencyCode", "payNetworkCode", "payAmount", "depositAddress", "memo"' => [ 71 | [ 72 | 'preOrderId' => '07d9469e-aa78-4263-a12b-25da82390de3', 73 | 'orderId' => 'ORD123', 74 | 'validUntil' => '2023-01-01T00:00:00Z', 75 | 'receiveCurrencyCode' => 'SOL', 76 | 'receiveAmount' => '0.5', 77 | 'redirectUrl' => 'https://spectrocoin.com/en/payment/preorder/07d9469e-aa78-4263-a12b-25da82390de3', 78 | ], 79 | [ 80 | 'preOrderId' => '07d9469e-aa78-4263-a12b-25da82390de3', 81 | 'orderId' => 'ORD123', 82 | 'validUntil' => '2023-01-01T00:00:00Z', 83 | 'payCurrencyCode' => null, 84 | 'payNetworkCode' => null, 85 | 'receiveCurrencyCode' => 'SOL', 86 | 'payAmount' => null, 87 | 'receiveAmount' => '0.5', 88 | 'depositAddress' => null, 89 | 'memo' => null, 90 | 'redirectUrl' => 'https://spectrocoin.com/en/payment/preorder/07d9469e-aa78-4263-a12b-25da82390de3', 91 | ], 92 | ], 93 | 'Valid response data with random order' => [ 94 | [ 95 | 'payCurrencyCode' => null, 96 | 'validUntil' => '2023-01-01T00:00:00Z', 97 | 'payNetworkCode' => null, 98 | 'preOrderId' => '07d9469e-aa78-4263-a12b-25da82390de3', 99 | 'orderId' => 'ORD123', 100 | 'receiveCurrencyCode' => 'SOL', 101 | 'memo' => 'test', 102 | 'redirectUrl' => 'https://spectrocoin.com/en/payment/preorder/07d9469e-aa78-4263-a12b-25da82390de3', 103 | 'receiveAmount' => '0.5', 104 | 'payAmount' => null, 105 | 'depositAddress' => null, 106 | ], 107 | [ 108 | 'preOrderId' => '07d9469e-aa78-4263-a12b-25da82390de3', 109 | 'orderId' => 'ORD123', 110 | 'validUntil' => '2023-01-01T00:00:00Z', 111 | 'payCurrencyCode' => null, 112 | 'payNetworkCode' => null, 113 | 'receiveCurrencyCode' => 'SOL', 114 | 'payAmount' => null, 115 | 'receiveAmount' => '0.5', 116 | 'depositAddress' => null, 117 | 'memo' => 'test', 118 | 'redirectUrl' => 'https://spectrocoin.com/en/payment/preorder/07d9469e-aa78-4263-a12b-25da82390de3', 119 | ], 120 | ], 121 | ]; 122 | } 123 | 124 | 125 | #[DataProvider('invalidCreateOrderResponseProvider')] 126 | #[TestDox('Test CreateOrderResponse initialization with invalid data')] 127 | public function testCreateOrderResponseWithInvalidData(array $order_data): void 128 | { 129 | $this->expectException(InvalidArgumentException::class); 130 | new CreateOrderResponse($order_data); 131 | } 132 | 133 | 134 | public static function invalidCreateOrderResponseProvider(): array 135 | { 136 | return [ 137 | 'No preOrderId' => [[ 138 | 'orderId' => 'ORD123', 139 | 'validUntil' => '2023-01-01T00:00:00Z', 140 | 'payCurrencyCode' => null, 141 | 'payNetworkCode' => null, 142 | 'receiveCurrencyCode' => 'SOL', 143 | 'payAmount' => null, 144 | 'receiveAmount' => '0.5', 145 | 'depositAddress' => null, 146 | 'memo' => null, 147 | 'redirectUrl' => 'https://spectrocoin.com/en/payment/preorder/07d9469e-aa78-4263-a12b-25da82390de3', 148 | ]], 149 | 'No orderId' => [[ 150 | 'preOrderId' => '07d9469e-aa78-4263-a12b-25da82390de3', 151 | 'validUntil' => '2023-01-01T00:00:00Z', 152 | 'payCurrencyCode' => null, 153 | 'payNetworkCode' => null, 154 | 'receiveCurrencyCode' => 'SOL', 155 | 'payAmount' => null, 156 | 'receiveAmount' => '0.5', 157 | 'depositAddress' => null, 158 | 'memo' => null, 159 | 'redirectUrl' => 'https://spectrocoin.com/en/payment/preorder/07d9469e-aa78-4263-a12b-25da82390de3', 160 | ]], 161 | 'receiveCurrencyCode is less than 3 characters (wrong format)' => [[ 162 | 'preOrderId' => '07d9469e-aa78-4263-a12b-25da82390de3', 163 | 'orderId' => 'ORD123', 164 | 'validUntil' => '2023-01-01T00:00:00Z', 165 | 'payCurrencyCode' => null, 166 | 'payNetworkCode' => null, 167 | 'receiveCurrencyCode' => 'SO', 168 | 'payAmount' => null, 169 | 'receiveAmount' => '0.5', 170 | 'depositAddress' => null, 171 | 'memo' => null, 172 | 'redirectUrl' => 'https://spectrocoin.com/en/payment/preorder/07d9469e-aa78-4263-a12b-25da82390de3', 173 | ]], 174 | 'receiveCurrencyCode is more than 3 characters (wrong format)' => [[ 175 | 'preOrderId' => '07d9469e-aa78-4263-a12b-25da82390de3', 176 | 'orderId' => 'ORD123', 177 | 'validUntil' => '2023-01-01T00:00:00Z', 178 | 'payCurrencyCode' => null, 179 | 'payNetworkCode' => null, 180 | 'receiveCurrencyCode' => 'SOLA', 181 | 'payAmount' => null, 182 | 'receiveAmount' => '0.5', 183 | 'depositAddress' => null, 184 | 'memo' => null, 185 | 'redirectUrl' => 'https://spectrocoin.com/en/payment/preorder/07d9469e-aa78-4263-a12b-25da82390de3', 186 | ]], 187 | 'receiveAmount is negative number' => [[ 188 | 'preOrderId' => '07d9469e-aa78-4263-a12b-25da82390de3', 189 | 'orderId' => 'ORD123', 190 | 'validUntil' => '2023-01-01T00:00:00Z', 191 | 'payCurrencyCode' => null, 192 | 'payNetworkCode' => null, 193 | 'receiveCurrencyCode' => 'SOL', 194 | 'payAmount' => null, 195 | 'receiveAmount' => '-1', 196 | 'depositAddress' => null, 197 | 'memo' => null, 198 | 'redirectUrl' => 'https://spectrocoin.com/en/payment/preorder/07d9469e-aa78-4263-a12b-25da82390de3', 199 | ]], 200 | 'receiveAmount is zero' => [[ 201 | 'preOrderId' => '07d9469e-aa78-4263-a12b-25da82390de3', 202 | 'orderId' => 'ORD123', 203 | 'validUntil' => '2023-01-01T00:00:00Z', 204 | 'payCurrencyCode' => null, 205 | 'payNetworkCode' => null, 206 | 'receiveCurrencyCode' => 'SOL', 207 | 'payAmount' => null, 208 | 'receiveAmount' => '0', 209 | 'depositAddress' => null, 210 | 'memo' => null, 211 | 'redirectUrl' => 'https://spectrocoin.com/en/payment/preorder/07d9469e-aa78-4263-a12b-25da82390de3', 212 | ]], 213 | 'redirectUrl with missing TLD' => [[ 214 | 'preOrderId' => '07d9469e-aa78-4263-a12b-25da82390de3', 215 | 'orderId' => 'ORD123', 216 | 'validUntil' => '2023-01-01T00:00:00Z', 217 | 'payCurrencyCode' => null, 218 | 'payNetworkCode' => null, 219 | 'receiveCurrencyCode' => 'SOL', 220 | 'payAmount' => null, 221 | 'receiveAmount' => '10', 222 | 'depositAddress' => null, 223 | 'memo' => null, 224 | 'redirectUrl' => 'https://spectrocoin/en/payment/preorder/07d9469e-aa78-4263-a12b-25da82390de3', 225 | ]], 226 | 'redirectUrl with dot' => [[ 227 | 'preOrderId' => '07d9469e-aa78-4263-a12b-25da82390de3', 228 | 'orderId' => 'ORD123', 229 | 'validUntil' => '2023-01-01T00:00:00Z', 230 | 'payCurrencyCode' => null, 231 | 'payNetworkCode' => null, 232 | 'receiveCurrencyCode' => 'SOL', 233 | 'payAmount' => null, 234 | 'receiveAmount' => '10', 235 | 'depositAddress' => null, 236 | 'memo' => null, 237 | 'redirectUrl' => 'https://spectrocoin./en/payment/preorder/07d9469e-aa78-4263-a12b-25da82390de3', 238 | ]], 239 | 'redirectUrl with double dot' => [[ 240 | 'preOrderId' => '07d9469e-aa78-4263-a12b-25da82390de3', 241 | 'orderId' => 'ORD123', 242 | 'validUntil' => '2023-01-01T00:00:00Z', 243 | 'payCurrencyCode' => null, 244 | 'payNetworkCode' => null, 245 | 'receiveCurrencyCode' => 'SOL', 246 | 'payAmount' => null, 247 | 'receiveAmount' => '10', 248 | 'depositAddress' => null, 249 | 'memo' => null, 250 | 'redirectUrl' => 'https://spectrocoin..com/en/payment/preorder/07d9469e-aa78-4263-a12b-25da82390de3', 251 | ]], 252 | 'redirectUrl with invalid domain label' => [[ 253 | 'preOrderId' => '07d9469e-aa78-4263-a12b-25da82390de3', 254 | 'orderId' => 'ORD123', 255 | 'validUntil' => '2023-01-01T00:00:00Z', 256 | 'payCurrencyCode' => null, 257 | 'payNetworkCode' => null, 258 | 'receiveCurrencyCode' => 'SOL', 259 | 'payAmount' => null, 260 | 'receiveAmount' => '10', 261 | 'depositAddress' => null, 262 | 'memo' => null, 263 | 'redirectUrl' => 'https://-spectrocoin.com/en/payment/preorder/07d9469e-aa78-4263-a12b-25da82390de3', 264 | ]], 265 | 'Empty redirectUrl' => [[ 266 | 'preOrderId' => '07d9469e-aa78-4263-a12b-25da82390de3', 267 | 'orderId' => 'ORD123', 268 | 'validUntil' => '2023-01-01T00:00:00Z', 269 | 'payCurrencyCode' => null, 270 | 'payNetworkCode' => null, 271 | 'receiveCurrencyCode' => 'SOL', 272 | 'payAmount' => null, 273 | 'receiveAmount' => '10', 274 | 'depositAddress' => null, 275 | 'memo' => null, 276 | 'redirectUrl' => '', 277 | ]], 278 | ]; 279 | } 280 | } 281 | -------------------------------------------------------------------------------- /tests/SCMerchantClient/Http/OrderCallbackTest.php: -------------------------------------------------------------------------------- 1 | getValidPayload(); 80 | $payload['sign'] = $this->signPayload($payload); 81 | 82 | $orderCallback = new OrderCallback($payload, self::$tempPublicKeyFile); 83 | $this->assertInstanceOf(OrderCallback::class, $orderCallback); 84 | 85 | $this->assertEquals($payload['userId'], $orderCallback->getUserId()); 86 | $this->assertEquals($payload['merchantApiId'], $orderCallback->getMerchantApiId()); 87 | $this->assertEquals($payload['merchantId'], $orderCallback->getMerchantId()); 88 | $this->assertEquals($payload['apiId'], $orderCallback->getApiId()); 89 | $this->assertEquals($payload['orderId'], $orderCallback->getOrderId()); 90 | $this->assertEquals($payload['payCurrency'], $orderCallback->getPayCurrency()); 91 | $this->assertEquals(Utils::formatCurrency($payload['payAmount']), $orderCallback->getPayAmount()); 92 | $this->assertEquals($payload['receiveCurrency'], $orderCallback->getReceiveCurrency()); 93 | $this->assertEquals(Utils::formatCurrency($payload['receiveAmount']), $orderCallback->getReceiveAmount()); 94 | $this->assertEquals(Utils::formatCurrency($payload['receivedAmount']), $orderCallback->getReceivedAmount()); 95 | $this->assertEquals($payload['description'], $orderCallback->getDescription()); 96 | $this->assertEquals($payload['orderRequestId'], $orderCallback->getOrderRequestId()); 97 | $this->assertEquals($payload['status'], $orderCallback->getStatus()); 98 | $this->assertEquals($payload['sign'], $orderCallback->getSign()); 99 | } 100 | 101 | private function getValidPayload(): array 102 | { 103 | return [ 104 | 'userId' => '1ba2fe21-4f94-4ae1-ba43-ba5e5be11057', 105 | 'merchantApiId' => 'e8fc7ded-0c54-49bd-b598-cec1bfd42ed6', 106 | 'merchantId' => '1387551', 107 | 'apiId' => '101984', 108 | 'orderId' => '291828', 109 | 'payCurrency' => 'SOL', 110 | 'payAmount' => '10', 111 | 'receiveCurrency'=> 'EUR', 112 | 'receiveAmount' => '100', 113 | 'receivedAmount' => '100', 114 | 'description' => 'test', 115 | 'orderRequestId' => '14799205', 116 | 'status' => '3', 117 | ]; 118 | } 119 | 120 | private function signPayload(array $payload): string 121 | { 122 | $data = http_build_query([ 123 | 'merchantId' => $payload['merchantId'], 124 | 'apiId' => $payload['apiId'], 125 | 'orderId' => $payload['orderId'], 126 | 'payCurrency' => $payload['payCurrency'], 127 | 'payAmount' => Utils::formatCurrency($payload['payAmount']), 128 | 'receiveCurrency'=> $payload['receiveCurrency'], 129 | 'receiveAmount' => Utils::formatCurrency($payload['receiveAmount']), 130 | 'receivedAmount' => Utils::formatCurrency($payload['receivedAmount']), 131 | 'description' => $payload['description'], 132 | 'orderRequestId' => $payload['orderRequestId'], 133 | 'status' => $payload['status'], 134 | ]); 135 | $signature = ''; 136 | openssl_sign($data, $signature, self::$testPrivateKey, OPENSSL_ALGO_SHA1); 137 | return base64_encode($signature); 138 | } 139 | 140 | #[TestDox('Test OrderCallback initialization with invalid signature')] 141 | public function testInvalidSignature(): void 142 | { 143 | $payload = $this->getValidPayload(); 144 | $payload['sign'] = 'invalidsignature'; 145 | $this->expectException(\Exception::class); 146 | $this->expectExceptionMessage('Invalid payload signature.'); 147 | new OrderCallback($payload, self::$tempPublicKeyFile); 148 | } 149 | 150 | 151 | #[DataProvider('invalidPayloadProvider')] 152 | #[TestDox('Test OrderCallback with invalid payload: {0}')] 153 | public function testInvalidPayload(array $modifications, string $expectedError): void 154 | { 155 | $payload = $this->getValidPayload(); 156 | foreach ($modifications as $key => $value) { 157 | if ($value === null) { 158 | unset($payload[$key]); 159 | } else { 160 | $payload[$key] = $value; 161 | } 162 | } 163 | 164 | if ( 165 | array_key_exists('payAmount', $modifications) || 166 | array_key_exists('receiveAmount', $modifications) || 167 | array_key_exists('receivedAmount', $modifications) 168 | ) { 169 | $payload['sign'] = 'dummy-signature'; 170 | } else { 171 | $payload['sign'] = $this->signPayload($payload); 172 | } 173 | 174 | $this->expectException(\InvalidArgumentException::class); 175 | $this->expectExceptionMessage($expectedError); 176 | new OrderCallback($payload, self::$tempPublicKeyFile); 177 | } 178 | 179 | public static function invalidPayloadProvider(): array 180 | { 181 | return [ 182 | 'empty userId' => [ 183 | ['userId' => ''], 184 | 'userId is empty' 185 | ], 186 | 'empty merchantApiId' => [ 187 | ['merchantApiId' => ''], 188 | 'merchantApiId is empty' 189 | ], 190 | 'empty merchantId' => [ 191 | ['merchantId' => ''], 192 | 'merchantId is empty' 193 | ], 194 | 'empty apiId' => [ 195 | ['apiId' => ''], 196 | 'apiId is empty' 197 | ], 198 | 'empty orderId' => [ 199 | ['orderId' => ''], 200 | 'orderId is empty' 201 | ], 202 | 'empty status' => [ 203 | ['status' => ''], 204 | 'status is empty' 205 | ], 206 | 'invalid payCurrency (too short)' => [ 207 | ['payCurrency' => 'SO'], 208 | 'payCurrency is not 3 characters long' 209 | ], 210 | 'invalid payCurrency (too long)' => [ 211 | ['payCurrency' => 'SOLX'], 212 | 'payCurrency is not 3 characters long' 213 | ], 214 | 'non-numeric payAmount' => [ 215 | ['payAmount' => 'abc'], 216 | 'The provided amount must be numeric.' 217 | ], 218 | 'zero payAmount' => [ 219 | ['payAmount' => '0'], 220 | 'payAmount is not a valid positive number' 221 | ], 222 | 'negative payAmount' => [ 223 | ['payAmount' => '-5'], 224 | 'payAmount is not a valid positive number' 225 | ], 226 | 'invalid receiveCurrency (too short)' => [ 227 | ['receiveCurrency' => 'EU'], 228 | 'receiveCurrency is not 3 characters long' 229 | ], 230 | 'invalid receiveCurrency (too long)' => [ 231 | ['receiveCurrency' => 'EURO'], 232 | 'receiveCurrency is not 3 characters long' 233 | ], 234 | 'non-numeric receiveAmount' => [ 235 | ['receiveAmount' => 'abc'], 236 | 'The provided amount must be numeric.' 237 | ], 238 | 'zero receiveAmount' => [ 239 | ['receiveAmount' => '0'], 240 | 'receiveAmount is not a valid positive number' 241 | ], 242 | 'negative receiveAmount' => [ 243 | ['receiveAmount' => '-50'], 244 | 'receiveAmount is not a valid positive number' 245 | ], 246 | 'missing receivedAmount' => [ 247 | ['receivedAmount' => null], 248 | 'receivedAmount is not set' 249 | ], 250 | 'non-numeric orderRequestId' => [ 251 | ['orderRequestId' => 'abc'], 252 | 'orderRequestId is not a valid positive number' 253 | ], 254 | 'zero orderRequestId' => [ 255 | ['orderRequestId' => '0'], 256 | 'orderRequestId is not a valid positive number' 257 | ], 258 | 'negative orderRequestId' => [ 259 | ['orderRequestId' => '-10'], 260 | 'orderRequestId is not a valid positive number' 261 | ], 262 | ]; 263 | } 264 | 265 | #[TestDox('Test OrderCallback with multiple validation errors')] 266 | public function testMultipleValidationErrors(): void 267 | { 268 | $payload = $this->getValidPayload(); 269 | $payload['userId'] = ''; 270 | $payload['payCurrency'] = 'XX'; 271 | $payload['payAmount'] = '-10'; 272 | $payload['orderRequestId'] = '0'; 273 | $payload['status'] = ''; 274 | // Sign the modified payload. 275 | $payload['sign'] = $this->signPayload($payload); 276 | $this->expectException(\InvalidArgumentException::class); 277 | try { 278 | new OrderCallback($payload, self::$tempPublicKeyFile); 279 | } catch (\InvalidArgumentException $ex) { 280 | $message = $ex->getMessage(); 281 | $this->assertStringContainsString('userId is empty', $message); 282 | $this->assertStringContainsString('status is empty', $message); 283 | $this->assertStringContainsString('payCurrency is not 3 characters long', $message); 284 | $this->assertStringContainsString('payAmount is not a valid positive number', $message); 285 | $this->assertStringContainsString('orderRequestId is not a valid positive number', $message); 286 | throw $ex; 287 | } 288 | } 289 | } 290 | -------------------------------------------------------------------------------- /tests/SCMerchantClient/SCMerchantClientTest.php: -------------------------------------------------------------------------------- 1 | dotenv = DotenvVault::createImmutable(__DIR__ . '/..', '.env'); 40 | $this->dotenv->safeLoad(); 41 | 42 | $this->project_id = $_SERVER['PROJECT_ID']; 43 | $this->client_id = $_SERVER['CLIENT_ID']; 44 | $this->client_secret = $_SERVER['CLIENT_SECRET']; 45 | 46 | $this->sc_client = new SCMerchantClient($this->project_id, $this->client_id, $this->client_secret); 47 | } 48 | 49 | protected function tearDown(): void 50 | { 51 | parent::tearDown(); 52 | } 53 | 54 | protected function getCachedToken() { 55 | if (self::$cachedToken && $this->sc_client->isTokenValid(self::$cachedToken, time())) { 56 | return self::$cachedToken; 57 | } 58 | self::$cachedToken = $this->sc_client->getAccessToken(); 59 | if (!isset(self::$cachedToken['expires_at'])) { 60 | self::$cachedToken['expires_at'] = time() + self::$cachedToken['expires_in']; 61 | } 62 | return self::$cachedToken; 63 | } 64 | 65 | // createOrder() 66 | #[TestDox('Test createOrder() with valid data')] 67 | public function testCreateOrderValid(): void{ 68 | $order_data = [ 69 | 'orderId' => 'order' . rand(1, 1000), 70 | 'description' => 'Test order', 71 | 'receiveAmount' => '1.00', 72 | 'receiveCurrencyCode' => 'EUR', 73 | 'callbackUrl' => 'https://example.com/callback', 74 | 'successUrl' => 'https://example.com/success', 75 | 'failureUrl' => 'https://example.com/failure', 76 | ]; 77 | $access_token_data = $this->getCachedToken(); 78 | 79 | $response = $this->sc_client->createOrder($order_data, $access_token_data); 80 | $this->assertInstanceOf(CreateOrderResponse::class, $response, 'Response should be an instance of CreateOrderResponse.'); 81 | $this->assertIsString($response->getOrderId(), 'Order ID should be a string.'); 82 | $this->assertNotEmpty($response->getOrderId(), 'Order ID should not be empty.'); 83 | $this->assertIsString($response->getRedirectUrl(), 'Redirect URL should be a string.'); 84 | $this->assertNotEmpty($response->getRedirectUrl(), 'Redirect URL should not be empty.'); 85 | } 86 | 87 | #[DataProvider('invalidCreateOrderDataProvider')] 88 | #[TestDox('Test createOrder() with invalid data')] 89 | public function testCreateOrderWithInvalid(array $order_data, ?array $token_data, string $expectedErrorClass): void { 90 | // Use the cached token if token_data is not provided by the test case. 91 | if ($token_data === null) { 92 | $token_data = $this->getCachedToken(); 93 | } 94 | $response = $this->sc_client->createOrder($order_data, $token_data); 95 | $this->assertInstanceOf($expectedErrorClass, $response, "Expected an instance of {$expectedErrorClass}."); 96 | } 97 | 98 | public static function invalidCreateOrderDataProvider(): array { 99 | return [ 100 | 'Empty order data' => [ 101 | 'order_data' => [], 102 | 'token_data' => null, // use cached token 103 | 'expectedErrorClass' => \SpectroCoin\SCMerchantClient\Exception\GenericError::class, 104 | ], 105 | 'Missing orderId' => [ 106 | 'order_data' => [ 107 | // 'orderId' omitted 108 | 'description' => 'Test order', 109 | 'receiveAmount' => '1.00', 110 | 'receiveCurrencyCode' => 'EUR', 111 | 'callbackUrl' => 'https://example.com/callback', 112 | 'successUrl' => 'https://example.com/success', 113 | 'failureUrl' => 'https://example.com/failure', 114 | ], 115 | 'token_data' => null, 116 | 'expectedErrorClass' => \SpectroCoin\SCMerchantClient\Exception\GenericError::class, 117 | ], 118 | 'Missing description' => [ 119 | 'order_data' => [ 120 | 'orderId' => 'order' . rand(1, 1000), 121 | // 'description' omitted 122 | 'receiveAmount' => '1.00', 123 | 'receiveCurrencyCode' => 'EUR', 124 | 'callbackUrl' => 'https://example.com/callback', 125 | 'successUrl' => 'https://example.com/success', 126 | 'failureUrl' => 'https://example.com/failure', 127 | ], 128 | 'token_data' => null, 129 | 'expectedErrorClass' => \SpectroCoin\SCMerchantClient\Exception\GenericError::class, 130 | ], 131 | 'Missing receiveAmount' => [ 132 | 'order_data' => [ 133 | 'orderId' => 'order' . rand(1, 1000), 134 | 'description' => 'Test order', 135 | // 'receiveAmount' omitted 136 | 'receiveCurrencyCode' => 'EUR', 137 | 'callbackUrl' => 'https://example.com/callback', 138 | 'successUrl' => 'https://example.com/success', 139 | 'failureUrl' => 'https://example.com/failure', 140 | ], 141 | 'token_data' => null, 142 | 'expectedErrorClass' => \SpectroCoin\SCMerchantClient\Exception\GenericError::class, 143 | ], 144 | 'Missing receiveCurrencyCode' => [ 145 | 'order_data' => [ 146 | 'orderId' => 'order' . rand(1, 1000), 147 | 'description' => 'Test order', 148 | 'receiveAmount' => '1.00', 149 | // 'receiveCurrencyCode' omitted 150 | 'callbackUrl' => 'https://example.com/callback', 151 | 'successUrl' => 'https://example.com/success', 152 | 'failureUrl' => 'https://example.com/failure', 153 | ], 154 | 'token_data' => null, 155 | 'expectedErrorClass' => \SpectroCoin\SCMerchantClient\Exception\GenericError::class, 156 | ], 157 | 'Invalid callbackUrl' => [ 158 | 'order_data' => [ 159 | 'orderId' => 'order' . rand(1, 1000), 160 | 'description' => 'Test order', 161 | 'receiveAmount' => '1.00', 162 | 'receiveCurrencyCode' => 'EUR', 163 | 'callbackUrl' => 'not_a_valid_url', 164 | 'successUrl' => 'https://example.com/success', 165 | 'failureUrl' => 'https://example.com/failure', 166 | ], 167 | 'token_data' => null, 168 | 'expectedErrorClass' => \SpectroCoin\SCMerchantClient\Exception\GenericError::class, 169 | ], 170 | 'Invalid successUrl' => [ 171 | 'order_data' => [ 172 | 'orderId' => 'order' . rand(1, 1000), 173 | 'description' => 'Test order', 174 | 'receiveAmount' => '1.00', 175 | 'receiveCurrencyCode' => 'EUR', 176 | 'callbackUrl' => 'https://example.com/callback', 177 | 'successUrl' => 'invalid_url', 178 | 'failureUrl' => 'https://example.com/failure', 179 | ], 180 | 'token_data' => null, 181 | 'expectedErrorClass' => \SpectroCoin\SCMerchantClient\Exception\GenericError::class, 182 | ], 183 | 'Invalid failureUrl' => [ 184 | 'order_data' => [ 185 | 'orderId' => 'order' . rand(1, 1000), 186 | 'description' => 'Test order', 187 | 'receiveAmount' => '1.00', 188 | 'receiveCurrencyCode' => 'EUR', 189 | 'callbackUrl' => 'https://example.com/callback', 190 | 'successUrl' => 'https://example.com/success', 191 | 'failureUrl' => 'invalid_url', 192 | ], 193 | 'token_data' => null, 194 | 'expectedErrorClass' => \SpectroCoin\SCMerchantClient\Exception\GenericError::class, 195 | ], 196 | ]; 197 | } 198 | 199 | 200 | 201 | // getAccessToken() 202 | #[TestDox('Test getAccessToken() with valid data')] 203 | public function testGetAccessTokenValid() 204 | { 205 | $access_token_data = $this->sc_client->getAccessToken(); 206 | $this->assertIsArray($access_token_data, "Response should be array"); 207 | $this->assertArrayHasKey('access_token', $access_token_data, "Has access_token key."); 208 | $this->assertIsString($access_token_data['access_token'], "access_token should be a string."); 209 | $this->assertNotEmpty($access_token_data['access_token'], "access_token should not be empty."); 210 | $this->assertArrayHasKey('expires_in', $access_token_data, "Missing expires_in key."); 211 | $this->assertIsInt($access_token_data['expires_in'], "expires_in should be an integer."); 212 | $this->assertGreaterThan(0, $access_token_data['expires_in'], "expires_in should be greater than 0."); 213 | $this->assertArrayHasKey('token_type', $access_token_data, "Missing token_type key."); 214 | $this->assertSame('bearer', strtolower($access_token_data['token_type']), "token_type should be 'bearer'."); 215 | } 216 | 217 | #[DataProvider('invalidClientCredentialsProvider')] 218 | #[TestDox('Test getAccessToken() with invalid data')] 219 | public function testGetAccessTokenInvalid($client_id, $client_secret): void { 220 | $sc_client = new SCMerchantClient("dummy_project", $client_id, $client_secret); 221 | $response = $sc_client->getAccessToken(); 222 | 223 | $this->assertIsObject($response, 'Response should be an object.'); 224 | 225 | $this->assertInstanceOf(ApiError::class, $response, 'Response should be an instance of ApiError.'); 226 | 227 | $this->assertIsString($response->getMessage(), 'Error message should be a string.'); 228 | $this->assertNotEmpty($response->getMessage(), 'Error message should not be empty.'); 229 | 230 | $this->assertIsInt($response->getCode(), 'Error code should be an integer.'); 231 | 232 | $this->assertSame($response->getCode(), 401); 233 | } 234 | 235 | 236 | public static function invalidClientCredentialsProvider(): array 237 | { 238 | return [ 239 | 'All credentials invalid' => [ 240 | 'dummy_client', 241 | 'dummy_secret', 242 | ], 243 | 'Only client_id is valid' => [ 244 | $_SERVER['CLIENT_ID'], 245 | 'dummy_secret', 246 | ], 247 | 'Only client_secret is valid' => [ 248 | 'dummy_client', 249 | $_SERVER['CLIENT_SECRET'], 250 | ], 251 | ]; 252 | } 253 | 254 | // IsTokenValid 255 | #[DataProvider('validTokenProvider')] 256 | #[TestDox('Test IsTokenValid() with return value as true')] 257 | public function testIsTokenValidReturnsTrue(array $tokenData, int $currentTime): void 258 | { 259 | $client = new SCMerchantClient('dummy_project', 'dummy_client', 'dummy_secret'); 260 | $this->assertTrue($client->isTokenValid($tokenData, $currentTime)); 261 | } 262 | 263 | #[DataProvider('invalidTokenProvider')] 264 | #[TestDox('Test IsTokenValid() with return value as false')] 265 | public function testIsTokenValidReturnsFalse(array $tokenData, int $currentTime): void 266 | { 267 | $client = new SCMerchantClient('dummy_project', 'dummy_client', 'dummy_secret'); 268 | $this->assertFalse($client->isTokenValid($tokenData, $currentTime)); 269 | } 270 | 271 | public static function validTokenProvider(): array 272 | { 273 | return [ 274 | 'Valid token (expires in future)' => [ 275 | ['expires_at' => time() + 100], 276 | time(), 277 | ], 278 | ]; 279 | } 280 | 281 | public static function invalidTokenProvider(): array 282 | { 283 | return [ 284 | 'Token expires now' => [ 285 | ['expires_at' => time()], 286 | time(), 287 | ], 288 | 'Token expired (past)' => [ 289 | ['expires_at' => time() - 100], 290 | time(), 291 | ], 292 | 'Missing expires_at key' => [ 293 | [], 294 | time(), 295 | ], 296 | 'Null expires_at' => [ 297 | ['expires_at' => null], 298 | time(), 299 | ], 300 | ]; 301 | } 302 | 303 | /** 304 | * Inject a custom HTTP client into the SCMerchantClient instance. 305 | * 306 | * @param SCMerchantClient $client 307 | * @param \GuzzleHttp\Client $httpClient 308 | */ 309 | private function setHttpClient(SCMerchantClient $client, \GuzzleHttp\Client $httpClient): void 310 | { 311 | $reflection = new \ReflectionClass($client); 312 | $property = $reflection->getProperty('http_client'); 313 | $property->setAccessible(true); 314 | $property->setValue($client, $httpClient); 315 | } 316 | 317 | #[TestDox('Test createOrder() handles an InvalidArgumentException by returning a GenericError')] 318 | public function testCreateOrderHandlesInvalidArgumentException(): void 319 | { 320 | $client = new SCMerchantClient('dummy_project', 'dummy_client', 'dummy_secret'); 321 | 322 | $order_data = []; 323 | $token_data = ['access_token' => 'dummy_token', 'expires_at' => time() + 100]; 324 | 325 | $response = $client->createOrder($order_data, $token_data); 326 | $this->assertInstanceOf( 327 | \SpectroCoin\SCMerchantClient\Exception\GenericError::class, 328 | $response, 329 | 'Expected GenericError on InvalidArgumentException' 330 | ); 331 | $this->assertStringContainsString("Invalid order creation payload", $response->getMessage()); 332 | } 333 | 334 | #[TestDox('Test createOrder() handles an InvalidArgumentException in HTTP request by returning a GenericError')] 335 | public function testCreateOrderHandlesInvalidArgumentExceptionInHttpRequest(): void 336 | { 337 | $client = new SCMerchantClient('dummy_project', 'dummy_client', 'dummy_secret'); 338 | 339 | $mockHttpClient = $this->createMock(\GuzzleHttp\Client::class); 340 | $mockHttpClient->expects($this->once()) 341 | ->method('request') 342 | ->will($this->throwException(new \InvalidArgumentException("Invalid argument in HTTP request", 123))); 343 | 344 | $this->setHttpClient($client, $mockHttpClient); 345 | 346 | $order_data = [ 347 | 'orderId' => 'order' . rand(1, 1000), 348 | 'description' => 'Test order', 349 | 'receiveAmount' => '1.00', 350 | 'receiveCurrencyCode' => 'EUR', 351 | 'callbackUrl' => 'https://example.com/callback', 352 | 'successUrl' => 'https://example.com/success', 353 | 'failureUrl' => 'https://example.com/failure', 354 | ]; 355 | $token_data = ['access_token' => 'dummy_token', 'expires_at' => time() + 100]; 356 | 357 | $response = $client->createOrder($order_data, $token_data); 358 | 359 | $this->assertInstanceOf( 360 | \SpectroCoin\SCMerchantClient\Exception\GenericError::class, 361 | $response, 362 | 'Expected GenericError when an InvalidArgumentException is thrown during the HTTP request' 363 | ); 364 | $this->assertStringContainsString("Invalid argument in HTTP request", $response->getMessage()); 365 | $this->assertSame(123, $response->getCode()); 366 | } 367 | 368 | 369 | #[TestDox('Test createOrder() handles a RequestException by returning an ApiError')] 370 | public function testCreateOrderHandlesRequestException(): void 371 | { 372 | $client = new SCMerchantClient('dummy_project', 'dummy_client', 'dummy_secret'); 373 | 374 | $mockHttpClient = $this->createMock(\GuzzleHttp\Client::class); 375 | $mockHttpClient->method('request')->will( 376 | $this->throwException(new \GuzzleHttp\Exception\RequestException( 377 | "Request error", 378 | new \GuzzleHttp\Psr7\Request('POST', 'test') 379 | )) 380 | ); 381 | 382 | $this->setHttpClient($client, $mockHttpClient); 383 | 384 | $order_data = [ 385 | 'orderId' => 'order' . rand(1, 1000), 386 | 'description' => 'Test order', 387 | 'receiveAmount' => '1.00', 388 | 'receiveCurrencyCode' => 'EUR', 389 | 'callbackUrl' => 'https://example.com/callback', 390 | 'successUrl' => 'https://example.com/success', 391 | 'failureUrl' => 'https://example.com/failure', 392 | ]; 393 | $token_data = ['access_token' => 'dummy_token', 'expires_at' => time() + 100]; 394 | 395 | $response = $client->createOrder($order_data, $token_data); 396 | $this->assertInstanceOf( 397 | \SpectroCoin\SCMerchantClient\Exception\ApiError::class, 398 | $response, 399 | 'Expected ApiError on RequestException' 400 | ); 401 | $this->assertStringContainsString("Request error", $response->getMessage()); 402 | } 403 | 404 | #[TestDox('Test createOrder() handles a general Exception by returning a GenericError')] 405 | public function testCreateOrderHandlesGeneralException(): void 406 | { 407 | $client = new SCMerchantClient('dummy_project', 'dummy_client', 'dummy_secret'); 408 | 409 | $mockHttpClient = $this->createMock(\GuzzleHttp\Client::class); 410 | $mockHttpClient->method('request')->will( 411 | $this->throwException(new \Exception("General error")) 412 | ); 413 | 414 | $this->setHttpClient($client, $mockHttpClient); 415 | 416 | $order_data = [ 417 | 'orderId' => 'order' . rand(1, 1000), 418 | 'description' => 'Test order', 419 | 'receiveAmount' => '1.00', 420 | 'receiveCurrencyCode' => 'EUR', 421 | 'callbackUrl' => 'https://example.com/callback', 422 | 'successUrl' => 'https://example.com/success', 423 | 'failureUrl' => 'https://example.com/failure', 424 | ]; 425 | $token_data = ['access_token' => 'dummy_token', 'expires_at' => time() + 100]; 426 | 427 | $response = $client->createOrder($order_data, $token_data); 428 | $this->assertInstanceOf( 429 | \SpectroCoin\SCMerchantClient\Exception\GenericError::class, 430 | $response, 431 | 'Expected GenericError on general Exception' 432 | ); 433 | $this->assertStringContainsString("General error", $response->getMessage()); 434 | } 435 | 436 | #[TestDox('Test createOrder() handles invalid JSON response by returning a GenericError')] 437 | public function testCreateOrderHandlesInvalidJsonResponse(): void 438 | { 439 | $client = new SCMerchantClient('dummy_project', 'dummy_client', 'dummy_secret'); 440 | 441 | $responseMock = $this->createMock(\Psr\Http\Message\ResponseInterface::class); 442 | $streamMock = $this->createMock(\Psr\Http\Message\StreamInterface::class); 443 | $streamMock->method('getContents')->willReturn('invalid_json'); 444 | $responseMock->method('getBody')->willReturn($streamMock); 445 | 446 | $mockHttpClient = $this->createMock(\GuzzleHttp\Client::class); 447 | $mockHttpClient->method('request')->willReturn($responseMock); 448 | 449 | $this->setHttpClient($client, $mockHttpClient); 450 | 451 | $order_data = [ 452 | 'orderId' => 'order' . rand(1, 1000), 453 | 'description' => 'Test order', 454 | 'receiveAmount' => '1.00', 455 | 'receiveCurrencyCode' => 'EUR', 456 | 'callbackUrl' => 'https://example.com/callback', 457 | 'successUrl' => 'https://example.com/success', 458 | 'failureUrl' => 'https://example.com/failure', 459 | ]; 460 | $token_data = ['access_token' => 'dummy_token', 'expires_at' => time() + 100]; 461 | 462 | $response = $client->createOrder($order_data, $token_data); 463 | $this->assertInstanceOf( 464 | \SpectroCoin\SCMerchantClient\Exception\GenericError::class, 465 | $response, 466 | 'Expected GenericError when JSON decoding fails' 467 | ); 468 | $this->assertStringContainsString("Failed to parse JSON response", $response->getMessage()); 469 | } 470 | 471 | #[TestDox('Test getAccessToken() handles a RequestException by returning an ApiError')] 472 | public function testGetAccessTokenHandlesRequestException(): void 473 | { 474 | $client = new SCMerchantClient('dummy_project', 'dummy_client', 'dummy_secret'); 475 | 476 | $mockHttpClient = $this->createMock(\GuzzleHttp\Client::class); 477 | $mockHttpClient->method('post')->will( 478 | $this->throwException(new \GuzzleHttp\Exception\RequestException( 479 | "Auth Request error", 480 | new \GuzzleHttp\Psr7\Request('POST', 'test') 481 | )) 482 | ); 483 | 484 | $this->setHttpClient($client, $mockHttpClient); 485 | 486 | $response = $client->getAccessToken(); 487 | $this->assertInstanceOf( 488 | \SpectroCoin\SCMerchantClient\Exception\ApiError::class, 489 | $response, 490 | 'Expected ApiError on RequestException in getAccessToken()' 491 | ); 492 | $this->assertStringContainsString("Auth Request error", $response->getMessage()); 493 | } 494 | 495 | #[TestDox('Test getAccessToken() handles invalid access token response by returning an ApiError')] 496 | public function testGetAccessTokenHandlesInvalidAccessTokenResponse(): void 497 | { 498 | $client = new SCMerchantClient('dummy_project', 'dummy_client', 'dummy_secret'); 499 | 500 | $invalidTokenResponse = json_encode([]); // returns "{}" 501 | 502 | $responseMock = $this->createMock(\Psr\Http\Message\ResponseInterface::class); 503 | $streamMock = $this->createMock(\Psr\Http\Message\StreamInterface::class); 504 | // getAccessToken() casts the response body to string. 505 | $streamMock->method('__toString')->willReturn($invalidTokenResponse); 506 | $responseMock->method('getBody')->willReturn($streamMock); 507 | 508 | $mockHttpClient = $this->createMock(\GuzzleHttp\Client::class); 509 | $mockHttpClient->method('post')->willReturn($responseMock); 510 | 511 | $this->setHttpClient($client, $mockHttpClient); 512 | 513 | $response = $client->getAccessToken(); 514 | $this->assertInstanceOf( 515 | \SpectroCoin\SCMerchantClient\Exception\ApiError::class, 516 | $response, 517 | 'Expected ApiError when access token response is invalid' 518 | ); 519 | $this->assertEquals('Invalid access token response', $response->getMessage()); 520 | } 521 | 522 | #[TestDox('Test createOrder() handles a general Exception thrown by getContents() as GenericError')] 523 | public function testCreateOrderHandlesExceptionInGetContents(): void 524 | { 525 | $client = new SCMerchantClient('dummy_project', 'dummy_client', 'dummy_secret'); 526 | 527 | $streamMock = $this->createMock(\Psr\Http\Message\StreamInterface::class); 528 | $streamMock->method('getContents')->will($this->throwException(new \Exception("Stream error"))); 529 | 530 | $responseMock = $this->createMock(\Psr\Http\Message\ResponseInterface::class); 531 | $responseMock->method('getBody')->willReturn($streamMock); 532 | 533 | $mockHttpClient = $this->createMock(\GuzzleHttp\Client::class); 534 | $mockHttpClient->method('request')->willReturn($responseMock); 535 | 536 | $this->setHttpClient($client, $mockHttpClient); 537 | 538 | $order_data = [ 539 | 'orderId' => 'order' . rand(1, 1000), 540 | 'description' => 'Test order', 541 | 'receiveAmount' => '1.00', 542 | 'receiveCurrencyCode' => 'EUR', 543 | 'callbackUrl' => 'https://example.com/callback', 544 | 'successUrl' => 'https://example.com/success', 545 | 'failureUrl' => 'https://example.com/failure', 546 | ]; 547 | $token_data = ['access_token' => 'dummy_token', 'expires_at' => time() + 100]; 548 | 549 | $response = $client->createOrder($order_data, $token_data); 550 | 551 | $this->assertInstanceOf( 552 | \SpectroCoin\SCMerchantClient\Exception\GenericError::class, 553 | $response, 554 | 'Expected GenericError when an exception is thrown during getContents()' 555 | ); 556 | $this->assertStringContainsString("Stream error", $response->getMessage()); 557 | } 558 | } 559 | -------------------------------------------------------------------------------- /tests/SCMerchantClient/UtilsTest.php: -------------------------------------------------------------------------------- 1 | assertSame($expected, Utils::formatCurrency($input)); 19 | } 20 | 21 | public static function ValidformatCurrencyProvider(): array{ 22 | 23 | return [ 24 | 'no decimals' => [1, '1.0'], 25 | 'one decimal' => [0.1, '0.1'], 26 | 'two decimals' => [0.11, '0.11'], 27 | 'three decimals' => [0.111, '0.111'], 28 | 'four decimals with trailing zeros' => [0.111100000, '0.1111'], 29 | 'more than eight decimals' => [5.000000111, '5.00000011'], 30 | ]; 31 | } 32 | 33 | #[DataProvider('InvalidformatCurrencyProvider')] 34 | #[TestDox('formatCurrency() - Test currency formatting with invalid input')] 35 | public function testFormatCurrencyWithInvalidInput($input): void{ 36 | $this->expectException(\InvalidArgumentException::class); 37 | $this->expectExceptionMessage('The provided amount must be numeric.'); 38 | 39 | Utils::formatCurrency($input); 40 | } 41 | 42 | 43 | public static function invalidFormatCurrencyProvider(): array 44 | { 45 | return [ 46 | 'non-numeric string' => ['abc'], 47 | 'array input' => [[1, 2, 3]], 48 | 'object input' => [new \stdClass()], 49 | 'empty string' => [''], 50 | ]; 51 | } 52 | 53 | // encryptAuthData() and decryptAuthData() roundtrip 54 | 55 | #[DataProvider('validAuthDataProvider')] 56 | #[TestDox('encryptAuthData() & decryptAuthData() - Test data encryption and decryption')] 57 | public function testEncryptDecryptAuthData(string $data, string $encryptionKey, string $expected){ 58 | $encryptedData = Utils::encryptAuthData($data, $encryptionKey); 59 | $decryptedData = Utils::decryptAuthData($encryptedData, $encryptionKey); 60 | 61 | $this->assertSame($expected, $decryptedData); 62 | } 63 | 64 | public static function validAuthDataProvider(): array 65 | { 66 | $testEncryptionKey = 'secretKey123'; 67 | return[ 68 | 'Round-trip with normal text'=>['Hello world!', $testEncryptionKey, 'Hello world!'], 69 | 'Round-trip with an empty string'=>['', $testEncryptionKey, ''], 70 | 'Round-trip with special characters'=>['P@$$w0rd!#%^&', $testEncryptionKey, 'P@$$w0rd!#%^&'], 71 | 'Round-trip with Unicode text'=>['こんにちは世界', $testEncryptionKey, 'こんにちは世界'], 72 | 'Round-trip with a long text'=>['But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?', 73 | $testEncryptionKey, 74 | 'But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?'], 75 | 'Round-trip with numeric string as data'=>['2.50', $testEncryptionKey, '2.50'], 76 | 'Round-trip with encryption key containing special characters'=>['Hello world!', 'spécîålKey!', 'Hello world!'], 77 | 'Round-trip with binary data'=>['\x00\xFF\xFE\xFD', $testEncryptionKey, '\x00\xFF\xFE\xFD'], 78 | ]; 79 | } 80 | 81 | #[TestDox('decryptAuthData() - Test decryption with incorrect key')] 82 | public function testDecryptWithIncorrectKey(): void { 83 | $data = "Sensitive Data"; 84 | $correctKey = "secretKey123"; 85 | $wrongKey = "wrongKey"; 86 | $encrypted = Utils::encryptAuthData($data, $correctKey); 87 | 88 | $this->expectException(\RuntimeException::class); 89 | $this->expectExceptionMessage('Decryption failed: Invalid encryption key or corrupted data.'); 90 | 91 | Utils::decryptAuthData($encrypted, $wrongKey); 92 | } 93 | 94 | #[TestDox('encryptAuthData() - Encrypted output format check')] 95 | public function testEncryptedOutputFormat(): void { 96 | $data = "Hello, World!"; 97 | $encryptionKey = "secretKey123"; 98 | $encrypted = Utils::encryptAuthData($data, $encryptionKey); 99 | $this->assertNotSame($data, $encrypted, "Encrypted data should not equal the plain text."); 100 | 101 | $decoded = base64_decode($encrypted); 102 | 103 | $this->assertStringContainsString('::', $decoded, "Decoded encrypted data should contain the '::' delimiter."); 104 | 105 | $parts = explode('::', $decoded); 106 | $this->assertCount(2, $parts, "Decoded encrypted data should be split into exactly two parts by '::'."); 107 | } 108 | 109 | // sanitizeUrl() 110 | 111 | #[DataProvider('urlDataProvider')] 112 | #[TestDox('sanitizeUrl() - Test URL sanitization')] 113 | public function testSanitizeUrl($url, $expected): void{ 114 | $sanitizedUrl = Utils::sanitizeUrl($url); 115 | $this->assertSame($expected, $sanitizedUrl); 116 | } 117 | 118 | public static function urlDataProvider(): array{ 119 | 120 | return[ 121 | 'Input is null' => [null, null], 122 | 'Valid URL without extraneous characters' => ['https://example.com', 'https://example.com'], 123 | 'Valid URL with leading/trailing whitespace' => [' https://example.com ', 'https://example.com'], 124 | 'URL containing spaces and illegal characters' => ['https://exa mple.com/path?arg=