写点什么

NCF 如何对接三方的功能(五)

作者:MartyZane
  • 2021 年 12 月 13 日
  • 本文字数:5644 字

    阅读完需:约 19 分钟

NCF 如何对接三方的功能(五)

概述

后台的功能中除了增删改查,webapi,之外还有什么功能是必要的呢,那就是对接三方的功能,比如微信支付,支付宝支付,短信等,这里我来说一下 NCF 是如何对接这些三方的


微信的 APP 支付对接

参考文档

微信支付 V2 开发文档:https://pay.weixin.qq.com/wiki/doc/api/index.html

NCF 仓库地址:https://github.com/NeuCharFramework/NCF (要 Star 哦)


步骤

1.下载 NCF

2.创建自己的 XNCF 模块

3.引用 Nuget 包 ML.ThirdParty & ML.Common.SDK

     <ItemGroup>         <PackageReference Include="ML.Common.SDK" Version="1.0.2.8" />         <PackageReference Include="ML.ThirdParty" Version="1.0.2" />     </ItemGroup>
复制代码

4.建立自己的 Controller,并创建接口方法

//引用相关命名空间using ML.Common.SDK;using ML.ThirdParty.Wechat;
复制代码


/// <summary>        /// 微信支付        /// </summary>        /// <param name="openId">用户的微信OpenId</param>        /// <param name="userId">用户Id</param>        /// <param name="body">内容</param>        /// <param name="totalFee">支付的总金额</param>        /// <returns></returns>        [HttpPost]        public async Task<IActionResult> WxPayAsync(string openId,string userId,string body, int totalFee)        {            try            {                //ML 方案                WechatPayHelper wxpay = new WechatPayHelper();                WechatPaymentParam wxpayParam = new WechatPaymentParam();                wxpayParam.appid = "wx2y***********uix6";                wxpayParam.mch_id = "016*****78";                wxpayParam.attach = $"userId={userId};totalFee={totalFee.ToString()}";                wxpayParam.body = body;                wxpayParam.total_fee = totalFee.ToString();                wxpayParam.notify_url = "https://www.weixin.com/api/v1/payment/wxNotifyUrl";                wxpayParam.trade_type = "APP";                wxpayParam.openid = openId;                string strOutTradeNo = "";                var result = wxpay.Payment(wxpayParam, "5hJpKkSa******************LTu9kP", out strOutTradeNo);                SenparcTrace.Log($"result----{result},sign={strOutTradeNo}");                result = result.Replace("<![CDATA[", "").Replace("]]>", "").Replace("\n", "");                DataTable dtWxPayResponse = XMLHelper.XMLToDataTable(result);                var response = dtWxPayResponse.ToJson().Replace("}]", $",\"timestamp\":\"{DateTimeHelper.ConvertToJavaScriptUnix(DateTime.Now)}\"}}]");
MakeCallPaymentParam mcpp = new MakeCallPaymentParam(); mcpp.appid = "wx2y**********duix6"; mcpp.partnerid = "01******78"; mcpp.prepayid = dtWxPayResponse.Rows[0]["prepay_id"].ToString(); mcpp.package = "Sign=WXPay"; mcpp.noncestr = ""; mcpp.timestamp = ""; string strSign = ""; var data = wxpay.MakeCallPayment(mcpp, "5hJpK********************u9kP", out strSign); string rp = XMLHelper.XMLToDataTable(WechatPayHelper.FormatParamToXML(data)).ToJson(); return Success(rp); } catch (Exception ex) { return Fail(ex.Message); } }
复制代码

5.调用代码返回数据给前端

6.前端拿数据吊起支付


支付宝的 APP 支付对接

参考文档

支付宝支付开发文档:https://opendocs.alipay.com/open/204


步骤

1.下载 NCF

2.创建自己的 XNCF 模块

3.引用 Nuget 包 ML.ThirdParty & ML.Common.SDK & AopSdk

     <ItemGroup>         <PackageReference Include="ML.Common.SDK" Version="1.0.2.8" />         <PackageReference Include="ML.ThirdParty" Version="1.0.2" />     </ItemGroup>
复制代码

4.建立自己的 Controller,并创建接口方法

 //引用相关命名空间 using ML.Common.SDK; using ML.ThirdParty.Wechat;
复制代码


/// <summary>/// 支付宝支付/// </summary>/// <param name="amount">金额</param>/// <param name="userId">用户Id</param>/// <returns></returns>[HttpPost]public async Task<IActionResult> AliPaymentAsync(string amount,string userId){    try    {        SenparcTrace.Log($"amount---{amount},userId----{userId}");        PaymentService paymentService = new PaymentService();        var obj = await paymentService.PaymentParam(amount, userId);        return Success(obj);    }    catch (Exception ex)    {        return Fail(ex.Message);    }}
复制代码

5.建立 PaymentService

