├── .gitignore ├── LICENSE ├── README.md ├── go.mod ├── pasargad.go ├── rsa_parser.go ├── rsa_processor.go ├── rsa_signer.go └── types.go /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.exe~ 4 | *.dll 5 | *.so 6 | *.dylib 7 | 8 | # Test binary, built with `go test -c` 9 | *.test 10 | 11 | # Output of the go coverage tool, specifically when used with LiteIDE 12 | *.out 13 | 14 | # Dependency directories (remove the comment below to include it) 15 | # vendor/ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Golang SDK for Pasargad IPG 2 | 3 | Golang SDK for Pasargad Internet Payment Gateway (RESTful API) 4 | 5 | ## Installation 6 | 7 | ```bash 8 | go get -u github.com/pepco-api/golang-rest-sdk 9 | ``` 10 | 11 | ## Usage 12 | - Read API Documentation, [Click Here! (دانلود مستندات کامل درگاه پرداخت)](https://www.pep.co.ir/wp-content/uploads/2019/06/1-__PEP_IPG_REST-13971020.Ver3_.00.pdf) 13 | - Save your private key into an `.xml` file inside your project directory. 14 | 15 | 16 | ## Redirect User to Payment Gateway 17 | ```go 18 | package main 19 | import ( 20 | "fmt" 21 | "github.com/pepco-api/golang-rest-sdk" 22 | ) 23 | 24 | func main() { 25 | // Create an object from PasargadAPI struct 26 | // e.q: pasargadApi := pasargad.PasargadAPI(4412312,123456,"https://pep.co.ir/ipgtest","cert.xml"); 27 | pasargadApi := pasargad.PasargadAPI(YOUR_MERCHANT_CODE, YOUR_TERMINAL_ID, REDIRECT_URL, CERT_FILE_HERE) 28 | request := pasargad.CreatePaymentRequest{ 29 | Amount: 15000, 30 | InvoiceNumber: "4029", 31 | InvoiceDate: "2021/08/17 16:12:00", 32 | //Mobile: "09121231234", // Optional 33 | //Email: "xxxx@xxxx.xxx", // Optional 34 | } 35 | response, err := pasargadApi.Redirect(request) 36 | if err != nil { 37 | fmt.Println(err) 38 | } else { 39 | fmt.Println(response) 40 | } 41 | } 42 | ``` 43 | 44 | This method, will return a `string` like this: 45 | 46 | ``` 47 | // output: 48 | https://pep.shaparak.ir/payment.aspx?n=LySl+5tYkxL5qNMBRthW7DWzV8e3ALnTJUqiCS0V/io= 49 | // Redirect User to the generated URL to make payment 50 | ``` 51 | 52 | ## Checking and Verifying Transaction 53 | After Payment Process, User is going to be returned to your REDIRECT_URL. 54 | 55 | payment gateway is going to answer the payment result with sending below parameters to your redirectURL (as `QueryString` parameters): 56 | - InvoiceNumber (iN field) 57 | - InvoiceDate (iD field) 58 | - TransactionReferenceID (tref field) 59 | 60 | Store this information in a proper data storage and let's check transaction result by sending a check api request to the Bank: 61 | 62 | ```go 63 | package main 64 | import ( 65 | "fmt" 66 | "github.com/pepco-api/golang-rest-sdk" 67 | ) 68 | 69 | func main() { 70 | pasargadApi := pasargad.PasargadAPI(4412312,123456,"https://pep.co.ir/ipgtest","cert.xml"); 71 | request := pasargad.CreateCheckTransactionRequest{ 72 | InvoiceNumber: "4029", 73 | InvoiceDate: "2021/08/17 16:12:00", 74 | TransactionReferenceID: "637648135297288707", // optional 75 | } 76 | response, err := pasargadApi.CheckTransaction(request) 77 | if err != nil { 78 | fmt.Println(err) 79 | } else { 80 | fmt.Println(response) 81 | } 82 | } 83 | ``` 84 | 85 | Successful result: 86 | ```json 87 | { 88 | "TraceNumber": 13, 89 | "ReferenceNumber": 100200300400500, 90 | "TransactionDate": "2021/08/08 11:58:23", 91 | "Action": "1003", 92 | "TransactionReferenceID": "636843820118990203", 93 | "InvoiceNumber": "4029", 94 | "InvoiceDate": "2021/08/08 11:54:03", 95 | "MerchantCode": 100123, 96 | "TerminalCode": 200123, 97 | "Amount": 15000, 98 | "IsSuccess": true, 99 | "Message": " " 100 | } 101 | ``` 102 | Our code will return `CheckTransactionResponse` struct as response or `err` in case of any errors. 103 | 104 | If you got `IsSuccess` with `true` value, so everything is O.K! 105 | 106 | Now, for your successful transaction, you should call `VerifyPayment()` method to keep the money and Bank makes sure the checking process done properly: 107 | 108 | 109 | ```go 110 | package main 111 | import ( 112 | "fmt" 113 | "github.com/pepco-api/golang-rest-sdk" 114 | ) 115 | 116 | func main() { 117 | pasargadApi := pasargad.PasargadAPI(4412312,123456,"https://pep.co.ir/ipgtest","cert.xml"); 118 | request := pasargad.CreateVerifyPaymentRequest{ 119 | Amount: 15000, 120 | InvoiceDate: "2021/08/17 16:12:00",, 121 | InvoiceNumber: "4029", 122 | } 123 | response, err := pasargadApi.VerifyPayment(request) 124 | if err != nil { 125 | fmt.Println(err) 126 | } else { 127 | fmt.Println(response) 128 | } 129 | } 130 | ``` 131 | 132 | 133 | ...and the successful response looks like this response: 134 | ```json 135 | { 136 | "IsSuccess": true, 137 | "Message": " ", 138 | "MaskedCardNumber": "5022-29**-****-2328", 139 | "HashedCardNumber": "2DDB1E270C598677AE328AA37C2970E3075E1DB....", 140 | "ShaparakRefNumber": "100200300400500" 141 | } 142 | ``` 143 | Our code will return `VerifyPaymentResponse` struct as response or `err` in case of any errors. 144 | 145 | ## Payment Refund 146 | If for any reason, you decided to cancel an order in early hours after taking the order (maximum 2 hours later), you can refund the client payment to his/her bank card. 147 | 148 | for this, use `Refund()` method: 149 | 150 | 151 | ```go 152 | package main 153 | import ( 154 | "fmt" 155 | "github.com/pepco-api/golang-rest-sdk" 156 | ) 157 | 158 | func main() { 159 | pasargadApi := pasargad.PasargadAPI(4412312,123456,"https://pep.co.ir/ipgtest","cert.xml"); 160 | request := pasargad.CreateRefundRequest{ 161 | InvoiceDate: "2021/08/17 16:12:00", 162 | InvoiceNumber: "4029", 163 | } 164 | response, err := pasargadApi.Refund(request) 165 | if err != nil { 166 | fmt.Println(err) 167 | } else { 168 | fmt.Println(response) 169 | } 170 | } 171 | ``` 172 | Our code will return `RefundResponse` struct as response or `err` in case of any errors. 173 | 174 | # Support 175 | Please use your credentials to login into [Support Panel](https://my.pep.co.ir) 176 | Contact Author/Maintainer: [Reza Seyf](https://twitter.com/seyfcode) -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/pepco-api/golang-rest-sdk 2 | 3 | go 1.16 4 | -------------------------------------------------------------------------------- /pasargad.go: -------------------------------------------------------------------------------- 1 | package pasargad 2 | 3 | import ( 4 | "bytes" 5 | "encoding/json" 6 | "errors" 7 | "io/ioutil" 8 | "net/http" 9 | "time" 10 | ) 11 | 12 | // The API URLs 13 | const ( 14 | URL_GET_TOKEN = "https://pep.shaparak.ir/Api/v1/Payment/GetToken" 15 | 16 | // Redirect User with token to this URL. 17 | // e.q: https://pep.shaparak.ir/payment.aspx?n=Token 18 | URL_PAYMENT_GATEWAY = "https://pep.shaparak.ir/payment.aspx" 19 | URL_CHECK_TRANSACTION = "https://pep.shaparak.ir/Api/v1/Payment/CheckTransactionResult" 20 | URL_VERIFY_PAYMENT = "https://pep.shaparak.ir/Api/v1/Payment/VerifyPayment" 21 | URL_REFUND = "https://pep.shaparak.ir/Api/v1/Payment/RefundPayment" 22 | ) 23 | 24 | const ACTION_PAYMENT = "1003" 25 | 26 | // The API dateTime format for Pasargad 27 | const dateTimeFormat = "2006/01/02 15:04:05" 28 | 29 | // HTTPClient is HTTP client. 30 | type HTTPClient interface { 31 | Do(req *http.Request) (*http.Response, error) 32 | } 33 | 34 | // PasargadPaymentAPI for rest 35 | type PasargadPaymentAPI struct { 36 | httpClient HTTPClient 37 | merchantCode int64 38 | terminalId int64 39 | redirectUrl string 40 | certificationFile string 41 | sign string 42 | } 43 | 44 | // PasargadAPI creates a new PasargadPaymentAPI instance. 45 | func PasargadAPI(merchantCode int64, terminalId int64, redirectUrl string, certificationFile string) *PasargadPaymentAPI { 46 | return PasargadAPIClient(merchantCode, terminalId, redirectUrl, certificationFile, &http.Client{}) 47 | } 48 | 49 | // PasargadAPIClient creates a new PasargadPaymentAPI instance 50 | // and allows you to pass a http.Client. 51 | func PasargadAPIClient(merchantCode int64, terminalId int64, redirectUrl string, certificationFile string, httpClient HTTPClient) *PasargadPaymentAPI { 52 | return &PasargadPaymentAPI{ 53 | httpClient: httpClient, 54 | merchantCode: merchantCode, 55 | terminalId: terminalId, 56 | redirectUrl: redirectUrl, 57 | certificationFile: certificationFile, 58 | } 59 | } 60 | 61 | // makeRequest is our RequestBuilder object (used in other packages of pepco-api) 62 | func (m *PasargadPaymentAPI) makeRequest(url, method string, body interface{}, resp interface{}) error { 63 | var data []byte 64 | if body != nil { 65 | var err error 66 | data, err = json.Marshal(body) 67 | if err != nil { 68 | return err 69 | } 70 | } 71 | 72 | req, err := http.NewRequest(method, url, bytes.NewReader(data)) 73 | if err != nil { 74 | return err 75 | } 76 | 77 | req.Header.Set("Content-Type", "application/json") 78 | req.Header.Set("Accept", "application/json") 79 | req.Header.Set("Sign", m.sign) 80 | 81 | r, err := m.httpClient.Do(req) 82 | 83 | if err != nil { 84 | return err 85 | } 86 | defer r.Body.Close() 87 | 88 | // From Here -------------------- 89 | respData, err := ioutil.ReadAll(r.Body) 90 | if err != nil { 91 | return err 92 | } 93 | if r.StatusCode != 200 { 94 | var errRes ErrorResponse 95 | err = json.Unmarshal(respData, &errRes) 96 | if err != nil { 97 | return err 98 | } 99 | return errRes 100 | } else if resp != nil { 101 | err = json.Unmarshal(respData, &resp) 102 | if err != nil { 103 | return err 104 | } 105 | } 106 | // To here --------------------- 107 | 108 | return nil 109 | } 110 | 111 | // SetSign sets new key. 112 | func (m *PasargadPaymentAPI) SetSign(sign string) { 113 | m.sign = sign 114 | } 115 | 116 | // Sign Data with RSA key 117 | func (m *PasargadPaymentAPI) signData(body interface{}) error { 118 | var data []byte 119 | if body != nil { 120 | var err error 121 | // Getting Data ready for signing with PKCS1 122 | data, err = json.Marshal(body) 123 | if err != nil { 124 | return err 125 | } 126 | // Convert XML to Public/Private Keys 127 | res, err := m.convertXmlToKey() 128 | if err != nil { 129 | return err 130 | } 131 | // Creating Signer with our private key... 132 | signer, err := NewSigner(res) 133 | if err != nil { 134 | return err 135 | } 136 | 137 | // ...and finally, siging data. 138 | signedMessage, err := signer.SignBase64(data) 139 | if err != nil { 140 | return err 141 | } 142 | m.SetSign(signedMessage) 143 | } 144 | return nil 145 | } 146 | 147 | // Get Current timestamp in Y/m/d H:i:s format 148 | func (m *PasargadPaymentAPI) getTimestamp() string { 149 | now := time.Now() 150 | return now.Format(dateTimeFormat) 151 | } 152 | 153 | // Generate Payment URL 154 | func (m *PasargadPaymentAPI) Redirect(request CreatePaymentRequest) (string, error) { 155 | requestBody := request.GetRedirectRequest() 156 | requestBody.Action = ACTION_PAYMENT 157 | requestBody.MerchantCode = m.merchantCode 158 | requestBody.TerminalCode = m.terminalId 159 | requestBody.RedirectAddress = m.redirectUrl 160 | requestBody.TimeStamp = m.getTimestamp() 161 | 162 | m.signData(requestBody) 163 | var resp RedirectResponse 164 | err := m.makeRequest(URL_GET_TOKEN, "POST", requestBody, &resp) 165 | 166 | if err != nil { 167 | return "", err 168 | } 169 | 170 | if resp.IsSuccess == false { 171 | requestError := errors.New(resp.Message) 172 | return "", requestError 173 | } 174 | // In this stage, we got a successful response from Pasargad IPG 175 | var redirectAddress string = URL_PAYMENT_GATEWAY + "?n=" + resp.Token 176 | return redirectAddress, nil 177 | } 178 | 179 | // CheckTransaction method 180 | func (m *PasargadPaymentAPI) CheckTransaction(request CreateCheckTransactionRequest) (*CheckTransactionResponse, error) { 181 | requestBody := request.GetCheckTransactionRequest() 182 | requestBody.MerchantCode = m.merchantCode 183 | requestBody.TerminalCode = m.terminalId 184 | 185 | m.signData(requestBody) 186 | var resp CheckTransactionResponse 187 | err := m.makeRequest(URL_CHECK_TRANSACTION, "POST", requestBody, &resp) 188 | 189 | if err != nil { 190 | return nil, err 191 | } 192 | 193 | if resp.IsSuccess == false { 194 | requestError := errors.New(resp.Message) 195 | return nil, requestError 196 | } 197 | return &resp, nil 198 | } 199 | 200 | // VerifyPayment method 201 | func (m *PasargadPaymentAPI) VerifyPayment(request CreateVerifyPaymentRequest) (*VerifyPaymentResponse, error) { 202 | requestBody := request.GetVerifyPaymentRequest() 203 | requestBody.MerchantCode = m.merchantCode 204 | requestBody.TerminalCode = m.terminalId 205 | requestBody.TimeStamp = m.getTimestamp() 206 | 207 | m.signData(requestBody) 208 | var resp VerifyPaymentResponse 209 | err := m.makeRequest(URL_VERIFY_PAYMENT, "POST", requestBody, &resp) 210 | 211 | if err != nil { 212 | return nil, err 213 | } 214 | 215 | if resp.IsSuccess == false { 216 | requestError := errors.New(resp.Message) 217 | return nil, requestError 218 | } 219 | return &resp, nil 220 | } 221 | 222 | // Refund method 223 | func (m *PasargadPaymentAPI) Refund(request CreateRefundRequest) (*RefundResponse, error) { 224 | requestBody := request.GetRefundRequest() 225 | requestBody.MerchantCode = m.merchantCode 226 | requestBody.TerminalCode = m.terminalId 227 | requestBody.TimeStamp = m.getTimestamp() 228 | 229 | m.signData(requestBody) 230 | var resp RefundResponse 231 | err := m.makeRequest(URL_REFUND, "POST", requestBody, &resp) 232 | 233 | if err != nil { 234 | return nil, err 235 | } 236 | 237 | if resp.IsSuccess == false { 238 | requestError := errors.New(resp.Message) 239 | return nil, requestError 240 | } 241 | return &resp, nil 242 | } 243 | -------------------------------------------------------------------------------- /rsa_parser.go: -------------------------------------------------------------------------------- 1 | package pasargad 2 | /** 3 | * Thanks to Github User @Aaron0 for go-rsa-sign repository that inspired us: 4 | * @URL: https://github.com/AaronO/go-rsa-sign 5 | */ 6 | import ( 7 | "crypto/rsa" 8 | "crypto/x509" 9 | "encoding/pem" 10 | "fmt" 11 | ) 12 | 13 | func parsePrivateKey(data []byte) (*rsa.PrivateKey, error) { 14 | pemData, err := pemParse(data, "RSA PRIVATE KEY") 15 | if err != nil { 16 | return nil, err 17 | } 18 | 19 | return x509.ParsePKCS1PrivateKey(pemData) 20 | } 21 | 22 | func parsePublicKey(data []byte) (*rsa.PublicKey, error) { 23 | pemData, err := pemParse(data, "PUBLIC KEY") 24 | if err != nil { 25 | return nil, err 26 | } 27 | 28 | keyInterface, err := x509.ParsePKIXPublicKey(pemData) 29 | if err != nil { 30 | return nil, err 31 | } 32 | 33 | pubKey, ok := keyInterface.(*rsa.PublicKey) 34 | if !ok { 35 | return nil, fmt.Errorf("could not cast parsed key to *rsa.PublickKey") 36 | } 37 | 38 | return pubKey, nil 39 | } 40 | 41 | func pemParse(data []byte, pemType string) ([]byte, error) { 42 | block, _ := pem.Decode(data) 43 | if block == nil { 44 | return nil, fmt.Errorf("no PEM block found") 45 | } 46 | if pemType != "" && block.Type != pemType { 47 | return nil, fmt.Errorf("public key's type is '%s', expected '%s'", block.Type, pemType) 48 | } 49 | return block.Bytes, nil 50 | } -------------------------------------------------------------------------------- /rsa_processor.go: -------------------------------------------------------------------------------- 1 | package pasargad 2 | /** 3 | * Thanks to phemmer for the gist: 4 | * https://gist.github.com/phemmer/fea012d087ff65819645 5 | */ 6 | import ( 7 | "crypto/rsa" 8 | "crypto/x509" 9 | "encoding/base64" 10 | "encoding/pem" 11 | "encoding/xml" 12 | "fmt" 13 | "io/ioutil" 14 | "math/big" 15 | ) 16 | 17 | type XMLRSAKey struct { 18 | Modulus string 19 | Exponent string 20 | P string 21 | Q string 22 | DP string 23 | DQ string 24 | InverseQ string 25 | D string 26 | } 27 | 28 | func (m *PasargadPaymentAPI)b64d(str string) []byte { 29 | decoded, err := base64.StdEncoding.DecodeString(str) 30 | if err != nil { 31 | fmt.Println(err) 32 | } 33 | return []byte(decoded) 34 | } 35 | 36 | func (m *PasargadPaymentAPI)b64bigint(str string) *big.Int { 37 | bint := &big.Int{} 38 | bint.SetBytes(m.b64d(str)) 39 | return bint 40 | } 41 | 42 | func (m *PasargadPaymentAPI) convertXmlToKey() (block []byte, err error) { 43 | xmlbs, err := ioutil.ReadFile(m.certificationFile) 44 | if err != nil { 45 | fmt.Println(err) 46 | } 47 | 48 | if decoded, err := base64.StdEncoding.DecodeString(string(xmlbs)); err == nil { 49 | xmlbs = decoded 50 | } 51 | 52 | xrk := XMLRSAKey{} 53 | error := xml.Unmarshal(xmlbs, &xrk) 54 | if error != nil { 55 | fmt.Println(error) 56 | } 57 | key := &rsa.PrivateKey{ 58 | PublicKey: rsa.PublicKey{ 59 | N: m.b64bigint(xrk.Modulus), 60 | E: int(m.b64bigint(xrk.Exponent).Int64()), 61 | }, 62 | D: m.b64bigint(xrk.D), 63 | Primes: []*big.Int{m.b64bigint(xrk.P), m.b64bigint(xrk.Q)}, 64 | Precomputed: rsa.PrecomputedValues{ 65 | Dp: m.b64bigint(xrk.DP), 66 | Dq: m.b64bigint(xrk.DQ), 67 | Qinv: m.b64bigint(xrk.InverseQ), 68 | CRTValues: ([]rsa.CRTValue)(nil), 69 | }, 70 | } 71 | 72 | pemkey := &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)} 73 | block = pem.EncodeToMemory(pemkey) 74 | return block, nil 75 | } 76 | -------------------------------------------------------------------------------- /rsa_signer.go: -------------------------------------------------------------------------------- 1 | package pasargad 2 | /** 3 | * Thanks to Github User @Aaron0 for go-rsa-sign repository that inspired us: 4 | * @URL: https://github.com/AaronO/go-rsa-sign 5 | */ 6 | import ( 7 | "crypto" 8 | "crypto/rand" 9 | "crypto/rsa" 10 | "encoding/base64" 11 | "encoding/hex" 12 | ) 13 | 14 | type Signer struct { 15 | Key *rsa.PrivateKey 16 | } 17 | 18 | func NewSigner(pemKey []byte) (*Signer, error) { 19 | key, err := parsePrivateKey(pemKey) 20 | if err != nil { 21 | return nil, err 22 | } 23 | 24 | return &Signer{key}, nil 25 | } 26 | 27 | func (s *Signer) Sign(data []byte) ([]byte, error) { 28 | hash := crypto.SHA1 29 | h := hash.New() 30 | h.Write(data) 31 | hashed := h.Sum(nil) 32 | 33 | return rsa.SignPKCS1v15(rand.Reader, s.Key, hash, hashed) 34 | } 35 | 36 | func (s *Signer) SignHex(data []byte) (string, error) { 37 | sig, err := s.Sign(data) 38 | if err != nil { 39 | return "", err 40 | } 41 | return hex.EncodeToString(sig), nil 42 | } 43 | 44 | func (s *Signer) SignBase64(data []byte) (string, error) { 45 | sig, err := s.Sign(data) 46 | if err != nil { 47 | return "", err 48 | } 49 | return base64.StdEncoding.EncodeToString(sig), nil 50 | } 51 | -------------------------------------------------------------------------------- /types.go: -------------------------------------------------------------------------------- 1 | package pasargad 2 | 3 | // General Types ================================================ 4 | // ErrorResponse is the API error response. 5 | type ErrorResponse struct { 6 | IsSuccess bool `json:"IsSuccess"` // status of request (True or False) 7 | Message string `json:"Message"` // Message - The response of server. 8 | } 9 | 10 | // Error returns a formatted error string. 11 | func (m ErrorResponse) Error() string { 12 | return "Error Message: " + m.Message 13 | } 14 | 15 | // Redirect Data Types ========================================== 16 | // CreatePaymentRequest is the format of our data to send to bank 17 | type CreatePaymentRequest struct { 18 | Amount int64 `json:"amount"` // invoice amount 19 | InvoiceNumber string `json:"invoiceNumber"` // invoice number 20 | InvoiceDate string `json:"invoiceDate"` // invoice date 21 | Action string `json:"action"` // request action identifier 22 | Mobile string `json:"mobile"` // mobile number of the user 23 | Email string `json:"email"` // email address of the user 24 | MerchantCode int64 `json:"merchantCode"` // merchant code 25 | TerminalCode int64 `json:"terminalCode"` // terminal code 26 | RedirectAddress string `json:"redirectAddress"` // redirect url 27 | TimeStamp string `json:"timeStamp"` // Current timestamp (Y/m/d H:i:s) 28 | } 29 | 30 | // Get Redirect Request and it's parameters 31 | func (m *CreatePaymentRequest) GetRedirectRequest() CreatePaymentRequest { 32 | return CreatePaymentRequest{ 33 | Amount: m.Amount, 34 | InvoiceNumber: m.InvoiceNumber, 35 | InvoiceDate: m.InvoiceDate, 36 | Mobile: m.Mobile, 37 | Email: m.Email, 38 | Action: m.Action, 39 | MerchantCode: m.MerchantCode, 40 | TerminalCode: m.TerminalCode, 41 | RedirectAddress: m.RedirectAddress, 42 | TimeStamp: m.TimeStamp, 43 | } 44 | } 45 | 46 | // RedirectResponse data type 47 | type RedirectResponse struct { 48 | IsSuccess bool `json:"IsSuccess"` // status of request (True or False) 49 | Message string `json:"Message"` // Message - The response of server 50 | Token string `json:"Token"` // Token (for successful requests) 51 | } 52 | 53 | // Check Transaction Data Types =================================================== 54 | // CreateCheckTransactionRequest is the struct to create a checkTransaction request 55 | type CreateCheckTransactionRequest struct { 56 | TransactionReferenceID string `json:"transactionReferenceID"` // transaction reference id 57 | InvoiceNumber string `json:"invoiceNumber"` // invoice number 58 | InvoiceDate string `json:"invoiceDate"` // invoice date 59 | TerminalCode int64 `json:"terminalCode"` // terminal code 60 | MerchantCode int64 `json:"merchantCode"` // merchant code 61 | } 62 | 63 | // GetCheckTransactionRequest and parameters 64 | func (m *CreateCheckTransactionRequest) GetCheckTransactionRequest() CreateCheckTransactionRequest { 65 | return CreateCheckTransactionRequest{ 66 | InvoiceNumber: m.InvoiceNumber, 67 | InvoiceDate: m.InvoiceDate, 68 | TransactionReferenceID: m.TransactionReferenceID, 69 | MerchantCode: m.MerchantCode, 70 | TerminalCode: m.TerminalCode, 71 | } 72 | } 73 | 74 | // RedirectResponse data type 75 | type CheckTransactionResponse struct { 76 | IsSuccess bool `json:"IsSuccess"` // status of request (True or False) 77 | Message string `json:"Message"` // Message - The response of server 78 | ReferenceNumber int64 `json:"ReferenceNumber"` // Reference number 79 | TraceNumber int64 `json:"TraceNumber"` // trace number 80 | TransactionDate string `json:"TransactionDate"` // transaction date 81 | Action string `json:"Action"` // action identifier 82 | TransactionReferenceID string `json:"TransactionReferenceID"` // transaaction internal reference id 83 | InvoiceNumber string `json:"InvoiceNumber"` // invoice number 84 | InvoiceDate string `json:"InvoiceDate"` // invoice date 85 | MerchantCode int64 `json:"MerchantCode"` // merchant code 86 | TerminalCode int64 `json:"TerminalCode"` // terminal code 87 | Amount int64 `json:"amount"` // transaction amount 88 | } 89 | 90 | // Verify Payment Data Types ================================================ 91 | // CreateVerifyPaymentRequest is the struct to create a VerifyPayment request 92 | type CreateVerifyPaymentRequest struct { 93 | Amount int64 `json:"amount"` // invoice amount 94 | InvoiceNumber string `json:"invoiceNumber"` // invoice number 95 | InvoiceDate string `json:"invoiceDate"` // invoice date 96 | TerminalCode int64 `json:"terminalCode"` // terminal code 97 | MerchantCode int64 `json:"merchantCode"` // merchant code 98 | TimeStamp string `json:"timeStamp"` // Current timestamp (Y/m/d H:i:s) 99 | } 100 | 101 | // GetVerifyPaymentRequest and parameters 102 | func (m *CreateVerifyPaymentRequest) GetVerifyPaymentRequest() CreateVerifyPaymentRequest { 103 | return CreateVerifyPaymentRequest{ 104 | Amount: m.Amount, 105 | InvoiceNumber: m.InvoiceNumber, 106 | InvoiceDate: m.InvoiceDate, 107 | MerchantCode: m.MerchantCode, 108 | TerminalCode: m.TerminalCode, 109 | TimeStamp: m.TimeStamp, 110 | } 111 | } 112 | 113 | // VerifyPaymentResponse 114 | // VerifyPaymentResponse data type 115 | type VerifyPaymentResponse struct { 116 | IsSuccess bool `json:"IsSuccess"` // status of request (True or False) 117 | Message string `json:"Message"` // Message - The response of server 118 | MaskedCardNumber string `json:"MaskedCardNumber"` // Masked Card Number (like: 5022-29**-****-2328) 119 | HashedCardNumber string `json:"HashedCardNumber"` // Hashed Card Number (like: 2DDB1E270C598.....) 120 | ShaparakRefNumber string `json:"ShaparakRefNumber"` // Shaparak Reference ID (like: 100200300400500) 121 | } 122 | 123 | // Refund Data Types ================================================== 124 | // CreateRefundRequest is the struct to create a Refund Payment to user 125 | type CreateRefundRequest struct { 126 | InvoiceNumber string `json:"invoiceNumber"` // invoice number 127 | InvoiceDate string `json:"invoiceDate"` // invoice date 128 | TerminalCode int64 `json:"terminalCode"` // terminal code 129 | MerchantCode int64 `json:"merchantCode"` // merchant code 130 | TimeStamp string `json:"timeStamp"` // Current timestamp (Y/m/d H:i:s) 131 | } 132 | 133 | // GetRefundRequest and parameters 134 | func (m *CreateRefundRequest) GetRefundRequest() CreateRefundRequest { 135 | return CreateRefundRequest{ 136 | InvoiceNumber: m.InvoiceNumber, 137 | InvoiceDate: m.InvoiceDate, 138 | MerchantCode: m.MerchantCode, 139 | TerminalCode: m.TerminalCode, 140 | TimeStamp: m.TimeStamp, 141 | } 142 | } 143 | 144 | // RefundResponse data type 145 | type RefundResponse struct { 146 | IsSuccess bool `json:"IsSuccess"` // status of request (True or False) 147 | Message string `json:"Message"` // Message - The response of server 148 | } 149 | --------------------------------------------------------------------------------