欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

微信JS-SDK坐標(biāo)位置如何轉(zhuǎn)換為百度地圖坐標(biāo)

 更新時(shí)間:2016年07月04日 16:49:43   作者:迪克豬  
這篇文章主要介紹了微信JS-SDK坐標(biāo)位置如何轉(zhuǎn)換為百度地圖坐標(biāo) 的相關(guān)資料,感興趣的小伙伴們可以參考一下

微信JS-SDK開發(fā)過程中,使用getLocation獲取坐標(biāo)位置,如何將微信獲取的坐標(biāo)直接應(yīng)用到百度地圖中,顯示以下效果:

說明:紅色圖標(biāo)是從微信轉(zhuǎn)換過來的位置,藍(lán)色圖標(biāo)是周邊位置。首先從微信開發(fā)流程講解。

1、微信JS-SDK開發(fā)文檔

首先進(jìn)入官網(wǎng)的幫助文檔:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115&token=&lang=zh_CN

可對(duì)文檔進(jìn)行詳細(xì)的研讀,要獲取位置信息,分以下步驟:

第一步:綁定域名

進(jìn)入微信公眾號(hào),找到“公眾號(hào)設(shè)置”菜單,進(jìn)入“功能設(shè)置”面板,

點(diǎn)擊“設(shè)置”可設(shè)置引用js的相關(guān)域名:

第二步:引用官方j(luò)s類庫

在需要調(diào)用JS接口的頁面引入如下JS文件,(支持https):http://res.wx.qq.com/open/js/jweixin-1.0.0.js 。

引用頁面是location.aspx,如下:

<%@ Page Title="獲取位置" Language="C#" AutoEventWireup="true" MasterPageFile="~/wxcrm/Site.Master" CodeFile="location.aspx.cs" Inherits="DTcms.Web.wxcrm.location" %>

<asp:Content ID="Content1" ContentPlaceHolderID="cphHead" runat="server">
 <script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
 <script type="text/javascript">
 $("#mask").show();
 wx.config({
  debug: false, //開啟調(diào)試模式,如為true,則彈出每個(gè)js函數(shù)調(diào)用情況
  appId: '<%= ResultJsData.GetValue("appid") %>', //必填,公眾號(hào)的唯一標(biāo)識(shí)
  timestamp: <%= ResultJsData.GetValue("timestamp") %>, //必填,生成簽名的時(shí)間戳
  nonceStr: '<%= ResultJsData.GetValue("noncestr") %>', //必填,生成簽名的隨機(jī)串
  signature: '<%= ResultJsData.GetValue("signature") %>', //必填,簽名
  jsApiList: [
  'checkJsApi',
  'onMenuShareTimeline',
  'onMenuShareAppMessage',
  'onMenuShareQQ',
  'onMenuShareWeibo',
  'hideMenuItems',
  'showMenuItems',
  'hideAllNonBaseMenuItem',
  'showAllNonBaseMenuItem',
  'translateVoice',
  'startRecord',
  'stopRecord',
  'onRecordEnd',
  'playVoice',
  'pauseVoice',
  'stopVoice',
  'uploadVoice',
  'downloadVoice',
  'chooseImage',
  'previewImage',
  'uploadImage',
  'downloadImage',
  'getNetworkType',
  'openLocation',
  'getLocation',
  'hideOptionMenu',
  'showOptionMenu',
  'closeWindow',
  'scanQRCode',
  'chooseWXPay',
  'openProductSpecificView',
  'addCard',
  'chooseCard',
  'openCard'
  ]
 });
 wx.ready(function(){
  wx.checkJsApi({
  jsApiList: [
   'getNetworkType',
   'previewImage',
   'getLocation'
  ],
  success: function (res) {
  }
  });
  wx.getLocation({
  type: 'wgs84', // 默認(rèn)為wgs84的gps坐標(biāo),如果要返回直接給openLocation用的火星坐標(biāo),可傳入'gcj02'
  success: function (res) {
   try {
   var latitude = res.latitude; // 緯度,浮點(diǎn)數(shù),范圍為90 ~ -90
   var longitude = res.longitude; // 經(jīng)度,浮點(diǎn)數(shù),范圍為180 ~ -180。
   var speed = res.speed; // 速度,以米/每秒計(jì)
   var accuracy = res.accuracy; // 位置精度
   //alert(JsonUti.convertToString(res));
   //wx.openLocation({
   // latitude: res.latitude, // 緯度,浮點(diǎn)數(shù),范圍為90 ~ -90
   // longitude: res.longitude, // 經(jīng)度,浮點(diǎn)數(shù),范圍為180 ~ -180。
   // name: '當(dāng)前位置', // 位置名
   // address: '點(diǎn)擊查看', // 地址詳情說明
   // scale: 28, // 地圖縮放級(jí)別,整形值,范圍從1~28。默認(rèn)為最大
   // infoUrl: "location1.aspx?m=Home&c=Index&a=getlocation&latitude="+latitude+"&longitude="+longitude // 在查看位置界面底部顯示的超鏈接,可點(diǎn)擊跳轉(zhuǎn)
   //});
   //alert(latitude+"-"+longitude);
   $("#mask").hide();
   window.location.href = "location1.aspx?m=Home&c=Index&a=getlocation&latitude=" +
    latitude +
    "&longitude=" +
    longitude +
    "&=speed" +
    speed +
    "&accuracy=" +
    accuracy;
   } catch (e) {
   alert(e.message);
   }
  },
  cancel: function (res) {
   window.location.href="none.aspx?msg=拒絕獲取地理位置&r=" + Math.random();//拒絕
  },
  fail:function() {
   alert("未能獲取地理位置!首先檢查手機(jī)是否啟用微信定位。");
  }
  });
 });

 wx.error(function(res) {
  // config信息驗(yàn)證失敗會(huì)執(zhí)行error函數(shù),如簽名過期導(dǎo)致驗(yàn)證失敗,具體錯(cuò)誤信息可以打開config的debug模式查看,也可以在返回的res參數(shù)中查看,對(duì)于SPA可以在這里更新簽名。
 });

 wx.fail(function(res) {
 });
 </script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="cphTitle" runat="server">
 獲取位置
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="cphContainer" runat="server">
 <br />
 <br />
 <center style="display: block;">

 <i class="weui_icon_msg weui_icon_info"></i>

 <div class="input_errow" style="width: 60%; height: 60%; text-align: center;">
  正在獲取地理位置信息...
 </div>
 </center>

 <div class="mask" style="display: none;">
 <span>
  <img src="/templates/txwap/images/mask.gif" />
 </span>
 </div>