using Senparc.CO2NET.Trace;using Senparc.Ncf.Core.Enums;using Senparc.Ncf.Repository;using Senparc.Ncf.Service;using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using ML.Xncf.Admin.Models.DatabaseModel;using ML.Xncf.Admin.Models.DatabaseModel.Dto;using Senparc.Ncf.Utility;using Microsoft.EntityFrameworkCore;using System.Text;using ML.Xncf.Admin.Models;using Aop.Api;using Aop.Api.Request;using Aop.Api.Response;using Aop.Api.Util;using Aop.Api.Domain;using System.Web;using ML.Xncf.Admin.Models.DatabaseModel.VO;using ML.Xncf.Admin.Param;
namespace ML.Xncf.Admin.Services{ public class PaymentService { public IAopClient client;
protected const string strPrivateKey = @"bxOYPgAy**********************3hRb4q2qVCuw6p3tJkXwmRLn1zrGvCvZbxOYPgAyIlE94ofz9v75nM20VM5cacea3hRb4q2qVCuw6p3tJkXwmRLn1zrGvCvZbxOYPgAyIlE94ofz9v75nM20VM5cacea3hRb4q2qVCuw6p3tJkXwmRLn1zrGvCvZbxOYPgAyIlE94ofz9v75nM20VM5cacea3hRb4q2qVCuw6p3tJkXwmRLn1zrGvCvZbxOYPgAyIlE94ofz9v75nM20VM5cacea3hRb4q2qVCuw6p3tJkXwmRLn1zrGvCvZbxOYPgAyIlE94ofz9v75nM20VM5cacea3hRb4q2qVCuw6p3tJkXwmRLn1zrGvCvZbxOYPgAyIlE94ofz9v75nM20VM5cacea3hRb4q2qVCuw6p3tJkXwmRLn1zrGvCvZbxOYPgAyIlE94ofz9v75nM20VM5cacea3hRb4q2qVCuw6p3tJkXwmRLn1zrGvCvZbxOYPgAyIlE94ofz9v75nM20VM5cacea3hRb4q2qVCuw6p3tJkXwmRLn1zrGvCvZbxOYPgAyIlE94ofz9v75nM20VM5cacea3hRb4q2qVCuw6p3tJkXwmRLn1zrGvCvZbxOYPgAyIlE94ofz9v75nM20VM5cacea3hRb4q2qVCuw6p3tJkXwmRLn1zrGvCvZbxOYPgAyIlE94ofz9v75nM20VM5cacea3hRb4q2qVCuw6p3tJkXwmRLn1zrGvCvZbxOYPgAyIlE94ofz9v75nM20VM5cacea3hRb4q2qVCuw6p3tJkXwmRLn1zrGvCvZbxOYPgAyIlE94ofz9v75nM20VM5cacea3hRb4q2qVCuw6p3tJkXwmRLn1zrGvCvZbxOYPgAyIlE94ofz9v75nM20VM5cacea3hRb4q2qVCuw6p3tJkXwmRLn1zrGvCvZbxOYPgAyIlE94ofz9v75nM20VM5cacea3hRb4q2qVCuw6p3tJkXwmRLn1zrGvCvZbxOYPgAyIlE94ofz9v75nM20VM5cacea3hRb4q2qVCuw6p3tJkXwmRLn1zrGvCvZbxOYPgAyIlE94ofz9v75nM20VM5cacea3hRb4q2qVCuw6p3tJkXwmRLn1zrGvCvZbxOYPgAyIlE94ofz9v75nM20VM5cacea3hRb4q2qVCuw6p3tJkXwmRLn1zrGvCvZbxOYPgAyIlE94ofz9v75nM20VM5cacea3hRb4q2qVCuw6p3tJkXwmRLn1zrGvCvZbxOYPgAyIlE94ofz9v75nM20VM5cacea3hRb4q2qVCuw6p3tJkXwmRLn1zrGvCvZbxOYPgAyIlE94ofz9v75nM20VM5cacea3hRb4q2qVCuw6p3tJkXwmRLn1zrGvCvZbxOYPgAyIlE94ofz9v75nM20VM5cacea3hRb4q2qVCuw6p3tJkXwmRLn1zrGvCvZbxOYPgAyIlE94ofz9v75nM20VM5cacea3hRb4q2qVCuw6p3tJkXwmRLn1zrGvCvZbxOYPgAyIlE94ofz9v75nM20VM5cacea3hRb4q2qVCuw6p3tJkXwmRLn"; protected const string strPublicKey = @"bxOYPgAy**********************3hRb4q2qVCuw6p3tJkXwmRLn1zrGvCvZbxOYPgAyIlE94ofz9v75nM20VM5cacea3hRb4q2qVCuw6p3tJkXwmRLn1zrGvCvZbxOYPgAyIlE94ofz9v75nM20VM5cacea3hRb4q2qVCuw6p3tJkXwmRLn1zrGvCvZbxOYPgAyIlE94ofz9v75nM20VM5cacea3hRb4q2qVCuw6p3tJkXwmRLn1zrGvCvZbxOYPgAyIlE94ofz9v75nM20VM5cacea3hRb4q2qVCuw6p3tJkXwmRLn1zrGvCvZbxOYPgAyIlE94ofz9v75nM20VM5cacea3hRb4q2qVCuw6p3tJkXwmRLn1zrGvCvZ";
public PaymentService() { client = new DefaultAopClient("https://openapi.alipay.com/gateway.do", "9880***************309", strPrivateKey, "json", "1.0", "RSA2", strPublicKey, "UTF-8", false); }
/// <summary> /// 支付宝参数 /// </summary> /// <returns></returns> public async Task<object> PaymentParam(string amount,string userId) { try { //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称如:alipay.trade.app.pay AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest(); //SDK已经封装掉了公共参数,这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。 AlipayTradeAppPayModel model = new AlipayTradeAppPayModel(); model.Body = "购买会员," + userId; string strOutTradeNo = DateTime.Now.ToString("yyyyMMddHHmmss"); model.OutTradeNo = strOutTradeNo; model.Subject = "购买会员";
if (!string.IsNullOrEmpty(amount)) { model.TotalAmount = amount; } else { model.TotalAmount = "0.01"; } model.ProductCode = "QUICK_MSECURITY_PAY"; model.TimeoutExpress = "30m"; request.SetBizModel(model); request.SetNotifyUrl("http://www.alibaba.com/api/alipay/notice"); //这里和普通的接口调用不同,使用的是sdkExecute AlipayTradeAppPayResponse response = client.SdkExecute(request); //HttpUtility.HtmlEncode是为了输出到页面时防止被浏览器将关键参数html转义,实际打印到日志以及http传输不会有这个问题 SenparcTrace.Log($"支付宝支付结果信息为未转义-----{response.Body}"); SenparcTrace.Log($"支付宝支付结果信息为-----{HttpUtility.HtmlEncode(response.Body)}"); return new BaseResult<object>(200,"请求成功", HttpUtility.HtmlEncode(response.Body).Replace("&", "&")); } catch (Exception ex) { return new BaseResult<object>(201, "请求失败", ex.Message); } }
}
}
复制代码

