当前位置:网站首页>gin集成支付宝支付
gin集成支付宝支付
2022-07-04 12:51:00 【.番茄炒蛋】
简介
由于开通支付宝支付需要提交各种各样的资料,这里使用的是沙箱环境,不过跟真正的支付宝都是一样的
代码
config.yaml
app_id: '你的appID'
private_key: '你的私钥'
ali_public_key: '你的阿里公钥'
notify_url: '支付成功回调地址'
return_url: '支付成功跳转地址'
product_code: 'FAST_INSTANT_TRADE_PAY' # 销售产品码,与支付宝签约的产品码名称
sub_ject: '番茄炒蛋' # 订单标题
config
type AliConfig struct {
AppID string `mapstructure:"app_id"`
PrivateKey string `mapstructure:"private_key"`
AliPublicKey string `mapstructure:"ali_public_key"`
NotifyURL string `mapstructure:"notify_url"`
ReturnURL string `mapstructure:"return_url"`
ProductCode string `mapstructure:"product_code"`
Subject string `mapstructure:"sub_ject"`
}
server
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/satori/go.uuid"
"github.com/smartwalle/alipay/v3"
"github.com/spf13/viper"
"go-alipay/config"
"log"
"net/http"
"strings"
)
var (
AliPayClient *alipay.Client
AliPayConfig config.AliConfig
)
func main() {
r := gin.Default()
InitAliConfig()
InitAlipayClient()
r.GET("/ping", Pong)
r.GET("/get/pay", GetPay)
r.POST("/alipay/notify", Notify)
_ = r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}
// InitAliConfig 初始化配置文件
func InitAliConfig() {
v := viper.New()
// 路径必须要写相对路径,相对于项目的路径
v.SetConfigFile("config.yaml")
if err := v.ReadInConfig(); err != nil {
log.Fatalf("读取配置文件失败: %s", err.Error())
}
// 映射到结构体
if err := v.Unmarshal(&AliPayConfig); err != nil {
log.Fatalf("映射结构体失败: %s", err.Error())
}
}
// InitAlipayClient 初始化*alipay.Client
// 生成支付url和回调都需要用,只初始化一次就可以了
func InitAlipayClient() {
var err error
// isProduction - 是否为生产环境,传 false 的时候为沙箱环境,用于开发测试,正式上线的时候需要改为 true
AliPayClient, err = alipay.New(AliPayConfig.AppID, AliPayConfig.PrivateKey, false)
if err != nil {
log.Fatalf("加载alipay.Client失败: %s", err.Error())
}
// 加载支付宝公钥
err = AliPayClient.LoadAliPayPublicKey(AliPayConfig.AliPublicKey)
if err != nil {
log.Fatalf("加载支付宝公钥失败: %s", err.Error())
}
}
// Pong ReturnURL:支付成功后会请求一次这个
func Pong(ctx *gin.Context) {
ctx.JSON(http.StatusOK, gin.H{
"message": "pong",
})
}
// Notify 回调地址: 支付成功后会回调这里;我们可以用来修改订单状态等等
func Notify(ctx *gin.Context) {
noti, err := AliPayClient.GetTradeNotification(ctx.Request)
if err != nil {
log.Println("获取回调信息失败", err.Error())
ctx.Status(http.StatusInternalServerError)
return
}
fmt.Printf("订单号:%s;状态:%s\n", noti.OutTradeNo, noti.TradeStatus)
ctx.String(http.StatusOK, "success")
}
// GetPay 获取支付url
func GetPay(ctx *gin.Context) {
OutTradeNo := fmt.Sprintf("%s", strings.ReplaceAll(uuid.NewV4().String(), "-", ""))
var p = alipay.TradePagePay{
}
p.NotifyURL = AliPayConfig.NotifyURL // 回调地址;用来通知我们支付结果的,好去修改状态
p.ReturnURL = AliPayConfig.ReturnURL // 返回地址;支付成功后,浏览器内跳转地址
p.Subject = AliPayConfig.Subject
p.OutTradeNo = OutTradeNo
p.TotalAmount = "10.00"
p.ProductCode = AliPayConfig.ProductCode
url, err := AliPayClient.TradePagePay(p)
if err != nil {
log.Fatalf("生成支付url失败: %s", err.Error())
}
var payURL = url.String()
log.Printf("订单号:%s创建支付url成功;", OutTradeNo)
ctx.JSON(http.StatusOK, gin.H{
"url": payURL,
})
}
测试
获取支付url
复制返回的url进行支付
ReturnURL
NotifyURL
边栏推荐
- BLOB,TEXT GEOMETRY or JSON column 'xxx' can't have a default value query 问题
- 学内核之三:使用GDB跟踪内核调用链
- 2022 Shandong Province safety officer C certificate examination question bank and online simulation examination
- Qt如何实现打包,实现EXE分享
- R语言使用epiDisplay包的dotplot函数通过点图的形式可视化不同区间数据点的频率、使用by参数指定分组参数可视化不同分组的点图分布
- 奇妙秘境 码蹄集
- gorm 之数据插入(转)
- Programmer anxiety
- 小程序直播 + 电商,想做新零售电商就用它吧!
- Worried about "cutting off gas", Germany is revising the energy security law
猜你喜欢
MySQL 5 installation and modification free
vscode 常用插件汇总
[matlab] summary of conv, filter, conv2, Filter2 and imfilter convolution functions
软件测试之测试评估
Summary of recent days (non-technical article)
学内核之三:使用GDB跟踪内核调用链
Mask wearing detection based on yolov1
TestSuite and testrunner in unittest
MySQL8版本免安装步骤教程
Unittest框架中引入TestFixture
随机推荐
Gorm 读写分离(转)
IP lab monthly resumption · issue 5
Understand chisel language thoroughly 06. Chisel Foundation (III) -- registers and counters
吃透Chisel语言.07.Chisel基础(四)——Bundle和Vec
Understand chisel language thoroughly 12. Chisel project construction, operation and testing (IV) -- chisel test of chisel test
golang fmt.printf()(转)
R语言使用epiDisplay包的followup.plot函数可视化多个ID(病例)监测指标的纵向随访图、使用stress.col参数指定强调线的id子集的颜色(色彩)
How to choose a technology stack for web applications in 2022
读取 Excel 表数据
基于PaddleX的智能零售柜商品识别
The mouse wheel of xshell/bash/zsh and other terminals is garbled (turn)
Huahao Zhongtian sprint Technology Innovation Board: perte annuelle de 280 millions de RMB, projet de collecte de fonds de 1,5 milliard de Beida Pharmaceutical est actionnaire
Understand chisel language thoroughly 09. Chisel project construction, operation and testing (I) -- build and run chisel project with SBT
【Matlab】conv、filter、conv2、filter2和imfilter卷积函数总结
markdown 语法之字体标红
使用默认路由作为指向Internet的路由
IDEA快捷键大全
Detailed explanation of Fisher information quantity detection countermeasure sample code
2022 Shandong Province safety officer C certificate examination question bank and online simulation examination
2022 hoisting machinery command examination simulation 100 questions simulation examination platform operation