</asp:Content>

頁面效果:

注意事項(xiàng):

(1)如果手機(jī)設(shè)置不允許微信獲取位置信息,則提示以上信息。

(2)上圖參數(shù)獲取的是GPS坐標(biāo),如使用百度地圖,要做一定轉(zhuǎn)換,將在location1.aspx中體現(xiàn)。

(3)所有需要使用JS-SDK的頁面必須先注入配置信息,否則將無法調(diào)用。

對(duì)應(yīng)location.aspx.cs實(shí)現(xiàn):

using Payment.WxWebHlper;
using Payment.WxWebHlper.Actions;
using System;
using System.Globalization;
using WxJsSDK;
using WxPayAPI;

namespace DTcms.Web.wxcrm
{
 public partial class location : PageBase
 {
 protected string appId { get; set; }
 protected string timestamp { get; set; }
 protected string nonceStr { get; set; }
 protected string signature { get; set; }
 public static string WxJsApiParam { get; set; }
 public WxJsData ResultJsData { get; set; }

 protected void Page_Load(object sender, EventArgs e)
 {
 JudgeCode();
 var webAuthorize = new WebAuthorizeAction();
 Code2TokenResult = webAuthorize.Code2Token(Request["code"]);
 if (Code2TokenResult.HasError())
 {
 Response.Redirect(Urls.PageOfLocation);
 GotoNonePage("獲取用戶憑證失敗,請(qǐng)重新獲取");
 return;
 }
 GetUserInfoResult = webAuthorize.GetUserInfo(Code2TokenResult.access_token);
 if (GetUserInfoResult.HasError())
 {
 GotoNonePage("獲取用戶信息失敗,請(qǐng)重新獲取");
 }
 var userid = wxOperation.HasBind(GetUserInfoResult.openid);
 if (userid.Equals(Guid.Empty))
 {
 Response.Redirect(Urls.Oauth2Url);
 GotoNonePage("微信用戶未綁定");
 }

 appId = WxPayConfig.APPID;
 timestamp = WxPayApi.GenerateTimeStamp();
 nonceStr = WxPayApi.GenerateNonceStr();
 //以下實(shí)現(xiàn)將在3、核心代碼實(shí)現(xiàn) 體現(xiàn) var jsApi = new JsApi(this);
 ResultJsData = jsApi.GetJsData();
 WxJsApiParam = jsApi.GetJsApiParameters();//獲取H5調(diào)起JS API參數(shù)
 }
 }
}

