package wechat
|
|
|
|
import (
|
|
"context"
|
|
"crypto/rsa"
|
|
"crypto/x509"
|
|
"errors"
|
|
"io/ioutil"
|
|
"log"
|
|
|
|
"git.tetele.net/tgo/helper"
|
|
"github.com/wechatpay-apiv3/wechatpay-go/core"
|
|
"github.com/wechatpay-apiv3/wechatpay-go/core/option"
|
|
"github.com/wechatpay-apiv3/wechatpay-go/utils"
|
|
)
|
|
|
|
/**
|
|
* 查询支付情况
|
|
* wx_appid 公众号 appid
|
|
* wx_mch_id 商户号
|
|
* wx_mch_serial_no 支付密钥
|
|
* wx_mch_apiclient_key 商户私钥
|
|
* wx_pay_cert 平台证书
|
|
*/
|
|
func GetPayResult(dbname, order_sn, wx_appid, wx_mch_id, wx_mch_serial_no, wx_mch_apiclient_key, wx_pay_cert string) (bool, map[string]interface{}, error) {
|
|
|
|
var (
|
|
ctx context.Context = context.Background()
|
|
client *core.Client
|
|
)
|
|
|
|
if wx_appid == "" {
|
|
return false, nil, errors.New("没有appid")
|
|
}
|
|
if wx_mch_id == "" {
|
|
return false, nil, errors.New("没有商户号")
|
|
}
|
|
|
|
privateKey, err := utils.LoadPrivateKey(wx_mch_apiclient_key)
|
|
if err != nil {
|
|
log.Println("商户私钥有误:", err)
|
|
return false, nil, errors.New("商户私钥不正确")
|
|
}
|
|
wechatPayCertificate, err := utils.LoadCertificate(wx_pay_cert)
|
|
if err != nil {
|
|
log.Println("平台证书有误:", err)
|
|
return false, nil, errors.New("平台证书不正确")
|
|
}
|
|
client, err = CreatePayClient(ctx, wechatPayCertificate, privateKey, wx_mch_id, wx_mch_serial_no)
|
|
if err != nil {
|
|
log.Println("create pay client error:", err)
|
|
return false, nil, errors.New("构造失败")
|
|
}
|
|
|
|
url := "https://api.mch.weixin.qq.com/v3/pay/transactions/out-trade-no/" + order_sn + "?mchid=" + wx_mch_id
|
|
|
|
ret, err := client.Get(ctx, url)
|
|
|
|
body, err := ioutil.ReadAll(ret.Response.Body)
|
|
|
|
var resp map[string]interface{}
|
|
|
|
err = json.Unmarshal(body, &resp)
|
|
|
|
if err != nil {
|
|
log.Println("json unmarshal error:", err)
|
|
return false, nil, err
|
|
} else {
|
|
if _, exists := resp["trade_state"]; exists {
|
|
if helper.ToStr(resp["trade_state"]) == "SUCCESS" {
|
|
return true, resp, nil
|
|
}
|
|
}
|
|
}
|
|
return false, nil, nil
|
|
}
|
|
|
|
/**
|
|
* 构造支付请求
|
|
* privateKey 商户私钥
|
|
* wechatPayCertificate 平台证书
|
|
* mchID 商户号
|
|
* mchSerialNo 支付密钥
|
|
*/
|
|
func CreatePayClient(ctx context.Context, wechatPayCertificate *x509.Certificate, privateKey *rsa.PrivateKey, mchID, mchSerialNo string) (*core.Client, error) {
|
|
|
|
var client *core.Client
|
|
var err error
|
|
|
|
if wechatPayCertificate != nil {
|
|
|
|
client, err = core.NewClient(
|
|
ctx, option.WithMerchantCredential(mchID, mchSerialNo, privateKey),
|
|
option.WithWechatPayCertificate([]*x509.Certificate{wechatPayCertificate}),
|
|
)
|
|
if err != nil {
|
|
log.Println("创建 Client 失败:", err)
|
|
return nil, err
|
|
}
|
|
} else {
|
|
client, err = core.NewClient(
|
|
ctx, option.WithMerchantCredential(mchID, mchSerialNo, privateKey), option.WithoutValidator(),
|
|
)
|
|
if err != nil {
|
|
log.Println("创建 Client 失败:", err)
|
|
return nil, err
|
|
}
|
|
}
|
|
|
|
return client, nil
|
|
}
|