微信支付-golang后端处理
一、支付流程
微信开放平台H5支付接入相关链接:https://pay.weixin.qq.com/wiki/doc/api/H5.php?chapter=15_4
相应的支付流程:
二、相关代码
1、统一下单
//首先定义一个UnifyOrderReq用于填入我们要传入的参数。
type UnifyOrderReq struct {
Appid string `xml:"appid"`
Body string `xml:"body"`
Mch_id string `xml:"mch_id"`
Nonce_str string `xml:"nonce_str"`
Notify_url string `xml:"notify_url"`
Trade_type string `xml:"trade_type"`
Spbill_create_ip string `xml:"spbill_create_ip"`
Total_fee int `xml:"total_fee"`
Out_trade_no string `xml:"out_trade_no"`
Sign string `xml:"sign"`
}
//wxpay计算签名的函数
func (o *APIHandler) wxpayCalcSign(mReq map[string]interface{}, key string) (sign string) {
log4go.Debug("wxpayCalcSign()...API KEY:%s", key)
//STEP 1, 对key进行升序排序.
sorted_keys := make([]string, 0)
for k, _ := range mReq {
sorted_keys = append(sorted_keys, k)
}
sort.Strings(sorted_keys)
//STEP2, 对key=value的键值对用&连接起来,略过空值
var signStrings string
for _, k := range sorted_keys {
fmt.Printf("k=%v, v=%v\n", k, mReq[k])
value := fmt.Sprintf("%v", mReq[k])
if value != "" {
signStrings = signStrings + k + "=" + value + "&"
}
}
//STEP3, 在键值对的最后加上key=API_KEY
if key != "" {
signStrings = signStrings + "key=" + key
}
log4go.Debug("wxpayCalcSign()...signStrings:%s", signStrings)
//STEP4, 进行MD5签名并且将所有字符转为大写.
md5Ctx := md5.New()
md5Ctx.Write([]byte(signStrings))
cipherStr := md5Ctx.Sum(nil)
upperSign := strings.ToUpper(hex.EncodeToString(cipherStr))
return upperSign
}
func (o *APIHandler) wxUnifyChargeReq(userId int64, orderNo string) (string, error) {
log4go.Debug("wxUnifyChargeReq()...userId:%d, orderNo:%s", userId, orderNo)
bookOrder, err := o.GetOrderByOrderNoDb(orderNo)
if err != nil {
log4go.Error("wxUnifyChargeReq(): GetOrderByOrderNoDb error.")
return "", err
}
nonceStr := GetRandomString(32)
//请求UnifiedOrder的代码
var yourReq UnifyOrderReq
yourReq.Appid = WX_APP_ID //微信开放平台我们创建出来的app的app id
yourReq.Body = bookOrder.LineNum
yourReq.Mch_id = WX_MCH_ID
yourReq.Nonce_str = nonceStr
yourReq.Notify_url = WX_NOTIFY_URL
yourReq.Trade_type = "APP"
yourReq.Spbill_create_ip = WX_INVOKE_API_IP
yourReq.Total_fee = int(bookOrder.TotalPrice * 100) //单位是分
yourReq.Out_trade_no = orderNo
var m map[string]interface{}
m = make(map[string]interface{}, 0)
m["appid"] = yourReq.Appid
m["body"] = yourReq.Body
m["mch_id"] = yourReq.Mch_id
m["notify_url"] = yourReq.Notify_url
m["trade_type"] = yourReq.Trade_type
m["spbill_create_ip"] = yourReq.Spbill_create_ip
m["total_fee"] = yourReq.Total_fee
m["out_trade_no"] = yourReq.Out_trade_no
m["nonce_str"] = yourReq.Nonce_str
yourReq.Sign = o.wxpayCalcSign(m, WX_PAY_KEY) // 这个是计算wxpay签名的函数上面已贴出
bytes_req, err := xml.Marshal(yourReq)
if err != nil {
log4go.Error("wxUnifyChargeReq(): xml.Marshal error:%s", err)
return "", err
}
str_req := string(bytes_req)
//wxpay的unifiedorder接口需要http body中xmldoc的根节点是<xml></xml>这种,所以这里需要replace一下
str_req = strings.Replace(str_req, "XUnifyOrderReq", "xml", -1)
bytes_req = []byte(str_req)
log4go.Debug("wxUnifyChargeReq()...str_req:%s", str_req)
//发送unified order请求.
req, err := http.NewRequest("POST", WX_UNIFIEDORDER_API, bytes.NewReader(bytes_req))
if err != nil {
log4go.Error("wxUnifyChargeReq(): http.NewRequest error:%s", err)
return "", err
}
req.Header.Set("Accept", "application/xml")
//这里的http header的设置是必须设置的.
req.Header.Set("Content-Type", "application/xml;charset=utf-8")
c := http.Client{}
resp, _err := c.Do(req)
if _err != nil {
log4go.Error("wxUnifyChargeReq(): http.Do error:%s", _err)
return "", err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
retXml := string(body)
log4go.Debug("wxUnifyChargeReq()...retXml:%s", retXml)
if err != nil {
return "", err
}
return retXml, nil
}
2、验签(待续)