2、將微信GPS坐標(biāo)轉(zhuǎn)換為百度坐標(biāo)

微信獲取坐標(biāo)成功后,頁面自動(dòng)跳轉(zhuǎn)到location1.aspx,處理流程如下:

微信坐標(biāo)—>轉(zhuǎn)換為百度地圖坐標(biāo)—>根據(jù)百度地圖API獲取位置信息—>根據(jù)百度地圖API顯示坐標(biāo)

<%@ Page Title="在線簽到" Language="C#" MasterPageFile="~/wxcrm/Site.Master" AutoEventWireup="true" CodeFile="location1.aspx.cs" Inherits="DTcms.Web.wxcrm.location1" %>

<asp:Content ID="Content1" ContentPlaceHolderID="cphHead" runat="server">
 <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
 <style type="text/css">
 #allmap { width: 100%; height: 300px; }
 </style>
 <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=dhRLKMR9QUO4wHmnnSZTarta"></script>
 <script type="text/javascript">
 //GPS坐標(biāo)
 var yy = <%= this.Request["longitude"] %>; //經(jīng)度,浮點(diǎn)數(shù),范圍為180 ~ -180。
 var xx = <%= this.Request["latitude"] %>; //緯度,浮點(diǎn)數(shù),范圍為90 ~ -90
 var gpsPoint = new BMap.Point(xx,yy);
 var bxx = 0.0;
 var byy = 0.0;

 /*
 * http://lbsyun.baidu.com/index.php?title=webapi/guide/changeposition
 */
 var PositionUrl = "http://api.map.baidu.com/geoconv/v1/?";
 function changePosition(){
 var str = "coords="+yy+","+xx+"&from=1&to=5";
 var url = PositionUrl + str;
 $("#positionUrl").html(url+"&ak=dhRLKMR9QUO4wHmnnSZTartg");
 var script = document.createElement('script');
 script.src = url + '&ak=dhRLKMR9QUO4wHmnnSZTarta&callback=dealResult';
 document.getElementsByTagName("head")[0].appendChild(script);
 }
 function dealResult(msg){
 if(msg.status != 0){
 alert("無正確的返回結(jié)果。");
 $("#mask").hide();
 return;
 }
 //JsonUti.convertToString(msg);
 bxx = msg.result[0].x;
 byy = msg.result[0].y;
 doOptions();
 }

 function getBaiduPosition() {
 var url ="http://api.map.baidu.com/geoconv/v1/?coords="+yy+","+xx+"&from=1&to=5&ak=dhRLKMR9QUO4wHmnnSZTarta";
 $.ajax({
 url: url,
 success: function(data,status,xhr) {
  alert(status);
  alert(data.status);
 },
 dataType: json
 });
 }

 var ADVANCED_POST = '';
 var advancedOptions = '';
 var address;
 var map;

 function renderOption(response) {
 var html = '';
 if (response.status ) {
 $("#mask").hide();
 var text = "無正確的返回結(jié)果!";
 alert(text);
 return;
 }
 var result = response.result;
 var location = response.result.location;
 var uri = 'http://api.map.baidu.com/marker?location='+ location.lat+','+location.lng +'&title='+response.result.level+'&content='+address+'&output=html';
 var staticimageUrl = "http://api.map.baidu.com/staticimage?center=" + location.lng+','+location.lat + "&markers=" + location.lng+','+location.lat;
 html = '<p>坐標(biāo):緯度: ' + location.lat + " 經(jīng)度: " + location.lng+'<br />';
 html += '精度: '+response.result.precise+'<br />' ;
 html += '可信度: '+response.result.confidence +'<br />';
 html += '地址類型: '+response.result.level+'</p>' ;
 html += '<p><img src="' + staticimageUrl + '" /></p>' ;
 html += '<p>分享該點(diǎn): <a href="' + uri + '" target="_blank">' + uri + '</a></p>'; //將該鏈接設(shè)置成可單擊
 // 百度地圖API功能
 map = new BMap.Map("allmap");
 var point = new BMap.Point(bxx, byy);
 var marker = new BMap.Marker(point); // 創(chuàng)建標(biāo)注
 map.addOverlay(marker); // 將標(biāo)注添加到地圖中
 map.centerAndZoom(point, 100);
 var opts = {
 width: 200, // 信息窗口寬度
 height: 100, // 信息窗口高度
 title: "我的位置", // 信息窗口標(biāo)題
 enableMessage: true,//設(shè)置允許信息窗發(fā)送短息
 message: result.formatted_address
 }

 $("#divPo").html("當(dāng)前位置:" + result.formatted_address);
 var infoWindow = new BMap.InfoWindow(result.formatted_address, opts); // 創(chuàng)建信息窗口對(duì)象
 marker.addEventListener("click", function () {
 map.openInfoWindow(infoWindow, point); //開啟信息窗口
 });

 var myIcon = new BMap.Icon("http://api.map.baidu.com/img/markers.png", new BMap.Size(23, 25), {
 offset: new BMap.Size(10, 25), // 指定定位位置
 imageOffset: new BMap.Size(0, 0 - 10 * 25) // 設(shè)置圖片偏移
 });

 var pois = result.pois;
 for(var i=0;i<pois.length;i++){
 var marker = new BMap.Marker(new BMap.Point(pois[i].point.x,pois[i].point.y),{icon:myIcon}); // 創(chuàng)建標(biāo)注
 var name = pois[i].name;
 var addr = pois[i].addr;
 map.addOverlay(marker); // 將標(biāo)注添加到地圖中
 addClickHandler(name,addr,marker);
 }

 $("#mask").hide();
 $("#btnSign").show();
 return;
 }

 function addClickHandler(name,addr,marker){
 marker.addEventListener("click",function(e){
 openInfo(name,addr,e)}
 );
 }

 function openInfo(name,addr,e){
 var p = e.target;
 var point = new BMap.Point(p.getPosition().lng, p.getPosition().lat);
 var opts = {
 width: 200, // 信息窗口寬度
 height: 100, // 信息窗口高度
 title: name, // 信息窗口標(biāo)題
 enableMessage: true,//設(shè)置允許信息窗發(fā)送短息
 message: addr
 }
 var infoWindow = new BMap.InfoWindow(addr,opts); // 創(chuàng)建信息窗口對(duì)象
 map.openInfoWindow(infoWindow,point); //開啟信息窗口
 }

 function doOptions() {
 var script = document.createElement('script');
 script.type = 'text/javascript';
 ADVANCED_POST ="http://api.map.baidu.com/geocoder/v2/?ak=dhRLKMR9QUO4wHmnnSZTartg&callback=renderOption&location=" + byy + ","+bxx+ "&output=json&pois=2";
 script.src = ADVANCED_POST;
 document.body.appendChild(script);
 };

 $(function () {
 $("#mask").show();
 $("#btnSign").hide();
 changePosition();
 });
 </script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="cphTitle" runat="server">
 在線簽到
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="cphContainer" runat="server">
 <form id="frmLocation" runat="server">
 <div class="box mb50">
 <div class="hd"><span>位置信息</span></div>
 <div class="bd" style="padding-left: 0">
 <ul class="stipx" style="height: 300px;">
  <div id="allmap"></div>
 </ul>
 </div>
 <div class="bd" style="padding-left: 0">
 <ul class="stipx">
  <div id="divPo"></div>
 </ul>
 </div>
 </div>
 <div class="next_btn" style="text-align: center; margin-top: -50px;">
 <input id="btnSign" type="button" value="我要簽到" style="cursor: pointer; width: 210px; height: 50px; border-radius: 15px; background-color: #00CD00; border: 0px #FE6714 solid; cursor: pointer; color: white; font-size: 16px;" />
 </div>
 <div class="mask" style="display: none;">
 <span>
 <img src="/templates/txwap/images/mask.gif" />
 </span>
 </div>
 </form>
