ashx代码部分(把下列代码保存成ashx文件,上传到服务器)
<% @ webhandler language="C#" class="AverageHandler" %>
using System;
using System.Net;
using System.Web;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.IO;
public class AverageHandler : IHttpHandler
{
public bool IsReusable
{ get { return true; } }
public void ProcessRequest(HttpContext ctx)
{
ctx.Response.ContentType = "application/json";
HttpRequest Request = ctx.Request;
string text = Request["encryptedData"];
string IV = Request["iv"];
//小程序appid和appsecret配置
string appid = "11111111111111111";//按实际填写
string secret = "222222222222222222";//按实际填写
string code = Request["code"];//微信获取登录的口令
Stream s_re = WebRequest.Create("https://api.weixin.qq.com/sns/jscode2session?appid="+appid+"&secret="+secret+"&js_code="+code+"&grant_type=authorization_code").GetResponse().GetResponseStream();
StreamReader sr = new StreamReader(s_re, Encoding.UTF8);
string strLine = sr.ReadToEnd();
sr.Close();
try
{
ctx.Response.Write(strLine);
}
catch (Exception ex)
{
//return "";
}
}
}
小程序wxml代码段
小程序js代码段
bindgetuserinfo: function (e) {
var that = this;
if (e.detail.userInfo) {
// 发送 res.code 到后台换取 openId, sessionKey, unionId
wx.login({
success: res => {
//console.log(res.code, e.detail.iv, e.detail.encryptedData)
wx.request({
//后台接口地址
url: 'https://www.XXXX.com/weixin/getopenid.ashx',
data: {
code: res.code,
},
method: 'GET',
header: {
'content-type': 'application/json'
},
success: function (res) {
console.log(res.data)
}
})
}
})
} else {
console.log(333, '执行到这里,说明拒绝了授权')
wx.showToast({
title: "为了您更好的体验,请先同意授权",
icon: 'none',
duration: 2000
});
}
}
执行结果: