.net 微信小程序,微信支付分对接开发(一)支付分授权

支付分api:https://pay.weixin.qq.com/wiki/doc/apiv3/payscore.php?chapter=14_0&index=1

小程序授权(envVersion目前只能是release(正式版),所以调试也只能正式版调试)

 

-----res数据来自后台----

wx.navigateToMiniProgram({
        appId: 'wxd8f3793ea3b935b8', //授权程序appid(固定)
        path: 'pages/use/enable', //授权方地址(固定)
        extraData: {
          mch_id: res.data.mch_Id,//商户号
          service_id: res.data.service_Id,//服务ID,商户后台配置
          out_request_no: res.data.out_request_no,//随机数
          timestamp: res.data.timeStamp,//时间戳
          nonce_str: res.data.nonceStr,//随机数32位
          sign_type: "HMAC-SHA256",
          sign: res.data.sign//签名串
        },
        envVersion: 'release',
        success(r) {
          console.log(r)
          //dosomething
          util.showToast("授权成功", 1)
        },
        fail() {
          //dosomething
          util.showToast("授权失败", 0)
        },

后台(.net):

            string SERVICE_ID = "";//商户后台配置参数
            string MerchantId = "";//商户后台配置参数
            string KEY = "";//商户后台配置参数
try
            {
                Dictionary<string, string> Para_dic = new Dictionary<string, string>();
                Para_dic.Add("mch_id", MerchantId);
                Para_dic.Add("service_id", SERVICE_ID);
                Para_dic.Add("out_request_no", out_request_no);//参数自己生成
                Para_dic.Add("timestamp", timeStamp);//时间戳自己生成
                Para_dic.Add("nonce_str", nonceStr);//参数自己生成
                Para_dic.Add("sign_type", "HMAC-SHA256");
                string[] keyArr = { "mch_id", "service_id", "out_request_no", "timestamp", "nonce_str", "sign_type" };
                sign = signArithmetic_SHA(keyArr, Para_dic, KEY);
            }
            catch (Exception) { }
result = JsonConvert.SerializeObject(new { out_request_no = out_request_no, timeStamp = timeStamp, nonceStr = nonceStr, sign = sign, service_Id = SERVICE_ID, mch_Id = MerchantId });

签名串加密方法:

/// <summary>
        /// 签名生成算法(SHA256)
        /// 返回签名
        /// </summary>
        public static string signArithmetic_SHA(string[] keyArray, Dictionary<string, string> dataDir, string key)
        {
            if (keyArray.Length != dataDir.Count)
            {
                return "";
            }
            string stringA = "";
            //ASCII码排序
            Array.Sort(keyArray, string.CompareOrdinal);
            for (int i = 0; i < dataDir.Count; i++)
            {
                stringA += keyArray[i];
                foreach (var item in dataDir)
                {
                    if (item.Key == keyArray[i])
                    {
                        stringA += "=" + item.Value + "&";
                    }
                }
            }
            //拼接API密钥 
            string signtemp = stringA + "key=" + key;

            return SHA256(signtemp, key).ToUpper();
        }
        private static string SHA256(string plaintext, string salt)
        {
            string result = "";
            var enc = Encoding.Default;
            byte[]
            baText2BeHashed = enc.GetBytes(plaintext),
            baSalt = enc.GetBytes(salt);
            HMACSHA256 hasher = new HMACSHA256(baSalt);
            byte[] baHashedText = hasher.ComputeHash(baText2BeHashed);
            result = string.Join("", baHashedText.ToList().Select(b => b.ToString("x2")).ToArray());
            return result;
        }

 

以下是一个C#对接通联微信小程序支付的示例代码: ```csharp using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net; using System.IO; using System.Xml; namespace WeChatPay { class Program { static void Main(string[] args) { string strAppid = "你的小程序的appid"; string strMchId = "你的商户号"; string strKey = "你的API密钥"; string strNonce = Guid.NewGuid().ToString().Replace("-", ""); string strBody = "商品描述"; string strOutTradeNo = "商户订单号"; string strTotalFee = "订单总金额,单位为"; string strSpbillCreateIp = "调用微信支付API的机器的IP地址"; string strNotifyUrl = "接收微信支付异步通知回调地址"; string strTradeType = "JSAPI"; string strOpenid = "用户在商户appid下的唯一标识"; string strSign = ""; //生成签名 SortedDictionary<string, string> dic = new SortedDictionary<string, string>(); dic.Add("appid", strAppid); dic.Add("mch_id", strMchId); dic.Add("nonce_str", strNonce); dic.Add("body", strBody); dic.Add("out_trade_no", strOutTradeNo); dic.Add("total_fee", strTotalFee); dic.Add("spbill_create_ip", strSpbillCreateIp); dic.Add("notify_url", strNotifyUrl); dic.Add("trade_type", strTradeType); dic.Add("openid", strOpenid); string strSignTemp = ""; foreach (KeyValuePair<string, string> kvp in dic) { if (!string.IsNullOrEmpty(kvp.Value)) { strSignTemp += kvp.Key + "=" + kvp.Value + "&"; } } strSignTemp += "key=" + strKey; strSign = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(strSignTemp, "MD5").ToUpper(); //生成XML请求参数 string strXml = "<xml>" + "<appid>" + strAppid + "</appid>" + "<mch_id>" + strMchId + "</mch_id>" + "<nonce_str>" + strNonce + "</nonce_str>" + "<body>" + strBody + "</body>" + "<out_trade_no>" + strOutTradeNo + "</out_trade_no>" + "<total_fee>" + strTotalFee + "</total_fee>" + "<spbill_create_ip>" + strSpbillCreateIp + "</spbill_create_ip>" + "<notify_url>" + strNotifyUrl + "</notify_url>" + "<trade_type>" + strTradeType + "</trade_type>" + "<openid>" + strOpenid + "</openid>" + "<sign>" + strSign + "</sign>" + "</xml>"; //向微信支付接口发送请求 string url = "https://api.mch.weixin.qq.com/pay/unifiedorder"; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; byte[] data = Encoding.UTF8.GetBytes(strXml); request.ContentLength = data.Length; Stream stream = request.GetRequestStream(); stream.Write(data, 0, data.Length); stream.Close(); //获取微信支付接口返回的数据 HttpWebResponse response = (HttpWebResponse)request.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8); string strResult = reader.ReadToEnd(); XmlDocument xmlResult = new XmlDocument(); xmlResult.LoadXml(strResult); //解析返回数据,获取prepay_id XmlNode xmlNode = xmlResult.SelectSingleNode("xml/prepay_id"); string strPrepayId = xmlNode.InnerText; //生成小程序支付需要的参数 SortedDictionary<string, string> dicPay = new SortedDictionary<string, string>(); dicPay.Add("appId", strAppid); dicPay.Add("nonceStr", strNonce); dicPay.Add("package", "prepay_id=" + strPrepayId); dicPay.Add("signType", "MD5"); dicPay.Add("timeStamp", Convert.ToInt64(DateTime.Now.Subtract(new DateTime(1970, 1, 1)).TotalSeconds).ToString()); string strSignTempPay = ""; foreach (KeyValuePair<string, string> kvp in dicPay) { if (!string.IsNullOrEmpty(kvp.Value)) { strSignTempPay += kvp.Key + "=" + kvp.Value + "&"; } } strSignTempPay += "key=" + strKey; string strPaySign = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(strSignTempPay, "MD5").ToUpper(); //返回小程序支付所需参数 Console.WriteLine("appId:" + strAppid); Console.WriteLine("nonceStr:" + strNonce); Console.WriteLine("package:" + "prepay_id=" + strPrepayId); Console.WriteLine("signType:MD5"); Console.WriteLine("timeStamp:" + dicPay["timeStamp"]); Console.WriteLine("paySign:" + strPaySign); } } } ``` 请注意替换代码中的变量值为您自己的实际值。此代码仅供参考,具体实现方式可能因为不同的商户号、API密钥等因素而有所不同。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值