</asp:Content>

本頁面主要涉及到百度地圖開放平臺(tái),要申請(qǐng)百度地圖ag。否則調(diào)用js則提示:APP不存在,AK有誤請(qǐng)重新檢查在重試。

(1)百度地圖技術(shù)一:坐標(biāo)轉(zhuǎn)換API

官網(wǎng)地址:http://lbsyun.baidu.com/index.php?title=webapi/guide/changeposition

API服務(wù)地址:http://api.map.baidu.com/geoconv/v1/?

文檔有詳細(xì)的說明,不再贅述哦。

(2)百度地圖技術(shù)二:根據(jù)坐標(biāo)獲取位置

官網(wǎng)網(wǎng)址:http://lbsyun.baidu.com/index.php?title=webapi/guide/webservice-geocoding

Geocoding API包括地址解析和逆地址解析功能:

地理編碼:即地址解析,由詳細(xì)到街道的結(jié)構(gòu)化地址得到百度經(jīng)緯度信息,例如:“北京市海淀區(qū)中關(guān)村南大街27號(hào)”地址解析的結(jié)果是“l(fā)ng:116.31985,lat:39.959836”。同時(shí),地理編碼也支持名勝古跡、標(biāo)志性建筑名稱直接解析返回百度經(jīng)緯度,例如:“百度大廈”地址解析的結(jié)果是“l(fā)ng:116.30815,lat:40.056885” ,通用的POI檢索需求,建議使用Place API。

