js 前端让当前页返回带code参数
注意,第一步调用获取code时,返回路径必须是域名,不可是IP
window.onload = function () {
LoadApid();
var code = getUrlParam("code");
if (code != null) { //存在code后台存储用户信息
LoadWXInfo();
}
else
{
GetWXInf();//不存在 则调用微信接口返回code
}
};
//生成带返回Code的微信接口地址
function GetWXInf() {
var str = window.location.protocol + "//" + window.location.host + window.location.pathname;
var appid = $("#appid").val();
var Wx = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri=" + encodeURIComponent(str) + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
return Wx;
}
//获取appid赋值给前端
function LoadApid() {
$.ajax({
type: "post",
url: "XX/XX/GetWXInfo.ashx",
async: false,
dataType: 'json',
data: { "action": "GetApid" },
success: function (ret) {
$("#appid").val(ret.appid);
}
});
}
//存储当前微信用户信息
function LoadWXInfo() {
var Code = getUrlParam("code");
if (Code != null) {
$.ajax({
type: "post",
url: "XX/XX/GetWXInfo.ashx",
async: false,
dataType: 'json',
data: { "action": "GetWxInfo", "code": Code },
success: function (ret) {
if (ret.code != 0) {
alert(ret.msg);
}
}
});
}
}
ashx 获取传输的code参数 调用其他接口 获取用户信息
ashx里面就是直接把code传过去直接调用方法,不细写了
GetWXInfo wx = new GetWXInfo();
WXName = wx.firstLoad(context.Request["code"]); //获取返回的微信昵称,若出错 则返回错误信息、
using Newtonsoft.Json.Linq;
using NLog;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.SessionState;
namespace Dal
{
public class GetWXInfo
{
private static readonly Logger _logger = LogManager.GetCurrentClassLogger();
//公众号信息部分
public string appid = ConfigurationManager.AppSettings["AppId"];
public string appsecret = ConfigurationManager.AppSettings["AppSecret"];
private String getKeyURL &#