6.调用代码返回数据给前端

7.前端拿数据吊起支付




阿里云短信对接

参考文档

开发文档:https://help.aliyun.com/document_detail/101414.html?spm=a2c4g.11186623.6.628.53d14fe8pYm0tR


步骤

1.下载 NCF

2.创建自己的 XNCF 模块

3.引用 Nuget 包 AlibabaCloud.SDK.Dysmsapi20170525

     <ItemGroup>         <PackageReference Include="AlibabaCloud.SDK.Dysmsapi20170525" Version="1.0.2" />     </ItemGroup>
复制代码

4.建立自己的 Controller,并创建方法,调用发送短信方法

  /// <summary>  /// 发送短信验证码  /// </summary>  /// <param name="mobile">手机号</param>  /// <returns></returns>  [HttpGet]  public async Task<IActionResult> SendSMS(string mobile)  {     try     {         var response = await ApiSendCodeAsync(mobile);         return Success(response);     }     catch (Exception ex)     {         return Fail(ex.Message);     } }
复制代码

5.建立调用短信的类,创建发送短信方法

 using AlibabaCloud.SDK.Dysmsapi20170525; using AlibabaCloud.SDK.Dysmsapi20170525.Models; using AlibabaCloud.OpenApiClient.Models;
复制代码


public async Task<object> ApiSendCodeAsync(string mobile){    Random random = new Random();    string strCode = random.Next(100000, 999999).ToString();    string strTemplateCode = "SMS_000000000";    string accessKeyId = "LTAI*********LB4";    string accessKeySecret = "vp**************************BW";    Config config = new Config    {        // 您的AccessKey ID        AccessKeyId = accessKeyId,        // 您的AccessKey Secret        AccessKeySecret = accessKeySecret,    };    // 访问的域名    config.Endpoint = "dysmsapi.aliyuncs.com";    Client client = new Client(config);    SendSmsRequest sendSmsRequest = new SendSmsRequest    {        PhoneNumbers = mobile,        SignName = "米立科技",        TemplateCode = strTemplateCode,        TemplateParam = $"{{\"code\":\"{strCode}\"}}",    };    // 复制代码运行请自行打印 API 的返回值    var smsResponse = client.SendSms(sendSmsRequest);    // 将验证码写入Redis    SenparcRedis.Set($"VerificationCode:{mobile}", strCode, 300);    return strCode;}
复制代码


发布于: 1 小时前阅读数: 9
用户头像

MartyZane

关注

坚持不懈,直到成功 2021.03.15 加入

技术痴一枚,资深开发,喜欢交流,热爱开源,希望能与更多优秀的开发者一共为社会的进步贡献一份自己的力量

评论

发布
暂无评论
NCF 如何对接三方的功能(五)