逆地理編碼:即逆地址解析,由百度經(jīng)緯度信息得到結(jié)構(gòu)化地址信息,例如:“l(fā)at:31.325152,lng:120.558957”逆地址解析的結(jié)果是“江蘇省蘇州市虎丘區(qū)塔園路318號(hào)”。

API服務(wù)地址:http://api.map.baidu.com/geocoder/v2/

具體參數(shù)可查看官方文檔。

示例:http://api.map.baidu.com/geocoder/v2/?ak=申請(qǐng)的百度KEY&location=34.79563,114.23075222912&callback=showLocation&output=xml&pois=1

注意事項(xiàng):

(1)百度開發(fā)者key申請(qǐng)

(2)百度地圖坐標(biāo)系統(tǒng)與微信的坐標(biāo)系統(tǒng)不同

(3)api調(diào)用地址及參數(shù)說明

(4)api回調(diào)函數(shù)意義

(5)理解json與jsonp的含義

3、微信JS-SDK核心代碼

(1)JsAPI.cs生成相關(guān)JS-SDK配置參數(shù)

using System;
using System.Globalization;
using System.Linq;
using System.Web.Security;
using System.Web.UI;
using WxPayAPI;

namespace WxJsSDK
{
 public class JsApi
 {
 /// <summary>
 /// 保存頁面對(duì)象,因?yàn)橐陬惖姆椒ㄖ惺褂肞age的Request對(duì)象
 /// </summary>
 private Page page { get; set; }

 public WxJsData ResultJsData { get; set; }

 /// <summary>
 ///
 /// </summary>
 /// <param name="page"></param>
 public JsApi(Page page)
 {
 this.page = page;
 }

 public WxJsData GetJsData()
 {
 var data = new WxJsData();
 data.SetValue("appid", WxPayConfig.APPID);//公眾賬號(hào)ID
 data.SetValue("timestamp", WxPayApi.GenerateTimeStamp());
 data.SetValue("noncestr", WxPayApi.GenerateNonceStr());//隨機(jī)字符串

 var url = GetUrl();
 data.SetValue("url", url);
 var jsToken = GetJsApiTicket();
 data.SetValue("jsapi_ticket", jsToken);
 var signature = MakeSignature(jsToken, data.GetValue("noncestr").ToString(), data.GetValue("timestamp").ToString(), url);
 data.SetValue("signature", signature);

 ResultJsData = data;
 return data;
 }

 private string MakeSignature(string jsapiTicket, string noncestr, string timestamp, string url)
 {
 string[] arrayList =
 {
 "jsapi_ticket=" + jsapiTicket,
 "timestamp=" + timestamp,
 "noncestr=" + noncestr,
 "url=" + url
 };
 Array.Sort(arrayList);
 var signature = string.Join("&", arrayList);
 signature = FormsAuthentication.HashPasswordForStoringInConfigFile(signature, "SHA1").ToLower();
 return signature;
 }

 private string GetJsApiTicket()
 {
 var jsAuth = new JsAuthorizeAction();
 var token = jsAuth.GetToken();
 var nd = DateTime.Now - token.CreateDate;
 Log.Error(this.GetType().ToString(), token.access_token);
 Log.Error(this.GetType().ToString(), token.IsValid().ToString());
 if (token.IsValid())
 return jsAuth.GetJsApiTicket(token.access_token).ticket;
 return "";
 }

 private string GetUrl()
 {
 string host = page.Request.Url.Host;
 string path = page.Request.Path;
 string queryString = page.Request.Url.Query;
 //這個(gè)地方要注意,參與簽名的是網(wǎng)頁授權(quán)獲取用戶信息時(shí)微信后臺(tái)回傳的完整url
 string url = "http://" + host + path + queryString;
 return url;
 }

 public string GetJsApiParameters()
 {
 Log.Debug(this.GetType().ToString(), "JsApi ::GetJsApiParam is processing...");

 string parameters = ResultJsData.ToJson();

 Log.Debug(this.GetType().ToString(), "Get JsApi : " + parameters);
 return parameters;
 }
 }
}

(2)JsAuthorizeAction.cs微信JS-SDK相關(guān)API調(diào)用函數(shù)

