当前位置:网站首页>Gin integrated Alipay payment
Gin integrated Alipay payment
2022-07-04 14:29:00 【. fried eggs with tomatoes】
brief introduction
Since opening Alipay payment requires submission of various materials , The sandbox environment is used here , But it's the same as the real Alipay
Alipay open platform sandbox environment
This article code address
Code
config.yaml
app_id: ' Yours appID'
private_key: ' Your private key '
ali_public_key: ' Your Alibaba public key '
notify_url: ' Payment success callback address '
return_url: ' The payment successfully jumps to the address '
product_code: 'FAST_INSTANT_TRADE_PAY' # Sales product code , Name of product code signed with Alipay
sub_ject: ' fried eggs with tomatoes ' # Order title
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 Initialize configuration file
func InitAliConfig() {
v := viper.New()
// Path must write relative path , Relative to the path of the project
v.SetConfigFile("config.yaml")
if err := v.ReadInConfig(); err != nil {
log.Fatalf(" Failed to read configuration file : %s", err.Error())
}
// Map to structure
if err := v.Unmarshal(&AliPayConfig); err != nil {
log.Fatalf(" Mapping structure failed : %s", err.Error())
}
}
// InitAlipayClient initialization *alipay.Client
// Generate payment url And callback both need , Just initialize once
func InitAlipayClient() {
var err error
// isProduction - Whether it is a production environment , Pass on false When it comes to sandbox environment , For development testing , It needs to be changed to true
AliPayClient, err = alipay.New(AliPayConfig.AppID, AliPayConfig.PrivateKey, false)
if err != nil {
log.Fatalf(" load alipay.Client Failure : %s", err.Error())
}
// Load Alipay public key
err = AliPayClient.LoadAliPayPublicKey(AliPayConfig.AliPublicKey)
if err != nil {
log.Fatalf(" Failed to load Alipay public key : %s", err.Error())
}
}
// Pong ReturnURL: This will be requested once the payment is successful
func Pong(ctx *gin.Context) {
ctx.JSON(http.StatusOK, gin.H{
"message": "pong",
})
}
// Notify token url : After the payment is successful, it will be recalled here ; We can use it to modify the order status and so on
func Notify(ctx *gin.Context) {
noti, err := AliPayClient.GetTradeNotification(ctx.Request)
if err != nil {
log.Println(" Failed to get callback information ", err.Error())
ctx.Status(http.StatusInternalServerError)
return
}
fmt.Printf(" The order number :%s; state :%s\n", noti.OutTradeNo, noti.TradeStatus)
ctx.String(http.StatusOK, "success")
}
// GetPay Get paid url
func GetPay(ctx *gin.Context) {
OutTradeNo := fmt.Sprintf("%s", strings.ReplaceAll(uuid.NewV4().String(), "-", ""))
var p = alipay.TradePagePay{
}
p.NotifyURL = AliPayConfig.NotifyURL // token url ; Used to inform us of the payment results , OK, change the status
p.ReturnURL = AliPayConfig.ReturnURL // The return address ; After successful payment , Jump address in browser
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(" Generate payment url Failure : %s", err.Error())
}
var payURL = url.String()
log.Printf(" The order number :%s Create payment url success ;", OutTradeNo)
ctx.JSON(http.StatusOK, gin.H{
"url": payURL,
})
}
test
Get paid url
Copy the returned url Make payment
ReturnURL
NotifyURL
边栏推荐
- Detailed index of MySQL
- flink sql-client.sh 使用教程
- PyTorch的自动求导机制详细解析,PyTorch的核心魔法
- leetcode:6109. 知道秘密的人数【dp的定义】
- Ruiji takeout notes
- 卷积神经网络经典论文集合(深度学习分类篇)
- No servers available for service: xxxx
- R语言ggplot2可视化:gganimate包创建动态折线图动画(gif)、使用transition_reveal函数在动画中沿给定维度逐步显示数据
- [cloud native] how can I compete with this database?
- Map of mL: Based on Boston house price regression prediction data set, an interpretable case is realized by using the map value to the LIR linear regression model
猜你喜欢
随机推荐
商业智能BI财务分析,狭义的财务分析和广义的财务分析有何不同?
Visual Studio调试方式详解
【MySQL从入门到精通】【高级篇】(五)MySQL的SQL语句执行流程
leetcode:6109. 知道秘密的人数【dp的定义】
架构方面的进步
尊重他人的行为
Leetcode T49: 字母异位词分组
Oppo find N2 product form first exposure: supplement all short boards
R language uses follow up of epidisplay package The plot function visualizes the longitudinal follow-up map of multiple ID (case) monitoring indicators, and uses stress The col parameter specifies the
ARouter的使用
How to operate and invest games on behalf of others at sea
SqlServer函数,存储过程的创建和使用
MySQL triggers
codeforce:C. Sum of Substrings【边界处理 + 贡献思维 + 灵光一现】
[algorithm leetcode] interview question 04.03 Specific depth node linked list (Multilingual Implementation)
Innovation and development of independent industrial software
Map of mL: Based on Boston house price regression prediction data set, an interpretable case of xgboost model using map value
去除重複字母[貪心+單調棧(用數組+len來維持單調序列)]
【MySQL从入门到精通】【高级篇】(四)MySQL权限管理与控制
Leetcode 61: rotating linked list