go-zero实战:让微服务Go起来——7 支付服务(pay

  • 进入服务工作区
1
bash复制代码$ cd mall/service/pay

7.1 生成 pay model 模型

  • 创建 sql 文件
1
bash复制代码$ vim model/pay.sql
  • 编写 sql 文件
1
2
3
4
5
6
7
8
9
10
11
12
13
sql复制代码CREATE TABLE `pay` (
`id` bigint unsigned NOT NULL AUTO_INCREMENT,
`uid` bigint unsigned NOT NULL DEFAULT '0' COMMENT '用户ID',
`oid` bigint unsigned NOT NULL DEFAULT '0' COMMENT '订单ID',
`amount` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '产品金额',
`source` tinyint(3) unsigned NOT NULL DEFAULT '0' COMMENT '支付方式',
`status` tinyint(3) unsigned NOT NULL DEFAULT '0' COMMENT '支付状态',
`create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`update_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `idx_uid` (`uid`),
KEY `idx_oid` (`oid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
  • 运行模板生成命令
1
bash复制代码$ goctl model mysql ddl -src ./model/pay.sql -dir ./model -c

7.2 生成 pay api 服务

  • 创建 api 文件
1
bash复制代码$ vim api/pay.api
  • 编写 api 文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
go复制代码type (
// 支付创建
CreateRequest {
Uid int64 `json:"uid"`
Oid int64 `json:"oid"`
Amount int64 `json:"amount"`
}
CreateResponse {
Id int64 `json:"id"`
}
// 支付创建

// 支付详情
DetailRequest {
Id int64 `json:"id"`
}
DetailResponse {
Id int64 `json:"id"`
Uid int64 `json:"uid"`
Oid int64 `json:"oid"`
Amount int64 `json:"amount"`
Source int64 `json:"source"`
Status int64 `json:"status"`
}
// 支付详情

// 支付回调
CallbackRequest {
Id int64 `json:"id"`
Uid int64 `json:"uid"`
Oid int64 `json:"oid"`
Amount int64 `json:"amount"`
Source int64 `json:"source"`
Status int64 `json:"status"`
}
CallbackResponse {
}
// 支付回调

)

@server(
jwt: Auth
)
service Pay {
@handler Create
post /api/pay/create(CreateRequest) returns (CreateResponse)

@handler Detail
post /api/pay/detail(DetailRequest) returns (DetailResponse)

@handler Callback
post /api/pay/callback(CallbackRequest) returns (CallbackResponse)
}
  • 运行模板生成命令
1
bash复制代码$ goctl api go -api ./api/pay.api -dir ./api

7.3 生成 pay rpc 服务

  • 创建 proto 文件
1
bash复制代码$ vim rpc/pay.proto
  • 编写 proto 文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
protobuf复制代码syntax = "proto3";

package pay;

option go_package = "./pay";

// 支付创建
message CreateRequest {
int64 Uid = 1;
int64 Oid = 2;
int64 Amount = 3;
}
message CreateResponse {
int64 id = 1;
}
// 支付创建

// 支付详情
message DetailRequest {
int64 id = 1;
}
message DetailResponse {
int64 id = 1;
int64 Uid = 2;
int64 Oid = 3;
int64 Amount = 4;
int64 Source = 5;
int64 Status = 6;
}
// 支付详情

// 支付详情
message CallbackRequest {
int64 id = 1;
int64 Uid = 2;
int64 Oid = 3;
int64 Amount = 4;
int64 Source = 5;
int64 Status = 6;
}
message CallbackResponse {
}
// 支付详情


service Pay {
rpc Create(CreateRequest) returns(CreateResponse);
rpc Detail(DetailRequest) returns(DetailResponse);
rpc Callback(CallbackRequest) returns(CallbackResponse);
}
  • 运行模板生成命令
1
bash复制代码$ goctl rpc protoc ./rpc/pay.proto --go_out=./rpc/types --go-grpc_out=./rpc/types --zrpc_out=./rpc

7.4 编写 pay rpc 服务

7.4.1 修改配置文件

  • 修改 pay.yaml 配置文件
1
bash复制代码$ vim rpc/etc/pay.yaml
  • 修改服务监听地址,端口号为0.0.0.0:9003,Etcd 服务配置,Mysql 服务配置,CacheRedis 服务配置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
yaml复制代码Name: pay.rpc
ListenOn: 0.0.0.0:9003

Etcd:
Hosts:
- etcd:2379
Key: pay.rpc

Mysql:
DataSource: root:123456@tcp(mysql:3306)/mall?charset=utf8mb4&parseTime=true&loc=Asia%2FShanghai

CacheRedis:
- Host: redis:6379
Type: node
Pass:

7.4.2 添加 pay model 依赖

  • 添加 Mysql 服务配置,CacheRedis 服务配置的实例化
1
bash复制代码$ vim rpc/internal/config/config.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
go复制代码package config

import (
"github.com/zeromicro/go-zero/core/stores/cache"
"github.com/zeromicro/go-zero/zrpc"
)

type Config struct {
zrpc.RpcServerConf

Mysql struct {
DataSource string
}

CacheRedis cache.CacheConf
}
  • 注册服务上下文 pay model 的依赖
1
bash复制代码$ vim rpc/internal/svc/servicecontext.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
go复制代码package svc

import (
"mall/service/pay/model"
"mall/service/pay/rpc/internal/config"

"github.com/zeromicro/go-zero/core/stores/sqlx"
)

type ServiceContext struct {
Config config.Config

PayModel model.PayModel
}

func NewServiceContext(c config.Config) *ServiceContext {
conn := sqlx.NewMysql(c.Mysql.DataSource)
return &ServiceContext{
Config: c,
PayModel: model.NewPayModel(conn, c.CacheRedis),
}
}

7.4.3 添加 user rpc,order rpc 依赖

  • 添加 user rpc, order rpc 服务配置
1
bash复制代码$ vim rpc/etc/pay.yaml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
yaml复制代码Name: pay.rpc
ListenOn: 0.0.0.0:9003
Etcd:
Hosts:
- etcd:2379
Key: pay.rpc

......

UserRpc:
Etcd:
Hosts:
- etcd:2379
Key: user.rpc

OrderRpc:
Etcd:
Hosts:
- etcd:2379
Key: order.rpc
  • 添加 user rpc, order rpc 服务配置的实例化
1
bash复制代码$ vim rpc/internal/config/config.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
go复制代码package config

import (
"github.com/zeromicro/go-zero/core/stores/cache"
"github.com/zeromicro/go-zero/zrpc"
)

type Config struct {
zrpc.RpcServerConf

Mysql struct {
DataSource string
}

CacheRedis cache.CacheConf

UserRpc zrpc.RpcClientConf
OrderRpc zrpc.RpcClientConf
}
  • 注册服务上下文 user rpc, order rpc 的依赖
1
go复制代码$ vim rpc/internal/svc/servicecontext.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
go复制代码package svc

import (
"mall/service/order/rpc/order"
"mall/service/pay/model"
"mall/service/pay/rpc/internal/config"
"mall/service/user/rpc/user"

"github.com/zeromicro/go-zero/core/stores/sqlx"
"github.com/zeromicro/go-zero/zrpc"
)

type ServiceContext struct {
Config config.Config

PayModel model.PayModel

UserRpc user.User
OrderRpc order.Order
}

func NewServiceContext(c config.Config) *ServiceContext {
conn := sqlx.NewMysql(c.Mysql.DataSource)
return &ServiceContext{
Config: c,
PayModel: model.NewPayModel(conn, c.CacheRedis),
UserRpc: user.NewUser(zrpc.MustNewClient(c.UserRpc)),
OrderRpc: order.NewOrder(zrpc.MustNewClient(c.OrderRpc)),
}
}

7.4.4 添加支付创建逻辑 Create

  • 添加根据 oid 查询订单支付记录 PayModel 方法 FindOneByOid
1
bash复制代码$ vim model/paymodel.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
go复制代码package model

......

var (
cachePayOidPrefix = "cache:pay:oid:"
)

type (
// PayModel is an interface to be customized, add more methods here,
// and implement the added methods in customPayModel.
PayModel interface {
payModel

FindOneByOid(ctx context.Context, oid int64) (*Pay, error)
}

customPayModel struct {
*defaultPayModel
}
)

......

func (m *defaultPayModel) FindOneByOid(ctx context.Context, oid int64) (*Pay, error) {
payOidKey := fmt.Sprintf("%s%v", cachePayOidPrefix, oid)
var resp Pay
err := m.QueryRowCtx(ctx, &resp, payOidKey, func(ctx context.Context, conn sqlx.SqlConn, v interface{}) error {
query := fmt.Sprintf("select %s from %s where `oid` = ? limit 1", payRows, m.table)
return conn.QueryRowCtx(ctx, v, query, oid)
})
switch err {
case nil:
return &resp, nil
case sqlc.ErrNotFound:
return nil, ErrNotFound
default:
return nil, err
}
}

......
  • 添加支付创建逻辑
1
bash复制代码$ vim rpc/internal/logic/createlogic.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
go复制代码package logic

import (
"context"

"mall/service/order/rpc/types/order"
"mall/service/pay/model"
"mall/service/pay/rpc/internal/svc"
"mall/service/pay/rpc/types/pay"
"mall/service/user/rpc/types/user"

"github.com/zeromicro/go-zero/core/logx"
"google.golang.org/grpc/status"
)

type CreateLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}

func NewCreateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateLogic {
return &CreateLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}

func (l *CreateLogic) Create(in *pay.CreateRequest) (*pay.CreateResponse, error) {
// 查询用户是否存在
_, err := l.svcCtx.UserRpc.UserInfo(l.ctx, &user.UserInfoRequest{
Id: in.Uid,
})
if err != nil {
return nil, err
}

// 查询订单是否存在
_, err = l.svcCtx.OrderRpc.Detail(l.ctx, &order.DetailRequest{
Id: in.Oid,
})
if err != nil {
return nil, err
}

// 查询订单是否已经创建支付
_, err = l.svcCtx.PayModel.FindOneByOid(l.ctx, in.Oid)
if err == nil {
return nil, status.Error(100, "订单已创建支付")
}

newPay := model.Pay{
Uid: in.Uid,
Oid: in.Oid,
Amount: in.Amount,
Source: 0,
Status: 0,
}

res, err := l.svcCtx.PayModel.Insert(l.ctx, &newPay)
if err != nil {
return nil, status.Error(500, err.Error())
}

newPay.Id, err = res.LastInsertId()
if err != nil {
return nil, status.Error(500, err.Error())
}

return &pay.CreateResponse{
Id: newPay.Id,
}, nil
}

7.4.5 添加支付详情逻辑 Detail

1
bash复制代码$ vim rpc/internal/logic/detaillogic.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
go复制代码package logic

import (
"context"

"mall/service/pay/model"
"mall/service/pay/rpc/internal/svc"
"mall/service/pay/rpc/types/pay"

"github.com/zeromicro/go-zero/core/logx"
"google.golang.org/grpc/status"
)

type DetailLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}

func NewDetailLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DetailLogic {
return &DetailLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}

func (l *DetailLogic) Detail(in *pay.DetailRequest) (*pay.DetailResponse, error) {
// 查询支付是否存在
res, err := l.svcCtx.PayModel.FindOne(l.ctx, in.Id)
if err != nil {
if err == model.ErrNotFound {
return nil, status.Error(100, "支付不存在")
}
return nil, status.Error(500, err.Error())
}

return &pay.DetailResponse{
Id: res.Id,
Uid: res.Uid,
Oid: res.Oid,
Amount: res.Amount,
Source: res.Source,
Status: res.Status,
}, nil
}

7.4.6 添加支付回调逻辑 Callback

1
bash复制代码$ vim rpc/internal/logic/callbacklogic.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
go复制代码package logic

import (
"context"

"mall/service/order/rpc/types/order"
"mall/service/pay/model"
"mall/service/pay/rpc/internal/svc"
"mall/service/pay/rpc/types/pay"
"mall/service/user/rpc/types/user"

"github.com/zeromicro/go-zero/core/logx"
"google.golang.org/grpc/status"
)

type CallbackLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}

func NewCallbackLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CallbackLogic {
return &CallbackLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}

func (l *CallbackLogic) Callback(in *pay.CallbackRequest) (*pay.CallbackResponse, error) {
// 查询用户是否存在
_, err := l.svcCtx.UserRpc.UserInfo(l.ctx, &user.UserInfoRequest{
Id: in.Uid,
})
if err != nil {
return nil, err
}

// 查询订单是否存在
_, err = l.svcCtx.OrderRpc.Detail(l.ctx, &order.DetailRequest{
Id: in.Oid,
})
if err != nil {
return nil, err
}

// 查询支付是否存在
res, err := l.svcCtx.PayModel.FindOne(l.ctx, in.Id)
if err != nil {
if err == model.ErrNotFound {
return nil, status.Error(100, "支付不存在")
}
return nil, status.Error(500, err.Error())
}
// 支付金额与订单金额不符
if in.Amount != res.Amount {
return nil, status.Error(100, "支付金额与订单金额不符")
}

res.Source = in.Source
res.Status = in.Status

err = l.svcCtx.PayModel.Update(l.ctx, res)
if err != nil {
return nil, status.Error(500, err.Error())
}

// 更新订单支付状态
_, err = l.svcCtx.OrderRpc.Paid(l.ctx, &order.PaidRequest{
Id: in.Oid,
})
if err != nil {
return nil, status.Error(500, err.Error())
}

return &pay.CallbackResponse{}, nil
}

7.5 编写 pay api 服务

7.5.1 修改配置文件

  • 修改 pay.yaml 配置文件
1
bash复制代码$ vim api/etc/pay.yaml
  • 修改服务地址,端口号为0.0.0.0:8003,Mysql 服务配置,CacheRedis 服务配置,Auth 验证配置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
yaml复制代码Name: Pay
Host: 0.0.0.0
Port: 8003

Mysql:
DataSource: root:123456@tcp(mysql:3306)/mall?charset=utf8mb4&parseTime=true&loc=Asia%2FShanghai

CacheRedis:
- Host: redis:6379
Type: node
Pass:

Auth:
AccessSecret: uOvKLmVfztaXGpNYd4Z0I1SiT7MweJhl
AccessExpire: 86400

7.5.2 添加 pay rpc 依赖

  • 添加 pay rpc 服务配置
1
bash复制代码$ vim api/etc/pay.yaml
1
2
3
4
5
6
7
8
9
10
11
yaml复制代码Name: Pay
Host: 0.0.0.0
Port: 8003

......

PayRpc:
Etcd:
Hosts:
- etcd:2379
Key: pay.rpc
  • 添加 pay rpc 服务配置的实例化
1
bash复制代码$ vim api/internal/config/config.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
go复制代码package config

import (
"github.com/zeromicro/go-zero/rest"
"github.com/zeromicro/go-zero/zrpc"
)

type Config struct {
rest.RestConf

Auth struct {
AccessSecret string
AccessExpire int64
}

PayRpc zrpc.RpcClientConf
}
  • 注册服务上下文 pay rpc 的依赖
1
bash复制代码$ vim api/internal/svc/servicecontext.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
go复制代码package svc

import (
"mall/service/pay/api/internal/config"
"mall/service/pay/rpc/pay"

"github.com/zeromicro/go-zero/zrpc"
)

type ServiceContext struct {
Config config.Config

PayRpc pay.Pay
}

func NewServiceContext(c config.Config) *ServiceContext {
return &ServiceContext{
Config: c,
PayRpc: pay.NewPay(zrpc.MustNewClient(c.PayRpc)),
}
}

7.5.3 添加支付创建逻辑 Create

1
bash复制代码$ vim api/internal/logic/createlogic.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
go复制代码package logic

import (
"context"

"mall/service/pay/api/internal/svc"
"mall/service/pay/api/internal/types"
"mall/service/pay/rpc/types/pay"

"github.com/zeromicro/go-zero/core/logx"
)

type CreateLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}

func NewCreateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateLogic {
return &CreateLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}

func (l *CreateLogic) Create(req *types.CreateRequest) (resp *types.CreateResponse, err error) {
res, err := l.svcCtx.PayRpc.Create(l.ctx, &pay.CreateRequest{
Uid: req.Uid,
Oid: req.Oid,
Amount: req.Amount,
})
if err != nil {
return nil, err
}

return &types.CreateResponse{
Id: res.Id,
}, nil
}

7.5.4 添加支付详情逻辑 Detail

1
bash复制代码$ vim api/internal/logic/detaillogic.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
go复制代码package logic

import (
"context"

"mall/service/pay/api/internal/svc"
"mall/service/pay/api/internal/types"
"mall/service/pay/rpc/types/pay"

"github.com/zeromicro/go-zero/core/logx"
)

type DetailLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}

func NewDetailLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DetailLogic {
return &DetailLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}

func (l *DetailLogic) Detail(req *types.DetailRequest) (resp *types.DetailResponse, err error) {
res, err := l.svcCtx.PayRpc.Detail(l.ctx, &pay.DetailRequest{
Id: req.Id,
})
if err != nil {
return nil, err
}

return &types.DetailResponse{
Id: req.Id,
Uid: res.Uid,
Oid: res.Oid,
Amount: res.Amount,
Source: res.Source,
Status: res.Status,
}, nil
}

7.5.5 添加支付回调逻辑 Callback

1
bash复制代码$ vim api/internal/logic/callbacklogic.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
go复制代码package logic

import (
"context"

"mall/service/pay/api/internal/svc"
"mall/service/pay/api/internal/types"
"mall/service/pay/rpc/types/pay"

"github.com/zeromicro/go-zero/core/logx"
)

type CallbackLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}

func NewCallbackLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CallbackLogic {
return &CallbackLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}

func (l *CallbackLogic) Callback(req *types.CallbackRequest) (resp *types.CallbackResponse, err error) {
_, err = l.svcCtx.PayRpc.Callback(l.ctx, &pay.CallbackRequest{
Id: req.Id,
Uid: req.Uid,
Oid: req.Oid,
Amount: req.Amount,
Source: req.Source,
Status: req.Status,
})
if err != nil {
return nil, err
}

return &types.CallbackResponse{}, nil
}

7.6 启动 pay rpc 服务

!提示:启动服务需要在 golang 容器中启动

1
2
3
bash复制代码$ cd mall/service/pay/rpc
$ go run pay.go -f etc/pay.yaml
Starting rpc server at 127.0.0.1:9003...

7.7 启动 pay api 服务

!提示:启动服务需要在 golang 容器中启动

1
2
3
bash复制代码$ cd mall/service/pay/api
$ go run pay.go -f etc/pay.yaml
Starting server at 0.0.0.0:8003...

项目地址:github

上一篇《go-zero实战:让微服务Go起来——6 订单服务(order)》

下一篇《go-zero实战:让微服务Go起来——8 RPC服务 Auth 验证》

本文转载自: 掘金

开发者博客 – 和开发相关的 这里全都有

0%