WeChat JS-SDK가 개발되는 동안 GetLocation은 좌표 위치를 얻는 데 사용됩니다. WeChat에서 얻은 좌표를 Baidu지도에 직접 적용하는 방법 : 다음 효과를 표시합니다.
참고 : 빨간색 아이콘은 WeChat에서 변환 된 위치이며 파란색 아이콘은 주변의 위치입니다. 먼저 WeChat 개발 과정에서 설명해 봅시다.
1. Wechat JS-SDK 개발 문서
먼저 공식 웹 사이트에 도움말 문서를 입력하십시오 : https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115&token=&lang=zh_cn
문서를 자세히 연구 할 수 있습니다. 위치 정보를 얻기 위해 다음 단계는 다음 단계로 나뉩니다.
1 단계 : 도메인 이름을 바인딩합니다
WeChat 공식 계정을 입력하고 "공식 계정 설정"메뉴를 찾은 다음 "기능 설정"패널을 입력하십시오.
"설정"을 클릭하여 js를 참조하는 관련 도메인 이름을 설정하십시오.
2 단계 : 공식 JS 클래스 라이브러리 인용
JS 인터페이스 (지원 https)를 호출 해야하는 페이지에 다음 JS 파일을 소개하십시오. http://res.wx.qq.com/open/js/jweixin-1.0.0.js.
참조 페이지는 다음과 같이 location.aspx입니다.
< %@ page title = "위치"언어 = "C#"AutoeventWireUp = "true"MasterPageFile = "~/wxcrm/site.mas src = "http://res.wx.qq.com/open/js/jweixin-1.0.js"> </script> <script type = "text/javaScript"> $ ( "#mask"). show (); wx.config ({debug : false, // debug mode, true, true, 각 js 함수 호출은 appid : '< %= resultjsdata.getValue ( "appid") %>', // 필수, 공식 계정의 고유 식별자의 고유 식별자 : < %= resultjsdata.getValue ( "timestamp"), // suptamp nonectam : // 생성. '< %= resultjsdata.getValue ( "noncest") %>', // 필수, 서명 임의 문자열 서명을 생성합니다. 'onmenushareweibo', 'hidemenuitems', 'showmenuitems', 'hideallnonbasemenuitems', 'showallnonbasemenuitems', 'showallnonbasemenuitems', 'showallnonbasemenuitems', 'transtrecord', 'stortrecord', '', 'stortrecord', 'PlayVoice', 'pauseVoice', 'stopVoice', 'uploadVoice', 'downloadVoice', 'downloadImage', 'previewimage', 'uploadImage', 'downloadImage', 'getnetworktype', 'getLocation', 'hideoptionmenu', 'scotewoTopoTo', ''scotewoToco '' 'ChooseWXPAY', 'OpenProductSpecificView', 'AddCard', 'Choosecard', 'OpenCard'}); wx.ready (function () {wx.checkjsapi ({jsapilist : [ 'getnetworktype', 'previewimage', 'getlocation'], success : function (res) {}}); wx.getLocation ({wgs84 ', // gps coordinates의 gps 코디네이네이션이 wgs84를 사용했다. OpenLocation은 'GCJ02'를 통과 할 수 있습니다. 위치 정확도 // aalert (jsonuti.converttostring (res)); // wx.openlocation ({// latitude : // latitude, floating point 번호, 범위 : res.longitude, // longritude, floating point 번호, 범위 : // pational position. View ', // 주소 세부 사항 // 척도 : // Zoom 레벨, 값 값, 값 값, 1에서 28까지의 맵 맵 줌 레벨입니다. 기본값은 최대 // 포다입니다 : "location1.aspx? m = home & c = index & a = getLocation & location ="+latitude+"& longitude ="+longitude // joming the theam the theam에 표시 될 수 있습니다. // Alert ( "#mask"). CONCEL : res) {wind wx.error (function (res) {// 구성 정보 확인 실패는 오류 함수를 실행합니다. 서명이 만료되면 확인이 실패합니다. 특정 오류 메시지의 경우 구성 모드를 열거나 반환 된 해안 매개 변수에서 볼 수 있습니다. wx.fail (function (res) {}); </script> </asp : content> <content = "content2"content2 "contentplaceholderid ="cphtitle "runat ="server "> 위치 가져 오기 </asp : content> <asp :"content3 "contentplaceholderid ="cphcontainer "runat ="server "> 정보 ... </div> </center> <div style = "display : none;"> <span> <img src = "/templates/txwap/images/mask.gif"/> </span> </div> </asp : content>페이지 효과 :
참고 :
(1) 휴대 전화 설정이 WeChat이 위치 정보를 얻을 수 있도록 허용하지 않으면 위의 정보가 촉진됩니다.
(2) 위 그림의 파라미터는 GPS 좌표를 얻습니다. Baidu 맵을 사용하는 경우 특정 변환을해야하며 Location1.aspx에 반영됩니다.
(3) JS-SDK가 필요한 모든 페이지에는 구성 정보가 먼저 주입되어야합니다. 그렇지 않으면 호출되지 않습니다.
해당 Location.aspx.cs 구현 :
payment.wxwebhlper; payment.wxwebhlper.actions를 사용하여 시스템 사용; 시스템 사용; 시스템 사용; wxpayapi 사용; wxpayapi 사용; 네임 스페이스 dtcms.web.wxcrm 사용 사용 세트; } 보호 된 문자열 timestamp {get; 세트; } 보호 된 문자열 noncestr {get; 세트; } 보호 된 문자열 서명 {get; 세트; } public static String wxjsapiparam {get; 세트; } public wxjsdata resultjsdata {get; 세트; } Protected void page_load (Object Sender, EventArgs e) {judgecode (); var webauthorize = 새로운 webauthorizeaction (); code2tokenresult = webauthorize.code2token (요청 [ "code"]); if (code2tokenresult.haserror ()) {response.redirect (urls.pageoflocation); gotononepage ( "사용자 자격 증명을 얻지 못했고, 다시 get"); 반품; } getUserInforesult = webauthorize.getUserInfo (code2tokenresult.access_token); if (getUserInforesult.haserRor ()) {gotonOnepage ( "사용자 정보를 얻지 못했습니다. 다시 get"); } var userId = wxoperation.hasbind (getuserinforesult.openid); if (userId.equals (Guid.Empty)) {response.redirect (urls.oauth2Url); gotononepage ( "wechat user bound"); } appid = wxpayconfig.appid; timestamp = wxpayapi.generateTimestamp (); noncest = wxpayapi.generatenoncest (); // 다음 구현은 3에 반영됩니다. 핵심 코드 구현 var jsapi = new Jsapi (this); resultjsdata = jsapi.getjsdata (); wxjsapiparam = jsapi.getjsapiparameters (); // js api 매개 변수를 조정하려면 h5를 가져옵니다}}}2. WeChat GPS 좌표를 Baidu 좌표로 변환합니다
WeChat이 좌표를 성공적으로 얻은 후 페이지는 자동으로 Location1.aspx로 이동하며 처리 흐름은 다음과 같습니다.
WeChat 좌표 -> Baidu 맵 좌표로 변환 -> Baidu Map API에 따라 위치 정보 얻기 -> Baidu Map API에 따른 디스플레이 좌표
< %@ page title = "온라인 체크인"언어 = "C#"MasterPageFile = "~/wxcrm/site.mas 이름 = "Viewport"Content = "Initial-Scale = 1.0, user-scalable = no" /> <style type = "text /css"> #allmap {너비 : 100%; 높이 : 300px; } </style> <script type = "text/javaScript"src = "http://api.map.baidu.com/api?v=2.0&ak=dhrlkmr9quo4whmnnsztarta"> </script> <script> <script>/javaScript "> // gps condritation. %>; // 경도, 부동 소수점 번호, 범위는 180 ~ -180입니다. var xx = < %= this.request [ "latitude"] %>; // 위도, 부동 소수점 번호, 범위는 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/?"; 함수 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 (스크립트); } function dealResult (msg) {if (msg.status! = 0) {alert ( "올바른 반환 결과 없음"); $ ( "#mask"). hide (); 반품; } //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 & ak = dhrlkmr9quo4whmnnsztarta"; $ .ajax ({url : url, success : function (data, status, xhr) {alert (status); alert (data.status);}, datatype : json}); } var advanced_post = ''; var advancedoptions = ''; var 주소; var지도; 함수 renderOption (응답) {var html = ''; if (response.status) {$ ( "#mask"). hide (); var text = "올바른 반환 결과가 없습니다!"; 경고 (텍스트); 반품; } 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> 좌표 : 위도 :' + location.lat + "longitude :" + location.lng + '<br />'; html+= '정밀 :'+response.result.precise+'<br />'; html += 'currency :' +response.result.confidence +'<br />'; html+= '주소 유형 :'+response.result.level+'</p>'; html + = '<p> <img src = "' + staticimageurl + '" /> < /p>'; html + = '<p>이 점을 공유하십시오. <a href = "' + uri + '"target = "_ blank">' + uri + '</a> </p>'; //이 링크를 클릭 가능로 설정 // baidu map API 함수 map = new bmap.map ( "AllMap"); var point = new bmap.point (bxx, byy); var 마커 = 새로운 bmap.marker (point); // 주석 맵을 만듭니다 .addoverlay (마커); // 맵 맵에 주석을 추가합니다 .CenterAndZoom (Point, 100); var opts = {width : 200, // 정보 창 너비 높이 : 100, 정보 창 높이 제목 : "내 위치", // 정보 창 제목 enableMessage : // 정보를 설정하여 짧은 메시지를 보내도록 허용됩니다. result.formatted_address} $ ( "#divpo"). var infowindow = new bmap.infowindow (result.formatted_address, opts); // 정보 창 윈드 개체 마커를 만듭니다 .adeventListener ( "click", function () {map.openinFowIndow (InfowIndow, Point); // 정보 창을 엽니 다); var myicon = new bmap.icon ( "http://api.map.baidu.com/img/markers.png", new bmap.size (23, 25), {오프셋 : new bmap.size (10, 25), // 포지셔닝 위치 ImageOffset : New Bmap.size (0, 0))); 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}); // 주석 생성 var name = pois [i] .name; var addr = pois [i] .addr; map.addoverlay (마커); //지도에 주석을 추가합니다 addClickHandler (이름, addr, 마커); } $ ( "#mask"). hide (); $ ( "#btnsign"). show (); 반품; } 함수 addClickHandler (이름, addr, 마커) {Marker.adeventListener ( "click", function (e) {OpenInfo (이름, addr, e)}); } 함수 OpenInfo (이름, addr, e) {var p = e.target; var point = new bmap.point (p.getPosition (). lng, p.getPosition (). lat); var opts = {너비 : 200, // 정보 창 너비 높이 : 100, // 정보 창 높이 제목 : 이름, // 정보 창 제목 enablemessage : true, // 정보 창이 짧은 메시지를 보내도록 허용합니다 : addr} var infowindow = new bmap.infowindow (addr, opts); // 정보 창을 만듭니다. // 정보 창을 엽니 다. 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 (스크립트); }; $ (function () {$ ( "#mask"). show (); $ ( "#btnsign"). hide (); ChangePosition ();}); </script> </asp : content> <ASP : Content2 "Content2"ContentPlaceHolderID = "cphTitle"runat = "Server"> 온라인 체크인 </asp : content> <asp : "content3"contentplaceHolderID = "cphcontainer"runat = "server"> frmlocation = "run ="frmlocation "> 정보 </span> </div> <div style = "padding-left : 0"> <ul Style = "height : 300px;"> <div id = "allmap"> </div> </ul> </div> <div style = "padding-left : 0"> <ul> <div id = "divpo"> </div> </div> </ul style = " -50px; /> </div> <div style = "display : none;"> <span> <img src = "/templates/txwap/images/mask.gif"/> </span> </div> </form> </asp : content>이 페이지에는 주로 Baidu Map Open Platform이 포함되며 Baidu Map Ag를 신청해야합니다. 그렇지 않으면 JS를 호출하면 앱이 존재하지 않습니다. 앱이 존재하지 않습니다. AK에 오류가 있으면 다시 확인하고 다시 시도하십시오.
(1) 바이두지도 기술 1 : 조정 전환 API
공식 웹 사이트 주소 : http://lbsyun.baidu.com/index.php?title=webapi/guide/changeposition
API 서비스 주소 : http://api.map.baidu.com/geoconv/v1/?
문서에는 자세한 설명이 있으므로 반복하지 않습니다.
(2) Baidu Map Technology 2 : 좌표를 기반으로 위치 얻기
공식 웹 사이트 : http://lbsyun.baidu.com/index.php?title=webapi/guide/webservice-geocoding
지오 코딩 API에는 주소 해상도 및 역 주소 해상도 기능이 포함되어 있습니다.
지리적 인코딩 : 즉, 주소 분석 및 바이두 위도 및 경도 정보는 거리의 자세한 구조화 된 주소에서 얻습니다. 예를 들어, "No. 27, Zhongguancun South Street, Haidian District, Beijing"의 주소 분석 결과는 "LNG : 116.31985, LAT : 39.959836"입니다. 동시에 지오 코딩은 또한 장소, 역사적 유적지 및 랜드 마크 건물의 직접 해상도를 지원하고 바이두 위도 및 경도로 돌아갑니다. 예를 들어, "Baidu Building"의 주소 분석 결과는 "LNG : 116.30815, LAT : 40.056885"입니다. 일반적인 POI 검색 요구 사항이며 Place API를 사용하는 것이 좋습니다.
역 지오 코딩 : 즉 역 주소 분석 및 구조화 된 주소 정보는 바이두 위도 및 경도 정보에서 얻습니다. 예를 들어, "LAT : 31.325152, LNG : 120.558957"역 주소 분석 결과는 "No. 318, Tayuan Road, Huqiu District, Suzhou City, Jiangsu Province"입니다.
API 서비스 주소 : http://api.map.baidu.com/geocoder/v2/
특정 매개 변수는 공식 문서를 확인하십시오.
예 : http://api.map.baidu.com/geocoder/v2/?ak= baidu 키 및 위치에 대한 appriched = 34.79563,114.23075222912 & callback = showlocation & output = xml & pois = 1
참고 :
(1) 바이두 개발자 키 응용 프로그램
(2) Baidu Map 좌표 시스템은 WeChat 좌표계와 다릅니다.
(3) API 호출 주소 및 매개 변수 설명
(4) API 콜백 함수의 의미
(5) JSON과 JSONP의 의미를 이해하십시오
3. Wechat JS-SDK 핵심 코드
(1) JSAPI.CS는 관련 JS-SDK 구성 매개 변수를 생성합니다
System.globalization 사용; System.Linq 사용; System.Web.Security 사용; System.Web.ui 사용; WXPayAPI 사용; 네임 스페이스 WXJSSDK {public class jsapi {// <summary> // // 페이지의 요청에 따라 페이지의 요청 대상을 클래스에 사용하려면 클래스의 메소드를 사용하려면 클래스 >/ </summary page page get; 세트; } public wxjsdata resultjsdata {get; 세트; } /// <summary> // // </summary> /// <param name = "page"> </param> public jsapi (페이지 페이지) {this.page = page; } public wxjsdata getJsData () {var data = new WxjsData (); data.setValue ( "appid", wxpayconfig.appid); // public acc data.setValue ( "noncest", wxpayapi.generatenoncest ()); // random string var url = geturl (); data.setValue ( "url", url); var jstoken = getJsapiticket (); data.setValue ( "jsapi_ticket", jstoken); var signature = MakesIgnature (jstoken, data.getValue ( "noncest"). toString (), data.getValue ( "timestamp"). toString (), url); data.setValue ( "서명", 서명); resultjsdata = data; 반환 데이터; } private string makeSignature (String jsapiticket, String noncest, String timestamp, String url) {String [] arraylist = { "jsapi_ticket =" + jsapiticket, "timestamp =" + timestamp, "noncest =" + noncestr = " + url}; Array.SORT (ArrayList); var signature = string.join ( "&", arraylist); signature = formsauthentication.hashpasswordforstoringinconfigfile (Signature, "Sha1"). tolower (); 반환 서명; } 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 ()) reture jsauth.getjsapiticket (token.access_token) .ticket; 반품 ""; } private String getUrl () {문자열 host = page.request.url.host; 문자열 경로 = page.request.path; 문자열 querystring = page.request.url.query; //이 장소는 웹 페이지가 사용자 정보 문자열을 얻을 수있는 권한이있을 때 완전한 URL이 WeChat 배경으로 전달된다는 점에 유의해야합니다. 반환 URL; } public String getJsapiparameters () {log.debug (this.getType (). toString (), "jsapi :: getJsapiparam은 처리 중 ..."); 문자열 매개 변수 = resultjsdata.tojson (); log.debug (this.getType (). toString (), "get jsapi :" + 매개 변수); 리턴 매개 변수; }}}(2) jsauthorizeaction.cswechat JS-SDK 관련 API 호출 기능
지불 사용 .wxwebhlper; 지불 사용 .wxwebhlper.results; 시스템 사용; wxpayapi; 네임 스페이스 WXJSSDK 사용 {public class jsauthorizeaction {private static tokenresult token = new Tokenresult () {errcode = -1}; 개인 정적 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 ()); } 리턴 토큰; } /// <summary> /// // // </summary> /// <returns> </returns> public tokenresult getokenresult () {var result = new Tokenresult (); {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.jsongringtoobj <tokenresult> (strrtn); } catch (예외 예) {log.error (this.getType (). toString (), ex.Message); 결과 = new Tokenresult () {errcode = -1086}; } 반환 결과; } /// <summary> // // // </summary> /// <param name = "token"> </param> /// <returns> </returns> public jsapiticketresult getJsapiticket (String token) {log.error (this.cedtype (). toString (), "getjsapet (to Ken) if (! jsapiticket.isvalid ()) {jsapiticket = getjsapiticketresult (Token); } return JSapiticket; } /// <summary> /// // // </summary> /// <param name = "token"> </param> /// <returns> </returns> public jsapiticketresult getJsapiticketresult (String token) {jsapiticketresult result; {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 = thools.jsonstringtoobj <jsapiticketresult> (strrtn); } catch (예외 예) {log.error (this.getType (). toString (), ex.Message); result = new jsapiticketresult () {errcode = -1086}; } 반환 결과; }} public class jsapiticketresult : returnResult {/// <summary> /// protuctor /// </summary> public jsapiticketresult () {createate = dateTime.now; } /// <summary> /// // // </summary> 공개 문자열 티켓 {get; 세트; } /// <summary> /// access_token 인터페이스 호출 자격 증명 시간 초과, 단위 (초) /// </summary> public int expripes_in {get; 세트; } /// <summary> /// Creation Time //// </summary> public datetime createate {get; 세트; } /// <summary> /// 유효한 지 결정 //// </summary> /// <returns> </returns> public bool isvalid () {if (this.errcode! = 0) return false; var nd = dateTime.now- 생성물; nd.seconds <7200; }} public class tokenresult : returnResult {/// <summary> /// protuctor /// </summary> public tokenresult () {createate = datetime.now; } /// <summary> /// 웹 권한 부여 인터페이스는 자격 증명을 호출합니다. 참고 :이 access_token은 기본 사항 /// </summary> public string access_token {get; 세트; } /// <summary> /// ac 세트; } /// <summary> /// Creation Time //// </summary> public datetime createate {get; 세트; } /// <summary> /// 유효한 지 결정 //// </summary> /// <returns> </returns> public bool isvalid () {if (this.errcode! = 0) return false; var nd = dateTime.now- 생성물; nd.seconds <7200; }}}(3) WXJSDATA.CS WECHAT JS-SDK 매개 변수 클래스
Litjson 사용; System.collections.generic 사용; System.security. Cryptography 사용; system.text 사용; System.xml 사용; wxpayapi; 네임 스페이스 wxjssdk {public class wxjsdata {private sortedDictionary <string, object> m_values = new SortedDictionary <String, Object> (); / *** 특정 필드의 값을 설정* @param 키 필드 이름* @param 값 필드 값*/ public void setValue (문자열 키, 개체 값) {m_values [key] = value; } / *** 필드 이름* @param 키 필드 이름* @return 필드 값을 기준으로 특정 필드의 값을 가져옵니다* / public object getValue (string key) {Object o = null; m_values.rygetValue (키, Out o); 반품 o; } / *** 필드가 설정되었는지 여부를 결정하십시오* @param 키 필드 이름* @return 필드 키가 설정된 경우 return retud, true, 그렇지 않으면 false* / public bool isset (string key) {object o = null; m_values.rygetValue (키, Out o); if (null! = O)는 true를 반환합니다. 거짓을 반환합니다. } /*** @Convert Dictionary to XML* @ReTurn 변환 된 XML 문자열* @Throws WXPAYEXCELCE ** /public String toxml () {// XML 형식으로 변환 할 수 없습니다 (0 == M_VALUES.count) {this.error (this.getType (). " 새로운 WXPayException을 던지십시오 ( "WXPAYDATA 데이터는 비어 있습니다!"); } 문자열 xml = "<xml>"; foreach (keyValuePair <string, object> m_values in m_values) {// 필드 값은 null이 될 수 없으며, 이는 다음 프로세스 (pair.value == null) {log.error (this.getType (). "wxpayData가 값 null!")에 영향을 미칩니다. 새로운 wxpayexception을 던지십시오 ( "wxpaydata는 값을 가진 필드가 포함되어 있습니다!"); } if (pair.value.getType () == typeof (int) || 쌍. value.getType () == typeof (decimal)) {xml + = "<" + pair.key + ">" + pair.value.toString () + "</" + pair.key + ">"; } else if (pair.value.getType () == typeof (string)) {xml + = "<" + pair.key + ">" + "<! } else // 문자열 및 int 유형을 제외하고는 다른 데이터 유형을 포함 할 수 없습니다 {log.error (this.getType (). toString (), "wxpayData 필드 데이터 유형 오류!"); 새로운 WXPAYEXCEPTION을 던지십시오 ( "WXPAYDATA 필드 데이터 유형 오류!"); }} xml += "</xml>"; XML을 반환합니다. } / *** @convert xml to wxpayData 객체 및 객체 내부의 데이터를 반환 할* @Param String XML 변환* @return Dictionary 변환* @Throws wxpayException* / public sortedDictionary <string, object> forxml (string xml) {if (string.isnullorempty (xml)) { log.error (this.getType (). toString (), "빈 XML 문자열을 WXPAYDATA로 변환하는 것은 합법적이지 않습니다!"); 새로운 WXPayException을 던지십시오 ( "빈 XML 문자열을 WXPAYDATA로 변환하는 것은 합법적이지 않습니다!"); } xmldocument xmldoc = new xmldocument (); xmldoc.loadxml (xml); xmlnode xmlnode = xmldoc.firstchild; // 루트 노드 get <xml> xmlnodelist modes = xmlnode.childnodes; foreach (노드의 xmlnode xn) {xmlelement xe = (xmlelement) xn; m_values [xe.name] = xe.innertext; // wxpaydata 내부의 데이터에 xml의 키 값 쌍을 가져옵니다 {// 2015-06-29 오류는 (m_values [ "return_code"]! = "success")가 없다는 것입니다. } checkSign (); // 서명을 확인하고 서명이 전달되지 않으면 예외를 던집니다.} catch (wxpayException ex) {새 wxpayException (ex.Message); } return m_values; } / *** @Dictionary 형식 URL 매개 변수 형식으로 변환* @ return url format String이 표시되지 않습니다. foreach (keyValuePair <string, object> m_values in m_values) {if (pair.value == null) {log.error (this.getType (). toString (), "wxpayData는 null!"); 새로운 wxpayexception을 던지십시오 ( "wxpaydata는 null 값이있는 필드가 포함되어 있습니다!"); } if (pair.key! = "sign"&& pair.value.tostring ()! = "" ") {buff + = pair.key +"= " + pair.value +"& "; }} buff = buff.trim ( '&'); 반환 버프; } / *** @dictionary json* @return json String data* / public string tojson () {String jsonst = jsonmapper.tojson (m_values); jssonst를 반환합니다. } / ** * 웹 페이지에 표시 될 수있는 결과에 형식으로 구성된 @Values (웹 페이지가 XML 형식으로 문자열을 직접 출력 할 수 없기 때문에) * / public String toprintstr () {String str = ""; foreach (keyValuePair <string, object> m_values in m_values) {if (pair.value == null) {log.error (this.getType (). toString (), "wxpayData는 값 null!"); 새로운 wxpayexception을 던지십시오 ( "wxpaydata는 값을 가진 필드가 포함되어 있습니다!"); } str += string.format ( "{0} = {1} <br>", pair.key, pair.value.toString ()); } log.debug (this.getType (). toString (), "웹 페이지에서 인쇄 :" + str); Return str; } /*** @generate 서명, 자세한 내용은 서명 생성 알고리즘을 참조하십시오.* @return 서명, 서명 필드는 서명에 참여하지 않습니다* /public string makesign () {// URL 형식 string str = tourl (); // 문자열 이후 API를 추가하십시오 str + = "& key =" + wxpayconfig.key; // md5 암호화 var md5 = md5.create (); var bs = md5.computehash (encoding.utf8.getBytes (str)); var sb = new StringBuilder (); foreach (bs in bs) {sb.append (b.tostring ( "x2")); } // 모든 문자는 대문자로 변환됩니다. 결과 = sb.toString (). toupper (); 반환 결과; } public String MakeAppSign () {// url 형식 string str = tourl (); // 문자열 이후 API를 추가하십시오 str + = "& key =" + wxpayConfig.keyOfApp; // md5 암호화 var md5 = md5.create (); var bs = md5.computehash (encoding.utf8.getBytes (str)); var sb = new StringBuilder (); foreach (bs in bs) {sb.append (b.tostring ( "x2")); } // 모든 문자는 대문자로 변환됩니다. 결과 = sb.toString (). toupper (); 반환 결과; } /**** 서명이 올바른지 확인하십시오* 진정으로 반환하고 예외를 제외하고 오류가 발생합니다* /public bool checksign () {// 서명이 설정되지 않으면 (! isset ( "sign")) {log.error (this.getType (). toString (), "wxpayData 서명이 존재하지 않지만"); 새로운 wxpayexception을 던지십시오 ( "WxpayData 서명이 존재하지만 합법적이지 않습니다!"); } // 서명이 설정되어 있지만 서명이 비어 있으면 (getValue ( "sign") == null || getValue ( "sign"). toString () == "") {log.error (this.getType (). toString (), "wxpayData 서명은 합법적이지 않지만"). 새로운 wxpayexception을 던지십시오 ( "WxpayData 서명이 존재하지만 합법적이지 않습니다!"); } // 수신 된 서명 string을 가져옵니다. return_sign = getValue ( "부호"). toString (); // 새 서명 계산 로컬 문자열 cal_sign = makesign (); if (cal_sign == return_sign) {return true; } log.error (this.getType (). toString (), "wxpayData 서명 확인 오류!"); 새 WXPAYEXCEPTION을 던지십시오 ( "WXPAYDATA 서명 검증 오류!"); } / ** * @getDictionary * / public sortedDictionary <string, object> getValues () {return m_values; }}}프롬프트 정보 : 관련 분석 아이디어는 공식 WeChat 공식 계정 지불 SDK, 다운로드 주소를 참조하십시오 : https://pay.weixin.qq.com/wiki/doc/api/jsapi_sl.php?chapter=11_1.
이 기사는 "JavaScript WeChat Development Skills의 요약"으로 편집되었으며 모두가 배우고 읽을 수 있습니다.
"Wechat Mini Program Development Tutorial"의 편집자가 모든 사람을 위해 신중하게 편집 한 WeChat 애플릿에 대한 튜토리얼을 추천합니다.
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.