using Payment.WxWebHlper;
using Payment.WxWebHlper.Results;
using System;
using WxPayAPI;

namespace WxJsSDK
{
 public class JsAuthorizeAction
 {
 private static TokenResult Token = new TokenResult() { errcode = -1 };
 private static JsApiTicketResult JsApiTicket = new JsApiTicketResult() { errcode = -1 };

 public TokenResult GetToken()
 {
 Log.Error(this.GetType().ToString(), "GetToken");
 if (!Token.IsValid())
 {
 Token = GeTokenResult();
 Log.Error(this.GetType().ToString(), Token.ToString());
 }
 return Token;
 }

 /// <summary>
 ///
 /// </summary>
 /// <returns></returns>
 public TokenResult GeTokenResult()
 {
 var result = new TokenResult();
 try
 {
 var webUtils = new WebUtils();
 var url = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", WxPayConfig.APPID, WxPayConfig.APPSECRET);
 var strRtn = webUtils.Get(url);
 result = Tools.JsonStringToObj<TokenResult>(strRtn);
 }
 catch (Exception ex)
 {
 Log.Error(this.GetType().ToString(), ex.Message);
 result = new TokenResult() { errcode = -1086 };
 }
 return result;
 }

 /// <summary>
 ///
 /// </summary>
 /// <param name="token"></param>
 /// <returns></returns>
 public JsApiTicketResult GetJsApiTicket(string token)
 {
 Log.Error(this.GetType().ToString(), "GetJsApiTicket傳入token:" + token);
 if (!JsApiTicket.IsValid())
 {
 JsApiTicket = GetJsApiTicketResult(token);
 }
 return JsApiTicket;
 }

 /// <summary>
 ///
 /// </summary>
 /// <param name="token"></param>
 /// <returns></returns>
 public JsApiTicketResult GetJsApiTicketResult(string token)
 {
 JsApiTicketResult result;
 try
 {
 var webUtils = new WebUtils();
 var url = string.Format("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={0}&type=jsapi", token);
 var strRtn = webUtils.Get(url);
 result = Tools.JsonStringToObj<JsApiTicketResult>(strRtn);
 }
 catch (Exception ex)
 {
 Log.Error(this.GetType().ToString(), ex.Message);
 result = new JsApiTicketResult() { errcode = -1086 };
 }
 return result;
 }
 }

 public class JsApiTicketResult : ReturnResult
 {
 /// <summary>
 /// 構(gòu)造函數(shù)
 /// </summary>
 public JsApiTicketResult()
 {
 CreateDate = DateTime.Now;
 }

 /// <summary>
 ///
 /// </summary>
 public string ticket { get; set; }

 /// <summary>
 /// access_token接口調(diào)用憑證超時(shí)時(shí)間,單位(秒)
 /// </summary>
 public int expires_in { get; set; }

 /// <summary>
 /// 創(chuàng)建時(shí)間
 /// </summary>
 public DateTime CreateDate { get; set; }

 /// <summary>
 /// 判斷是否有效
 /// </summary>
 /// <returns></returns>
 public bool IsValid()
 {
 if (this.errcode != 0)
 return false;
 var nd = DateTime.Now - CreateDate;
 return nd.Seconds < 7200;
 }
 }

 public class TokenResult : ReturnResult
 {
 /// <summary>
 /// 構(gòu)造函數(shù)
 /// </summary>
 public TokenResult()
 {
 CreateDate = DateTime.Now;
 }

 /// <summary>
 /// 網(wǎng)頁授權(quán)接口調(diào)用憑證,注意:此access_token與基礎(chǔ)支持的access_token不同
 /// </summary>
 public string access_token { get; set; }

 /// <summary>
 /// access_token接口調(diào)用憑證超時(shí)時(shí)間,單位(秒)
 /// </summary>
 public int expires_in { get; set; }

 /// <summary>
 /// 創(chuàng)建時(shí)間
 /// </summary>
 public DateTime CreateDate { get; set; }

 /// <summary>
 /// 判斷是否有效
 /// </summary>
 /// <returns></returns>
 public bool IsValid()
 {
 if (this.errcode != 0)
 return false;
 var nd = DateTime.Now - CreateDate;
 return nd.Seconds < 7200;
 }
 }
}

(3)WxJsData.cs微信JS-SDK參數(shù)類

using LitJson;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using System.Xml;
using WxPayAPI;

