当前位置:网站首页>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
边栏推荐
- An overview of 2D human posture estimation
- Chapter 17 process memory
- Innovation and development of independent industrial software
- Xcode 异常图片导致ipa包增大问题
- AI and Life Sciences
- 第十六章 字符串本地化和消息字典(二)
- 去除重複字母[貪心+單調棧(用數組+len來維持單調序列)]
- 数据中台概念
- Chapter 16 string localization and message Dictionary (2)
- R language ggplot2 visualization: gganimate package creates animated graph (GIF) and uses anim_ The save function saves the GIF visual animation
猜你喜欢
【MySQL从入门到精通】【高级篇】(四)MySQL权限管理与控制
Test process arrangement (3)
Leetcode T48:旋转图像
nowcoder重排链表
Digi XBee 3 RF: 4个协议,3种封装,10个大功能
Data Lake (13): spark and iceberg integrate DDL operations
按照功能对Boost库进行分类
Ultrasonic distance meter based on 51 single chip microcomputer
NowCoder 反转链表
Innovation and development of independent industrial software
随机推荐
MATLAB中tiledlayout函数使用
Detailed explanation of visual studio debugging methods
商业智能BI财务分析,狭义的财务分析和广义的财务分析有何不同?
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
如何游戏出海代运营、游戏出海代投
Innovation and development of independent industrial software
No servers available for service: xxxx
R language uses the DOTPLOT function of epidisplay package to visualize the frequency of data points in different intervals in the form of point graph, and uses the by parameter to specify the groupin
Transplant tinyplay for imx6q development board QT system
[MySQL from introduction to proficiency] [advanced chapter] (V) SQL statement execution process of MySQL
flink sql-client. SH tutorial
2022游戏出海实用发行策略
Digi XBee 3 rf: 4 protocols, 3 packages, 10 major functions
sql优化之explain
Test process arrangement (2)
LiveData
R language uses dplyr package group_ The by function and the summarize function calculate the mean and standard deviation of the target variables based on the grouped variables
Data Lake (13): spark and iceberg integrate DDL operations
GCC [6] - 4 stages of compilation
Real time data warehouse