資源簡介
2018改版后不能把官方API接口地址直接寫在小程序里了,因此需要自己去寫服務端來獲取openid等用戶信息,詳見代碼。
代碼片段和文件信息
using?System;
using?System.Collections.Generic;
using?System.Linq;
using?System.Web;
using?System.Web.Services;
using?System.Web.script.Serialization;
using?System.Web.script.Services;
using?System.Runtime.Serialization.Json;
using?System.Data;
using?System.Text;
using?System.IO;
using?System.Net;
using?Newtonsoft.Json;
using?Newtonsoft.Json.Linq;
///?
///?api?的摘要說明
///?
[WebService(Namespace?=?“http://tempuri.org/“)]
[WebServiceBinding(ConformsTo?=?WsiProfiles.BasicProfile1_1)]
//?若要允許使用?ASP.NET?AJAX?從腳本中調用此?Web?服務,請取消注釋以下行。?
[System.Web.script.Services.scriptService]
public?class?api?:?System.Web.Services.WebService
{
????[WebMethod]
????public?void?OpenID(string?code)
????{
????????//臨時登錄憑證code?獲取?session_key?和?openid
????????string?js_code?=?code;
????????//此處填寫自己小程序的appid和secret
????????string?serviceAddress?=?“https://api.weixin.qq.com/sns/jscode2session?appid=appid&secret=secret&js_code=“?+?js_code?+?“&grant_type=authorization_code“;
????????
????????HttpWebRequest?request?=?(HttpWebRequest)WebRequest.Create(serviceAddress);
????????request.Method?=?“GET“;
????????request.ContentType?=?“textml;charset=UTF-8“;
????????HttpWebResponse?response?=?(HttpWebResponse)request.GetResponse();
????????Stream?myResponseStream?=?response.GetResponseStream();
????????StreamReader?myStreamReader?=?new?StreamReader(myResponseStream?Encoding.UTF8);
????????string?jsonData?=?myStreamReader.ReadToEnd();
????????myStreamReader.Close();
????????myResponseStream.Close();
????????string?jsonString?=?jsonData;
????????Jobject?json?=?Jobject.Parse(jsonString);
????????string?openid?=?json[“openid“].ToString();
????????Context.Response.Write(GetJson(openid));
????}
????#region??把對象序列化?JSON?字符串
????///?
????///?把對象序列化?JSON?字符串?
????///?
????///?對象類型
????///?對象實體
????///?JSON字符串
????public?static?string?GetJson(T?obj)
????{
????????//記住?添加引用?System.ServiceModel.Web?
????????/**
?????????*?如果不添加上面的引用System.Runtime.Serialization.Json;?Json是出不來的哦
?????????*?*/
????????DataContractJsonSerializer?json?=?new?DataContractJsonSerializer(typeof(T));
????????using?(MemoryStream?ms?=?new?MemoryStream())
????????{
????????????json.Writeobject(ms?obj);
????????????string?szJson?=?Encoding.UTF8.GetString(ms.ToArray());
????????????return?szJson;
????????}
????}
????#endregion
}
????
- 上一篇:CLR via C# 第4版.pdf
- 下一篇:自制C#財物管理系統
評論
共有 條評論