namespace WxJsSDK
{
 public class WxJsData
 {
 private SortedDictionary<string, object> m_values = new SortedDictionary<string, object>();
 /**
 * 設(shè)置某個(gè)字段的值
 * @param key 字段名
 * @param value 字段值
 */

 public void SetValue(string key, object value)
 {
 m_values[key] = value;
 }

 /**
 * 根據(jù)字段名獲取某個(gè)字段的值
 * @param key 字段名
 * @return key對(duì)應(yīng)的字段值
 */

 public object GetValue(string key)
 {
 object o = null;
 m_values.TryGetValue(key, out o);
 return o;
 }

 /**
 * 判斷某個(gè)字段是否已設(shè)置
 * @param key 字段名
 * @return 若字段key已被設(shè)置,則返回true,否則返回false
 */

 public bool IsSet(string key)
 {
 object o = null;
 m_values.TryGetValue(key, out o);
 if (null != o)
 return true;
 return false;
 }

 /**
 * @將Dictionary轉(zhuǎn)成xml
 * @return 經(jīng)轉(zhuǎn)換得到的xml串
 * @throws WxPayException
 **/

 public string ToXml()
 {
 //數(shù)據(jù)為空時(shí)不能轉(zhuǎn)化為xml格式
 if (0 == m_values.Count)
 {
 Log.Error(this.GetType().ToString(), "WxPayData數(shù)據(jù)為空!");
 throw new WxPayException("WxPayData數(shù)據(jù)為空!");
 }

 string xml = "<xml>";
 foreach (KeyValuePair<string, object> pair in m_values)
 {
 //字段值不能為null,會(huì)影響后續(xù)流程
 if (pair.Value == null)
 {
  Log.Error(this.GetType().ToString(), "WxPayData內(nèi)部含有值為null的字段!");
  throw new WxPayException("WxPayData內(nèi)部含有值為null的字段!");
 }

 if (pair.Value.GetType() == typeof(int) || pair.Value.GetType() == typeof(decimal))
 {
  xml += "<" + pair.Key + ">" + pair.Value.ToString() + "</" + pair.Key + ">";
 }
 else if (pair.Value.GetType() == typeof(string))
 {
  xml += "<" + pair.Key + ">" + "<![CDATA[" + pair.Value + "]]></" + pair.Key + ">";
 }
 else//除了string和int類型不能含有其他數(shù)據(jù)類型
 {
  Log.Error(this.GetType().ToString(), "WxPayData字段數(shù)據(jù)類型錯(cuò)誤!");
  throw new WxPayException("WxPayData字段數(shù)據(jù)類型錯(cuò)誤!");
 }
 }
 xml += "</xml>";
 return xml;
 }

 /**
 * @將xml轉(zhuǎn)為WxPayData對(duì)象并返回對(duì)象內(nèi)部的數(shù)據(jù)
 * @param string 待轉(zhuǎn)換的xml串
 * @return 經(jīng)轉(zhuǎn)換得到的Dictionary
 * @throws WxPayException
 */

 public SortedDictionary<string, object> FromXml(string xml)
 {
 if (string.IsNullOrEmpty(xml))
 {
 Log.Error(this.GetType().ToString(), "將空的xml串轉(zhuǎn)換為WxPayData不合法!");
 throw new WxPayException("將空的xml串轉(zhuǎn)換為WxPayData不合法!");
 }

 XmlDocument xmlDoc = new XmlDocument();
 xmlDoc.LoadXml(xml);
 XmlNode xmlNode = xmlDoc.FirstChild;//獲取到根節(jié)點(diǎn)<xml>
 XmlNodeList nodes = xmlNode.ChildNodes;
 foreach (XmlNode xn in nodes)
 {
 XmlElement xe = (XmlElement)xn;
 m_values[xe.Name] = xe.InnerText;//獲取xml的鍵值對(duì)到WxPayData內(nèi)部的數(shù)據(jù)中
 }

 try
 {
 //2015-06-29 錯(cuò)誤是沒有簽名
 if (m_values["return_code"] != "SUCCESS")
 {
  return m_values;
 }
 CheckSign();//驗(yàn)證簽名,不通過會(huì)拋異常
 }
 catch (WxPayException ex)
 {
 throw new WxPayException(ex.Message);
 }

 return m_values;
 }

 /**
 * @Dictionary格式轉(zhuǎn)化成url參數(shù)格式
 * @ return url格式串, 該串不包含sign字段值
 */

