当前位置:网站首页>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


边栏推荐
- ML之shap:基于boston波士顿房价回归预测数据集利用Shap值对LiR线性回归模型实现可解释性案例
- Talk about 10 tips to ensure thread safety
- 实战解惑 | OpenCV中如何提取不规则ROI区域
- STM32F1与STM32CubeIDE编程实例-MAX7219驱动8位7段数码管(基于GPIO)
- Pandora IOT development board learning (RT thread) - Experiment 3 button experiment (learning notes)
- 2022游戏出海实用发行策略
- Some problems and ideas of data embedding point
- Chapter 16 string localization and message Dictionary (2)
- 流行框架:Glide的使用
- 递增的三元子序列[贪心训练]
猜你喜欢

Digi XBee 3 rf: 4 protocols, 3 packages, 10 major functions

按照功能对Boost库进行分类

Scratch Castle Adventure Electronic Society graphical programming scratch grade examination level 3 true questions and answers analysis June 2022

Practical puzzle solving | how to extract irregular ROI regions in opencv

【MySQL从入门到精通】【高级篇】(五)MySQL的SQL语句执行流程

C# wpf 实现截屏框实时截屏功能
![leetcode:6109. Number of people who know the secret [definition of DP]](/img/95/03e2606b249f26db052cf5075041c1.png)
leetcode:6109. Number of people who know the secret [definition of DP]

Leetcode 61: rotating linked list

Test evaluation of software testing

潘多拉 IOT 开发板学习(RT-Thread)—— 实验3 按键实验(学习笔记)
随机推荐
富文本编辑:wangEditor使用教程
LifeCycle
Test process arrangement (3)
Ml: introduction, principle, use method and detailed introduction of classic cases of snap value
Fs4059c is a 5V input boost charging 12.6v1.2a. Inputting a small current to three lithium battery charging chips will not pull it dead. The temperature is 60 ° and 1000-1100ma is recommended
10.(地图数据篇)离线地形数据处理(供Cesium使用)
gin集成支付宝支付
R language uses the mutation function of dplyr package to standardize the specified data column (using mean function and SD function), and calculates the grouping mean of the standardized target varia
Pandora IOT development board learning (RT thread) - Experiment 3 button experiment (learning notes)
Explain of SQL optimization
Leetcode t47: full arrangement II
基于51单片机的超声波测距仪
关于miui12.5 红米k20pro用au或者povo2出现问题的解决办法
为什么图片传输要使用base64编码
Detailed analysis of pytorch's automatic derivation mechanism, pytorch's core magic
Industrial Internet has greater development potential and more industry scenarios
Progress in architecture
卷积神经网络经典论文集合(深度学习分类篇)
scratch古堡历险记 电子学会图形化编程scratch等级考试三级真题和答案解析2022年6月
C # WPF realizes the real-time screen capture function of screen capture box