当前位置: 移动技术网 > IT编程>开发语言>.net > .net微信服务号发送红包

.net微信服务号发送红包

2017年12月12日  | 移动技术网IT编程  | 我要评论

心理罪遭遇被停更,002578,孕妇注意事项大全75j

本文实例为大家分享了.net微信红包发送代码,供大家参考,具体内容如下

注:需要开通微信支付的服务号!

//跳转微信登录页面
public actionresult index()
{
 viewbag.url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + {服务号appid} + "&redirect_uri=http%3a%2f%2f" + {微信重定向域名(填写程序域名,例如:www.xxxx.com)} + "%2f"+{程序控制器名,例如:home}+"%2f"+{程序action名,例如:redirectwechat}+"&response_type=code&scope=snsapi_userinfo&state=state#wechat_redirect";
 return view();
}

//获取accesstoken(访问微信接口需要)
public static string accesstoken(string wechatwxappid, string wechatwxappsecret)
{
 string strjson = httprequestutil.requesturl(string.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", wechatwxappid, wechatwxappsecret));
 if (strjson.indexof("errcode") == -1)
 {
  return getjsonvalue(strjson, "access_token");
 }
 else
 {
  return "";
 }
}
//解析json
public static string getjsonvalue(string jsonstr, string key)
{
 string result = string.empty;
 if (!string.isnullorempty(jsonstr))
 {
  key = "\"" + key.trim('"') + "\"";
  int index = jsonstr.indexof(key) + key.length + 1;
  if (index > key.length + 1)
  {
   //先截逗号,若是最后一个,截“}”号,取最小值
   int end = jsonstr.indexof(',', index);
   if (end == -1)
   {
    end = jsonstr.indexof('}', index);
   }
   result = jsonstr.substring(index, end - index);
   result = result.trim(new char[] { '"', ' ', '\'' }); //过滤引号或空格
  }
 }
 return result;
}

//请求url
public static string requesturl(string url, string method="post")
{
 // 设置参数
 httpwebrequest request = webrequest.create(url) as httpwebrequest;
 cookiecontainer cookiecontainer = new cookiecontainer();
 request.cookiecontainer = cookiecontainer;
 request.allowautoredirect = true;
 request.method = method;
 request.contenttype = "text/html";
 request.headers.add("charset", "utf-8");
 //发送请求并获取相应回应数据
 httpwebresponse response = request.getresponse() as httpwebresponse;
 //直到request.getresponse()程序才开始向目标网页发送post请求
 stream responsestream = response.getresponsestream();
 streamreader sr = new streamreader(responsestream, encoding.utf8);
 //返回结果网页(html)代码
 string content = sr.readtoend();
 return content;
}
//接收微信返回code
//接收微信数据获取用户信息
public actionresult redirectwechat(string code, string state)
{
 if (string.isnullorempty(code))
 {
  return content("您拒绝了授权!");
 }
 string access_token = accesstoken(微信appid, 微信appsecret);
 string st = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + 微信appid + "&secret=" + 微信appsecret + "&code=" + code + "&grant_type=authorization_code";
 string data = requesturl(st);
//拿到用户openid
string openid=getjsonvalue(data, "openid");
//获取用户其他信息
 string url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + access_token + "&openid=" + openid + "&lang=zh_cn";
 data = requesturl(url);
string subscribe=getjsonvalue(data, "subscribe");
 if (subscribe == "0")
 {
  ///未关注
  return redirecttoaction("");
 }

 return redirecttoaction("");
}

//发送红包action
public actionresult hb()
{
 string openid = "";//用户openid
 string url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack"; 
 string orderno = 商户号 + datetime.now.tostring("yyyymmdd")+"随机10位数字";//商户订单号 组成:mch_id+yyyymmdd+10位一天内不能重复的数字。 
 string code = ""//32为随机字符串; string key="key=" + "";//支付密钥(在商户平台设置32为字符串) 
 dictionary<string, string> data = new dictionary<string, string>(); data.add("act_name", "");//活动名称 
 data.add("client_ip", "192.168.1.1");//ip地址 
 data.add("mch_billno", orderno);//商户订单号 组成:mch_id+yyyymmdd+10位一天内不能重复的数字。 
 data.add("mch_id", "");//商户号 
 data.add("nonce_str", code);//随机字符串 
 data.add("re_openid", openid);//用户openid 
 data.add("remark", "");//备注 
 data.add("send_name","");//商户名称 
 data.add("total_amount", "100");//付款金额 单位分 
 data.add("total_num", "1");//红包发放总人数 
 data.add("wishing", "恭喜发财");//红包祝福语 
 data.add("wxappid", );//公众账号appid 
 string xml = getxml(data, key);//签名+拼接xml 
 string str=postwebrequests(url, xml);//微信返回xml err_code=success 就是成功
 return view(""); 
}

//发送红包(md5签名+拼接xml)
public static string getxml(dictionary<string, string> data,string paykey)
{
 string retstr;
 md5cryptoserviceprovider m5 = new md5cryptoserviceprovider();

 var data1=from d in data orderby d.key select d;
 string data2 = "";
 string xml = "<xml>";
 foreach (var item in data1)
 {
  //空值不参与签名
  if (item.value + "" != "")
  {
   data2 += item.key +"="+ item.value + "&";
  }
  xml += "<" + item.key + ">" + item.value+""+ "</" + item.key + ">";
 }

 data2 += paykey;
 //创建md5对象
 byte[] inputbye;
 byte[] outputbye;

 //使用gb2312编码方式把字符串转化为字节数组.
 try
 {
  inputbye = encoding.utf8.getbytes(data2);
 }
 catch
 {
  inputbye = encoding.getencoding("gb2312").getbytes(data2);
 }
 outputbye = m5.computehash(inputbye);

 retstr = system.bitconverter.tostring(outputbye);
 retstr = retstr.replace("-", "").toupper();
 xml += "<sign>" + retstr + "</sign>";//签名
 xml += "</xml>";
 return xml;
}

//发送红包请求post方法
public static string postwebrequests(string posturl, string menuinfo)
{
 string returnvalue = string.empty;
 try
 {
  encoding encoding = encoding.utf8;
  byte[] bytes = encoding.getbytes(menuinfo);
  string cert = @"e:\cdcert\apiclient_cert.p12";//支付证书路径
  string password = "1212121";//支付证书密码

  servicepointmanager.servercertificatevalidationcallback = new remotecertificatevalidationcallback(checkvalidationresult);
  x509certificate cer = new x509certificate(cert, password, x509keystorageflags.machinekeyset);
  httpwebrequest webrequest = (httpwebrequest)httpwebrequest.create(posturl);
  webrequest.clientcertificates.add(cer);
  webrequest.method = "post";
  webrequest.contentlength = bytes.length;
  webrequest.getrequeststream().write(bytes, 0, bytes.length);
  httpwebresponse webreponse = (httpwebresponse)webrequest.getresponse();
  stream stream = webreponse.getresponsestream();
  string resp = string.empty;
  using (streamreader reader = new streamreader(stream))
  {
    return reader.readtoend();
  }

 }
 catch (exception ex)
 {
  return "";
 }
} 

以下是微信开发官方相关文档

1.
2. 微信开放平台
3.
4.

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网