go语言接入paypalwebhook通知
一、paypal配置
1.登录paypal,进入开发者后台
2、进入app,没有的先创建测试app
3、输入webhook地址,勾选监听事项,创建一个webhook(一个app可以创建多个webhook,适用于一个app对应多个集群的情况)
二、代码
1、接入三方支付包
go get "github.com/plutov/paypal/v4"
2、demo
//paypal异步通知
func (s basicService) PayPalNotify(ctx context.Context, req api.PayNotifyRequest) string {
// 创建client
APIAddress := paypal.APIBaseLive
client, err := paypal.NewClient(s.conf.PayPal.ClientID, s.conf.PayPal.Secret, APIAddress)
if err != nil {
mylog.WithContext(ctx).Error("与PalPay连接失败:" + err.Error())
return FAIL
}
// 获取token
if _, err = client.GetAccessToken(ctx); err != nil {
mylog.WithContext(ctx).Error("Token失败:" + err.Error())
return FAIL
}
signature, err := client.VerifyWebhookSignature(ctx, req.Request, s.conf.PayPal.Webhook)
if err != nil {
mylog.WithContext(ctx).Error("验证WebHook失败(可能是其他区域的支付): " + err.Error())
return FAIL
}
if signature.VerificationStatus != "SUCCESS" {
mylog.WithContext(ctx).Error("WebHook错误或被篡改: " + signature.VerificationStatus)
return FAIL
}
body, err := ioutil.ReadAll(req.Request.Body)
if err != nil {
mylog.WithContext(ctx).Error("读取相应body失败" + err.Error())
return FAIL
}
var hookRes paypal.AnyEvent
err = json.Unmarshal(body, &hookRes)
if err != nil {
mylog.WithContext(ctx).Error(err.Error())
return FAIL
}
mylog.Debug(hookRes.EventType)
mylog.Debug(string(body))
errCode := ""
switch hookRes.EventType {
case paypal.EventCheckoutOrderApproved: //单笔付款
errCode = s.checkoutNotify(ctx, hookRes.Resource)
case "PAYMENT.SALE.COMPLETED": //订阅付费
errCode = s.salePayNotify(ctx, hookRes.Resource)
case "BILLING.SUBSCRIPTION.CANCELLED": //取消订阅
errCode = s.cancelSubNotify(ctx, body)
case "CUSTOMER.DISPUTE.CREATED": //有争议的订单创建(退款)
errCode = s.customerRefundNotify(ctx, body)
case "CUSTOMER.DISPUTE.RESOLVED": //争议已解决
errCode = s.PaymentRefundNotify(ctx, body)
case "PAYMENT.REFUND.DENIED": //退款被驳回
errCode = s.RefundFailNotify(ctx, body)
}
return errCode
}
3、paypal所有事件
https://developer.paypal.com/api/rest/webhooks/event-names/