75 lines
2.8 KiB
Go
75 lines
2.8 KiB
Go
package main
|
||
|
||
import (
|
||
"context"
|
||
"github.com/wechatpay-apiv3/wechatpay-go/core"
|
||
"github.com/wechatpay-apiv3/wechatpay-go/core/option"
|
||
"github.com/wechatpay-apiv3/wechatpay-go/services/payments/jsapi"
|
||
"github.com/wechatpay-apiv3/wechatpay-go/services/payments/native"
|
||
"github.com/wechatpay-apiv3/wechatpay-go/utils"
|
||
"log"
|
||
)
|
||
|
||
func main() {
|
||
var (
|
||
mchID string = "190000****" // 商户号
|
||
mchCertificateSerialNumber string = "3775B6A45ACD588826D15E583A95F5DD********" // 商户证书序列号
|
||
mchAPIv3Key string = "2ab9****************************" // 商户APIv3密钥
|
||
)
|
||
// 使用 utils 提供的函数从本地文件中加载商户私钥,商户私钥会用来生成请求的签名
|
||
mchPrivateKey, err := utils.LoadPrivateKeyWithPath("/path/to/merchant/apiclient_key.pem")
|
||
if err != nil {
|
||
log.Fatal("load merchant private key error")
|
||
}
|
||
ctx := context.Background()
|
||
// 使用商户私钥等初始化 client,并使它具有自动定时获取微信支付平台证书的能力
|
||
opts := []core.ClientOption{
|
||
option.WithWechatPayAutoAuthCipher(mchID, mchCertificateSerialNumber, mchPrivateKey, mchAPIv3Key),
|
||
}
|
||
client, err := core.NewClient(ctx, opts...)
|
||
if err != nil {
|
||
log.Fatalf("new wechat pay client err:%s", err)
|
||
}
|
||
// 以 Native 支付为例
|
||
svc := native.NativeApiService{Client: client}
|
||
// 发送请求
|
||
resp, result, err := svc.Prepay(ctx,
|
||
native.PrepayRequest{
|
||
Appid: core.String("wxd678efh567hg6787"),
|
||
Mchid: core.String("1900009191"),
|
||
Description: core.String("Image形象店-深圳腾大-QQ公仔"),
|
||
OutTradeNo: core.String("1217752501201407033233368018"),
|
||
Attach: core.String("自定义数据说明"),
|
||
NotifyUrl: core.String("https://www.weixin.qq.com/wxpay/pay.php"),
|
||
Amount: &native.Amount{
|
||
Total: core.Int64(100),
|
||
},
|
||
},
|
||
)
|
||
|
||
// 使用微信扫描 resp.code_url 对应的二维码,即可体验Native支付
|
||
log.Printf("status=%d resp=%s", result.Response.StatusCode, resp)
|
||
|
||
svc1 := jsapi.JsapiApiService{Client: client}
|
||
// 得到prepay_id,以及调起支付所需的参数和签名
|
||
resp1, result, err := svc1.PrepayWithRequestPayment(ctx,
|
||
jsapi.PrepayRequest{
|
||
Appid: core.String("wxd678efh567hg6787"),
|
||
Mchid: core.String("1900009191"),
|
||
Description: core.String("Image形象店-深圳腾大-QQ公仔"),
|
||
OutTradeNo: core.String("1217752501201407033233368018"),
|
||
Attach: core.String("自定义数据说明"),
|
||
NotifyUrl: core.String("https://www.weixin.qq.com/wxpay/pay.php"),
|
||
Amount: &jsapi.Amount{
|
||
Total: core.Int64(100),
|
||
},
|
||
Payer: &jsapi.Payer{
|
||
Openid: core.String("oUpF8uMuAJO_M2pxb1Q9zNjWeS6o"),
|
||
},
|
||
},
|
||
)
|
||
|
||
// 使用微信扫描 resp.code_url 对应的二维码,即可体验Native支付
|
||
log.Printf("status=%d resp=%s", result.Response.StatusCode, resp1)
|
||
}
|