 public string ToUrl()
 {
 string buff = "";
 foreach (KeyValuePair<string, object> pair in m_values)
 {
 if (pair.Value == null)
 {
  Log.Error(this.GetType().ToString(), "WxPayData內(nèi)部含有值為null的字段!");
  throw new WxPayException("WxPayData內(nèi)部含有值為null的字段!");
 }

 if (pair.Key != "sign" && pair.Value.ToString() != "")
 {
  buff += pair.Key + "=" + pair.Value + "&";
 }
 }
 buff = buff.Trim('&');
 return buff;
 }

 /**
 * @Dictionary格式化成Json
 * @return json串?dāng)?shù)據(jù)
 */

 public string ToJson()
 {
 string jsonStr = JsonMapper.ToJson(m_values);
 return jsonStr;
 }

 /**
 * @values格式化成能在Web頁面上顯示的結(jié)果(因?yàn)閣eb頁面上不能直接輸出xml格式的字符串)
 */

 public string ToPrintStr()
 {
 string str = "";
 foreach (KeyValuePair<string, object> pair in m_values)
 {
 if (pair.Value == null)
 {
  Log.Error(this.GetType().ToString(), "WxPayData內(nèi)部含有值為null的字段!");
  throw new WxPayException("WxPayData內(nèi)部含有值為null的字段!");
 }

 str += string.Format("{0}={1}<br>", pair.Key, pair.Value.ToString());
 }
 Log.Debug(this.GetType().ToString(), "Print in Web Page : " + str);
 return str;
 }

 /**
 * @生成簽名,詳見簽名生成算法
 * @return 簽名, sign字段不參加簽名
 */

 public string MakeSign()
 {
 //轉(zhuǎn)url格式
 string str = ToUrl();
 //在string后加入API KEY
 str += "&key=" + WxPayConfig.KEY;
 //MD5加密
 var md5 = MD5.Create();
 var bs = md5.ComputeHash(Encoding.UTF8.GetBytes(str));
 var sb = new StringBuilder();
 foreach (byte b in bs)
 {
 sb.Append(b.ToString("x2"));
 }
 //所有字符轉(zhuǎn)為大寫
 string result = sb.ToString().ToUpper();
 return result;
 }

 public string MakeAppSign()
 {
 //轉(zhuǎn)url格式
 string str = ToUrl();
 //在string后加入API KEY
 str += "&key=" + WxPayConfig.KEYofAPP;
 //MD5加密
 var md5 = MD5.Create();
 var bs = md5.ComputeHash(Encoding.UTF8.GetBytes(str));
 var sb = new StringBuilder();
 foreach (byte b in bs)
 {
 sb.Append(b.ToString("x2"));
 }
 //所有字符轉(zhuǎn)為大寫
 string result = sb.ToString().ToUpper();
 return result;
 }

 /**
 *
 * 檢測(cè)簽名是否正確
 * 正確返回true,錯(cuò)誤拋異常
 */

 public bool CheckSign()
 {
 //如果沒有設(shè)置簽名,則跳過檢測(cè)
 if (!IsSet("sign"))
 {
 Log.Error(this.GetType().ToString(), "WxPayData簽名存在但不合法!");
 throw new WxPayException("WxPayData簽名存在但不合法!");
 }
 //如果設(shè)置了簽名但是簽名為空,則拋異常
 if (GetValue("sign") == null || GetValue("sign").ToString() == "")
 {
 Log.Error(this.GetType().ToString(), "WxPayData簽名存在但不合法!");
 throw new WxPayException("WxPayData簽名存在但不合法!");
 }

 //獲取接收到的簽名
 string return_sign = GetValue("sign").ToString();

 //在本地計(jì)算新的簽名
 string cal_sign = MakeSign();

 if (cal_sign == return_sign)
 {
 return true;
 }

 Log.Error(this.GetType().ToString(), "WxPayData簽名驗(yàn)證錯(cuò)誤!");
 throw new WxPayException("WxPayData簽名驗(yàn)證錯(cuò)誤!");
 }

 /**
 * @獲取Dictionary
 */

 public SortedDictionary<string, object> GetValues()
 {
 return m_values;
 }
 }
}

提示信息:相關(guān)解析思路可參考微信公眾號(hào)支付官方SDK,下載地址:https://pay.weixin.qq.com/wiki/doc/api/jsapi_sl.php?chapter=11_1

本文已被整理到了《JavaScript微信開發(fā)技巧匯總》,歡迎大家學(xué)習(xí)閱讀。

為大家推薦現(xiàn)在關(guān)注度比較高的微信小程序教程一篇:《微信小程序開發(fā)教程》小編為大家精心整理的,希望喜歡。

以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論