forked from wechatpay-apiv3/wechatpay-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wechat_pay_credential.go
48 lines (42 loc) · 1.54 KB
/
wechat_pay_credential.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
// Copyright 2021 Tencent Inc. All rights reserved.
// Package credentials 微信支付 API v3 Go SDK 请求报文头 Authorization 信息生成器
package credentials
import (
"context"
"fmt"
"time"
"github.com/eden-w2w/wechatpay-go/core/auth"
"github.com/eden-w2w/wechatpay-go/core/consts"
"github.com/eden-w2w/wechatpay-go/utils"
)
// WechatPayCredentials 微信支付请求报文头 Authorization 信息生成器
type WechatPayCredentials struct {
Signer auth.Signer // 数字签名生成器
}
// GenerateAuthorizationHeader 生成请求报文头中的 Authorization 信息,详见:
// https://wechatpay-api.gitbook.io/wechatpay-api-v3/qian-ming-zhi-nan-1/qian-ming-sheng-cheng
func (c *WechatPayCredentials) GenerateAuthorizationHeader(
ctx context.Context, method, canonicalURL, signBody string,
) (string, error) {
if c.Signer == nil {
return "", fmt.Errorf("you must init WechatPayCredentials with signer")
}
nonce, err := utils.GenerateNonce()
if err != nil {
return "", err
}
timestamp := time.Now().Unix()
message := fmt.Sprintf(consts.SignatureMessageFormat, method, canonicalURL, timestamp, nonce, signBody)
signatureResult, err := c.Signer.Sign(ctx, message)
if err != nil {
return "", err
}
authorization := fmt.Sprintf(
consts.HeaderAuthorizationFormat, c.getAuthorizationType(),
signatureResult.MchID, nonce, timestamp, signatureResult.CertificateSerialNo, signatureResult.Signature,
)
return authorization, nil
}
func (c *WechatPayCredentials) getAuthorizationType() string {
return "WECHATPAY2-" + c.Signer.Algorithm()
}