說明
之前的項目有涉及到支付接口,包括微信和支付寶支付, 現在記錄一下
github地址:Golang-Payment
使用到的庫
- 網上找的微信支付接口代碼 地址,不過我在項目中需要使用到更多的參數,因此改了小部分源碼。如果使用的話還是需要自己實現的。
- 微信需要自己生成二維碼,因此我找了一個二維碼的庫 odeke-em/qr,我稍微修改了一下放在vendor目錄下
注意,我使用了beego,所以可能有beego的語法
代碼有兩個部分
/payment/controller/wxpay.go:
package Payment
import (
"encoding/base64"
"fmt"
"odeke-em/qr"
"os"
"payment/models/Wxpay"
"strconv"
"time"
"github.com/astaxie/beego"
)
type WxpayController struct {
beego.Controller
}
func (this *WxpayController) Native() {
orderNumber := this.Ctx.Input.Param(":id") //獲取訂單號
payAmount := this.GetString("price") //獲取價格
params := make(map[string]interface{})
params["body"] = "****company-" + orderNumber //顯示標題
params["out_trade_no"] = orderNumber
params["total_fee"] = payAmount
params["product_id"] = orderNumber
params["attach"] = "abc" //自定義參數
var modwx Wxpay.UnifyOrderReq
res := modwx.CreateOrder(this.Ctx, params)
this.Data["data"] = res
//拿到數據之后,需要生成二維碼。
this.Data["Image"] = Img(res.Code_url)
this.TplName = "Wxpay/index.tpl"
}
func (this *WxpayController) Notify() {
var notifyReq Wxpay.WXPayNotifyReq
res := notifyReq.WxpayCallback(this.Ctx)
//beego.Debug("res",res)
if res != nil {
//這里可以組織res的數據 處理自己的業務邏輯:
sendData := make(map[string]interface{})
sendData["id"] = res["out_trade_no"]
sendData["trade_no"] = res["transaction_id"]
paid_time, _ := time.Parse("20060102150405", res["time_end"].(string))
paid_timestr := paid_time.Format("2006-01-02 15:04:05")
sendData["paid_time"] = paid_timestr
sendData["payment_type"] = "wxpay"
intfee := res["cash_fee"].(int)
floatfee := float64(intfee)
cashfee := floatfee / 100
sendData["payment_amount"] = strconv.FormatFloat(cashfee, 'f', 2, 32)
//api(sendData)...自己的邏輯處理
//
}
}
func Img(url string) string {
code, err := qr.Encode(url, qr.H)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
imgByte := code.PNG()
str := base64.StdEncoding.EncodeToString(imgByte)
return str
}