實現:
其中用到了盛派封裝的方法
//微信公眾號 private static string OfficialAccountAppId => ConfigurationManager.AppSettings["OfficialAccountAppId"]; private static string OfficialAccountAppSecret => ConfigurationManager.AppSettings["OfficialAccountAppSecret"]; /// <summary> /// 返回帶參數(場景值)的公眾號二維碼圖片地址 /// </summary> /// <returns></returns> [Route("weixin/createqrcode/withParam")] [HttpGet] public async Task<RestResponse> GetOfficialAccountQRcodeWithParam(string scene_str) { var ticket = CreateQrCodeTicketAsync(scene_str); RestResponse result = new RestResponse(); //通過ticket獲取二維碼對應的url result.Content = QrCodeApi.GetShowQrCodeUrl(ticket); //利用盛派獲取圖片地址(本人對網絡請求並不熟悉,這里只是知道調用該方法能夠獲取成功,這里並沒有去細究) return result; } /// <summary> /// 利用微信API創建二維碼ticket /// </summary> /// <param name="scene_str">場景值</param> /// <returns></returns> private string CreateQrCodeTicketAsync(string scene_str) { var accessToken = WeiXinCommonBll.WxGetAccexxToken(OfficialAccountAppId, OfficialAccountAppSecret); //微信獲取access_token的方法每天有請求次數限制,應該自己封裝一下 string wxurl = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + accessToken; string strJson = "{\"expire_seconds\": 86400, \"action_name\": \"QR_STR_SCENE\", \"action_info\": {\"scene\": {\"scene_str\": " + scene_str + "}}}"; var result = Post(wxurl, strJson); if (result != null) { JObject jobect = JObject.Parse(result); string ticket = (string)jobect["ticket"]; if (string.IsNullOrEmpty(ticket)) { return null; } return ticket; } return null; } private string Post(string wxurl, string strJson) { WebClient client = new WebClient(); client.Credentials = CredentialCache.DefaultCredentials; string result = client.UploadString(wxurl, "POST", strJson); return result; }
因為盛派封裝的方法上說只有當 action_name 為 QR_LIMIT_STR_SCENE(永久的字符串參數值)時,后面的參數值 scene_str 才會有效,所以才在上面又自己寫了一下。
但是,經測試,其實臨時的字符串也是可以用的。所以,更簡單的方式是用盛派封裝的方法來實現:
//微信公眾號 private static string OfficialAccountAppId => ConfigurationManager.AppSettings["OfficialAccountAppId"]; private static string OfficialAccountAppSecret => ConfigurationManager.AppSettings["OfficialAccountAppSecret"]; /// <summary> /// 返回帶參數(場景值)的公眾號二維碼圖片地址 /// </summary> /// <returns></returns> [Route("weixin/createqrcode/withParam")] [HttpGet] public async Task<RestResponse> GetOfficialAccountQRcodeWithParam(string scene_str) { RestResponse result = new RestResponse(); var accessToken = WeiXinCommonBll.WxGetAccexxToken(OfficialAccountAppId, OfficialAccountAppSecret);
//原以為真的只有為永久字符串的時候 scene_str 才會有效,但是經測試,其實臨時字符串的時候也是可以用的! var qrTicket = await QrCodeApi.CreateAsync(accessToken, 500, 5, QrCode_ActionName.QR_STR_SCENE, scene_str); result.Content = QrCodeApi.GetShowQrCodeUrl(qrTicket.ticket); return result; }