编程语言
首页 > 编程语言> > C# 公众号网页开发 -绑定测试界面

C# 公众号网页开发 -绑定测试界面

作者:互联网

1、微信公众号网页开发授权文档 

 

2、主要测试代码

前端界面代码

<form method="POST" id="submitForm">
    <label for="name">工号</label>
    <input type="text" class="form-control" name="userNameOrEmailAddress" id="userNameOrEmailAddress" placeholder="请输入工号" required="required">
    <label for="name">密码</label>
    <input type="password" class="form-control" name="password" id="password" placeholder="请输入密码" required="required">  
    <label for="name">身份证号码</label>
    <input type="text" class="form-control" name="IDCard" id="IDCard" placeholder="请输入身份证号码" required="required">
    <input hidden name="openid" id="openid" value="@Model.openid"/>
    <button type="submit" class="btn btn-primary" style="margin-top:5px">提交绑定</button> 
</form>

后端代码

/// <summary>
/// 用户公众号openid
/// </summary>
public string openid = "";

/// <summary>
/// 进入界面获取微信code,拿到用户openid信息
/// </summary>
/// <returns></returns>
/// <exception cref="Exception"></exception>
public async Task OnGet()
{//先检查是否已经绑定了openid,进入就获取openid
    string code = Request.Query["code"].ToString();
    string state = Request.Query["state"].ToString();
    if (string.IsNullOrEmpty(code))
    {
        throw new Exception("获取code失败!");
    }
    string appid = "填写公众号appid"; //公众号appid
    string secret = "填写公众号secret";//公众号密钥
    //获取access_token
    string url = $@"https://api.weixin.qq.com/sns/oauth2/access_token?appid={appid}&secret={secret}&code={code}&grant_type=authorization_code";
    HttpClient tokenClient = new();
    string responseBody = await tokenClient.GetStringAsync(url);
    AccessTokenPublicDto at = JsonConvert.DeserializeObject<AccessTokenPublicDto>(responseBody);
    string access_token = at.access_token;
    openid = at.openid;
}

public async Task<IActionResult> OnPostAsync(UserLoginBindInfoDto input)
{
    if (ModelState.IsValid && input!=null)
    {
        bindInfo = await _iWeChatPublicBindService.PostPublicBind(input);
    }
    if (bindInfo.state)
    {
        return LocalRedirect($@"/Message?msg={bindInfo.message}");
    }
    else 
    {
        return Redirect($@"/Message?msg={bindInfo.message}");
    }
}    

 

测试主要代码使用 asp mvc core 项目

当前测试绑定界面需求场景:

小程序和公众号没有做绑定,所以在公众号做了个工号绑定操作,通过工号来关联公众号和小程序。

其他相关链接:

绑定公众号和小程序文档

微信开放平台

 

标签:openid,code,网页,string,C#,绑定,公众,appid
来源: https://www.cnblogs.com/xygsj/p/16691777.html