Created
August 15, 2021 08:31
-
-
Save viettranx/582b43980a9f60d637db6d36c76cfeea to your computer and use it in GitHub Desktop.
VNPay Payment URL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package payment | |
import ( | |
"crypto/sha256" | |
"encoding/hex" | |
"net/http" | |
"sort" | |
"strings" | |
"time" | |
) | |
type Payment struct { | |
OrderInfo string `json:"order_info"` | |
Amount string `json:"amount"` | |
BankCode string `json:"bank_code"` | |
OrderType string `json:"order_type"` | |
VnpUrl string | |
ReturnUrl string | |
IpAddr string | |
SecretKey string | |
TmnCode string | |
} | |
func (pay Payment) GeneratePaymentUrl() string { | |
currentDate := time.Now() | |
m := map[string]string{} | |
m["vnp_Version"] = "2" | |
m["vnp_Command"] = "pay" | |
m["vnp_TmnCode"] = pay.TmnCode | |
m["vnp_Amount"] = pay.Amount + "00" | |
m["vnp_CreateDate"] = currentDate.Format("20060102150405") | |
m["vnp_CurrCode"] = "VND" | |
m["vnp_IpAddr"] = pay.IpAddr | |
m["vnp_Locale"] = "vn" | |
m["vnp_OrderInfo"] = pay.OrderInfo | |
m["vnp_OrderType"] = pay.OrderType | |
m["vnp_ReturnUrl"] = pay.ReturnUrl | |
m["vnp_TxnRef"] = currentDate.Format("150405") | |
m["vnp_BankCode"] = pay.BankCode | |
m["vnp_ExpireDate"] = currentDate.Format("20060102150405") | |
req, _ := http.NewRequest("GET", pay.VnpUrl, nil) | |
q := req.URL.Query() | |
for key := range m { | |
q.Add(key, m[key]) | |
} | |
keys := []string{} | |
for k := range q { | |
keys = append(keys, k) | |
} | |
sort.Strings(keys) | |
qData := "" | |
for _, key := range keys { | |
qData += key + "=" + strings.Join(q[key], "") + "&" | |
} | |
signData := pay.SecretKey + qData | |
lengSignData := len(signData) | |
signData = signData[:lengSignData-1] | |
hash := sha256.New() | |
hash.Write([]byte(signData)) | |
hashed := hex.EncodeToString(hash.Sum(nil)) | |
q.Add("vnp_SecureHashType", "SHA256") | |
q.Add("vnp_SecureHash", hashed) | |
req.URL.RawQuery = q.Encode() | |
return req.URL.String() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment