├── .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 |