一、在支付前期,我们需要获取用户的OpenId,此块内容只针对于JSAPI(微信中直接支付)才需要,如果生成二维码(NATIVE)扫描支付,请跳过此步骤
思路大致是:获取用户的code值 > 根据code值再获取用户的OpenId
1、先绑定授权域名:开发者中心>网页服务>基础接口>网页授权获取用户基本信息>修改>设置网站的域名 。点击查看
2、获取用户的code值时,方式如下:
https://open.weixin.qq.com/connect/oauth2/authorize?appid=&redirect_uri=&response_type=code&scope=&state=STATE#wechat_redirect
其中APPId不用多说,redirect_uri为网站的回调地址,回调地址必须UrlEncode处理,其中返回的参数就有code值
关于网页授权的两种scope的区别说明:snsapi_base和snsapi_userinfo,scope只有这2种方式
snsapi_base是不需要用户同意的,但是回调地址中获取到的code,根据这个code只能获取用户的OpenId,像:昵称,性别等是无法获取的,但是对于微信支付足够了
snsapi_userinfo是需要用户同意才能获取code,通过code能够获取用户的基本信息,这个做微信登录比较好,但是如果客户不同意就没办法进行下边的环节了,所以微信支付不要用这个参数。
3、根据2中返回的code值,获取用户的OpenId,方法如下:
方式:POST,Url:https://api.weixin.qq.com/sns/oauth2/access_token?appid=&secret=&code=&grant_type=authorization_code"
其中code值是从2中获取到的,返回参数为json,其中有一个参数为openid。
//1.获取Code值
string v = HttpContext.Current.Server.UrlEncode("http://****");
string url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=&redirect_uri=" + v + "&response_type=code&scope=snsapi_base#wechat_redirect";
Response.Redirect(url);
string Code = base.QueryString("code");
//2.获取OpenId
string urls = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=&secret=&code=" + Code + "&grant_type=authorization_code";
string openid = PostWebRequest(urls, "");
/// <summary>
/// 获取OpenId方法
/// </summary>
/// <param name="postUrl"></param>
/// <param name="menuInfo"></param>
/// <returns></returns>
public string PostWebRequest(string postUrl, string menuInfo)
{
string returnValue = string.Empty;
try
{
byte[] byteData = Encoding.UTF8.GetBytes(menuInfo);
Uri uri = new Uri(postUrl);
HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(uri);
webReq.Method = "POST";
webReq.ContentType = "application/x-www-form-urlencoded";
webReq.ContentLength = byteData.Length;
//定义Stream信息
Stream stream = webReq.GetRequestStream();
stream.Write(byteData, 0, byteData.Length);
stream.Close();
//获取返回信息
HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
StreamReader streamReader = new StreamReader(response.GetResponseStream(), Encoding.Default);
returnValue = streamReader.ReadToEnd();
//关闭信息
streamReader.Close();
response.Close();
stream.Close();
JsonTextParser parser = new JsonTextParser();
JsonObjectCollection obj = parser.Parse(returnValue) as JsonObjectCollection;
JsonUtility.GenerateIndentedJsonText = false;
string openid = obj["openid"].GetValue().ToString();
return openid;
}
catch (Exception ex)
{
return ex.ToString();
}
}
二、微信支付
大致思路:微信支付>开发配置>支付授权目录 设置一个支付页面所在文件夹 点击查看相应位置
登录商户平台 > API安全 > 设置一个32位由数字和字母组成的密钥。 以上内容设置好后才可以进行支付参数的设置
1、引用微信JS http://res.wx.qq.com/open/js/jweixin-1.0.0.js
2、设置config参数
3、设置chooseWXPay参数
4、支付
这里需要强调的是,下边config和chooseWXPay中的参数名为:nonceStr、timestamp要一直,否则就会一直报错:paySign加密错误
其中package的prepay_id参数内容的获取内容为可以根据官网的要求来,但传参字段一定要小写,一定要小写!
paySign 的加密方式为chooseWXPay的参数内容:timestamp、nonceStr、package、signType、key的组合加密,加密方式 和获取prepay_id的方式一样,具体操作看代码。但是这里的加密的参数的大小写要前后台对应一直,否则加密一定错误!
加密的方式如:把所有的参数首字母从小到大传参的形式组成字符串后,把key值再拼接上,具体内容请参考微信的签名算法和微信下单的参数列表
<script src="../js/jquery.js" type="text/javascript"></script>
<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js" type="text/javascript"></script>
<script type="text/javascript">
wx.config({
debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId: '<%=appids %>', // 必填,公众号的唯一标识
timestamp: "<%=Timer %>", // 必填,生成签名的时间戳
nonceStr: "<%=RdCode %>", // 必填,生成签名的随机串
signature: "<%=GetSignature() %>", // 必填,签名,见附录1
jsApiList: ['chooseWXPay'] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
});
wx.ready(function () {
wx.chooseWXPay({
appId: '<%=appids %>',
timestamp: '<%=Timer %>',
nonceStr: '<%=RdCode %>',
package: 'prepay_id=<%=prepay_id %>',
signType: 'MD5',
paySign: '<%=paySign %>',
success: function (res) {
window.location.href = "cart4.aspx?Code=<%=Code %>";
},
cancel: function () {
window.location.href = "cart3.aspx?Code=<%=Code %>";
},
error: function (e) {
window.location.href = "cart3.aspx?Code=<%=Code %>";
}
});
});
</script>
public string appids = "";//这里是公众号的AppId
public string Code = ""; //订单号
public string Timer = "";//1970年到现在的秒数
public string OpenId = "";//用户的OpenId
public string paySign = "";//paySign
public string RdCode = "";//随机数
public string prepay_id = "";//package中prepay_id的值
public string AppSecret = "";//公众号的AppSecret
protected void Page_Load(object sender, EventArgs e)
{
GetTiks();
RdCode = getNoncestr().ToLower();
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
Timer = Convert.ToInt64(ts.TotalSeconds).ToString();
BindString();
}
/// <summary>
/// 获取jsapi_ticket的值
/// </summary>
public void GetTiks()
{
string value = "";
Stream outstream = null;
Stream instream = null;
StreamReader sr = null;
HttpWebResponse response = null;
HttpWebRequest request = null;
Encoding encoding = Encoding.UTF8;
try
{
request = (HttpWebRequest)WebRequest.Create("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + Get_Access_Token(appids, AppSecret) + "&type=jsapi");
CookieContainer cookieContainer = new CookieContainer();
request.CookieContainer = cookieContainer;
request.AllowAutoRedirect = true;
request.Method = "GET";
request.ContentType = "application/x-www-form-urlencoded";
response = request.GetResponse() as HttpWebResponse;
request.GetResponse();
instream = response.GetResponseStream();
sr = new StreamReader(instream, encoding);
JsonTextParser parser = new JsonTextParser();
JsonObjectCollection obj = parser.Parse(sr.ReadToEnd().Replace("[]", "null")) as JsonObjectCollection;
JsonUtility.GenerateIndentedJsonText = false;
Tiks = obj["ticket"].GetValue().ToString();
}
catch (Exception ex)
{
Tiks = "";
}
}
/// <summary>
/// 获取Access_Token值
/// </summary>
/// <param name="appid">AppId</param>
/// <param name="secret">AppSecret</param>
/// <returns></returns>
public static string Get_Access_Token(string appid, string secret)
{
string value = "";
Stream outstream = null;
Stream instream = null;
StreamReader sr = null;
HttpWebResponse response = null;
HttpWebRequest request = null;
Encoding encoding = Encoding.UTF8;
try
{
request = (HttpWebRequest)WebRequest.Create("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&app>
源码下载: WeiXinPay.rar
转自:https://www.cnblogs.com/imluzhi/p/4836216.html