說明
之前的項目有涉及到支付接口,包括微信和支付寶支付, 現(xiàn)在記錄一下
github地址:Golang-Payment
使用到的庫
go get github.com/ascoders/alipay
這是github上一個不錯的支付寶接口,一般來說直接import進(jìn)項目就行了,不過我在項目中需要使用到更多的參數(shù),因此改了小部分源碼。
注意,里面用到了beego的庫。
代碼有兩個部分
/payment/controller/alipay.go:
package Payment
import (
"alipay"
"strconv"
"strings"
"github.com/astaxie/beego"
)
type AlipayController struct {
beego.Controller
}
func newClient() *alipay.Client {
return &alipay.Client{
Partner: beego.AppConfig.String("alipartner"), // 合作者ID
Key: beego.AppConfig.String("alikey"), // 合作者私鑰
ReturnUrl: "http://" + beego.AppConfig.String("domainurl") + "/alipay/return", // 同步返回地址
NotifyUrl: "http://" + beego.AppConfig.String("domainurl") + "/alipay/notify", // 網(wǎng)站異步返回地址
Email: beego.AppConfig.String("aliemail"), // 網(wǎng)站賣家郵箱地址
}
}
func (this *AlipayController) Native() {
orderNo := this.GetString("orderNo") //獲取自己的訂單號
schemestr := this.Ctx.Input.Site()
alipayClient := newClient()
fee, _ := strconv.ParseFloat("100.5")//價格轉(zhuǎn)換
ots := alipay.Options{
OrderId: orderNo,
Fee: float32(fee),
NickName: "ricky",
Subject: "某某訂單" + orderNo,
Extra_common_param: schemestr, //加上自己需要用到的參數(shù)
}
form := alipayClient.Form(ots)
res := map[string]interface{}{"form": form}
this.Data["json"] = res
this.ServeJSON()
}
func (this *AlipayController) Return() {
alipayClient := newClient()
result := alipayClient.Return(&this.Controller)
//beego.Debug("notify", result)
if result.Status == 1 { //付款成功,處理訂單
//處理訂單
if result.Extra_common_param != "" {
url := typestr[1] + "/order/detail/" + result.OrderNo
this.Ctx.Redirect(302, url)
}
} else {
res := map[string]interface{}{"msg": "來源驗證失敗"}
this.Data["json"] = res
this.ServeJSON()
}
}
func (this *AlipayController) Notify() {
alipayClient := newClient()
result := alipayClient.Notify(&this.Controller)
timetest := this.GetString("gmt_payment")
if result.Status == 1 { //付款成功,處理訂單
sendData := make(map[string]interface{})
sendData["id"] = result.OrderNo
sendData["trade_no"] = result.TradeNo
sendData["paid_time"] = timetest
sendData["payment_type"] = "alipay"
sendData["payment_amount"] = result.TotalFee
//這里處理自己的業(yè)務(wù)邏輯
if result.Extra_common_param != "" {
//your method 例如修改數(shù)據(jù)庫中訂單的狀態(tài)為付款。。
}
}
}