2017-07-15 00:54:57 snakeMoving 阅读数 3173
  • 微信支付开发-微信公众号开发12-微信开发php

    微信公众平台开发之微信支付开发是子恒老师《微信公众平台开发》视频教程的第12部。详细讲解了用php进行微信支付的开发。内容包含获取支付密钥,微信公众号支付开发,扫码支付,微信刷卡支付,异步处理支付结果等等。欢迎反馈,微信/QQ:68183131

    28870 人正在学习 去看看 秦子恒

之前没有接触过微信开发,出来工作后第一份工作是做微信开发,我的任务只是写一个接口。

进入正题,微信开发,本文的微信开发是指微信公众号开发,本文从微信开发的最基础部分做一个简单的记录,并且附上自己写的一段代码。

openid:openid其实就是一个数据库主键,是腾讯为每个公众号的唯一标识

userinfo:其实就是用户信息,这些可以授权获取到的信息及其有限,就是用户名性别地址之类的

其实微信开发文档写得很清楚了,本人啰嗦了点所以记下来了

一般我们进入一个公众号,它可能会让我们授权,其实这样他就获取到我们的信息,他可以保存到数据库,作为会员信息,这样就省去了注册的一个步骤

首先获取授权这一步,其实是开发者后台获取用户code的一个手段,code可以干嘛?code可以作为一个钥匙,通过微信提供的接口,携带着开发者的appid和秘钥,以及code

就可以获取到用户的openid和accesstoken,其实获取到这2个没什么卵用,然后你可以利用openid和accesstoken通过另外一个接口获取到用户信息,这就有用啦。

以下附上自己写的菜得抠脚的代码,还忘个各位大佬完善一些细节

package wechat.Common;

/**
 * Created by sam on 2017/7/13.
 */

/**
 * 授权后重定向的回调链接地址,请使用urlEncode对链接进行处理
 * 应用授权作用域,snsapi_base (不弹出授权页面,直接跳转,只能获取用户openid),
 * snsapi_userinfo (弹出授权页面可通过openid拿到昵称、性别、所在地。
 * 并且,即使在未关注的情况下,只要用户授权,也能获取其信息)
 */
public class URLBean {
    public static final String appid = "这个写自己的";
    public static final String appsecret = "这个写自己的";
    public static final String GETCODE
            = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE#wechat_redirect";
    public static final String GETACCESSTOKENANDID
            = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
    public static final String REFRESHTOKEN
            = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN ";
    //需要用get访问,https协议
    public static final String USERINFO
            = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
    public static final String BASEURL = "/grant/getCode?visitUrl=VISIT";
    public static final String PROJECT_URL = "http://2691670703.tunnel.qydev.com/WeChat";
}
package wechat.Common;

import org.apache.log4j.Logger;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * Created by sam on 2017/7/13. 
 */
public class WechatFilter implements Filter{

	private Logger logger = org.apache.log4j.Logger.getLogger(this.getClass());

    public void init(FilterConfig filterConfig) throws ServletException {
        //
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        HttpSession session = request.getSession();
        String openId = (String) session.getAttribute("openid");
        String URL = request.getRequestURI();
        if(isNeedGrant(URL)){
			if(openId!=null){
				filterChain.doFilter(request,response);
			}else{
				String queryString = request.getQueryString();
				String redirect_url = "";
				if(queryString!=null) {
					redirect_url = request.getRequestURL().toString()+"?"+queryString;
				}else {
					redirect_url = request.getRequestURL().toString();
				}
				String url  = URLBean.PROJECT_URL+URLBean.BASEURL.replace("VISIT",URLEncoder.encode(redirect_url, "UTF-8"));
				String target = URLBean.GETCODE.
						replace("APPID",URLBean.appid).
						replace("SCOPE","snsapi_userinfo").
						replace("REDIRECT_URI", url);
				response.sendRedirect(target);
			}
		}else{
			filterChain.doFilter(request,response);
		}

    }

    public void destroy() {
        //
    }
	/**
	 * 需要判断是否拉取openid不然它会无限循环进来
	 */
	public boolean isNeedGrant(String url){
		//判断是否是正在走向我定义好的接口
//		if (url.contains("/grant/getCode")){
//			return true;
//		}
//		return false;
		return true;
	}
}
package wechat.Common;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import wechat.Entity.WeChatUser;
import wechat.Service.WeChatUserService;

import java.net.URLDecoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Created by sam on 2017/7/13.
 */
@Controller
@RequestMapping("/grant")
public class Grant {
	private Logger logger = Logger.getLogger(this.getClass());
	@Autowired
	private WeChatUserService weChatUserService;
	//Illegal character in scheme name at index 0
    @RequestMapping("/getCode")
    public void getCode(HttpServletRequest HttpServletRequest, 
    		HttpServletResponse httpServletResponse)throws Exception{
        //这里拉取code,然后重定向到获取openId和accessToken的地址
    	HttpSession httpSession =  HttpServletRequest.getSession();
    	String code = HttpServletRequest.getParameter("code");
    	String redirect_url = HttpServletRequest.getParameter("visitUrl");
    	redirect_url = URLDecoder.decode(redirect_url,"UTF-8");
    	String url = URLBean.GETACCESSTOKENANDID.replace("APPID", URLBean.appid).
    			replace("SECRET", URLBean.appsecret).replace("CODE", code);
    	String resp = HttpClientUtil.doGet(url);
    	AccessTokenOpenId ao = JsonUtils.jsonToPojo(resp, AccessTokenOpenId.class);
    	String openId = ao.getOpenid();
    	httpSession.setAttribute("openid", openId);
    	WeChatUser chatUser = weChatUserService.getWeChatUserByOpenId(openId);
    	if(chatUser==null) {
    		String userinfojson = HttpClientUtil.doGet(URLBean.USERINFO
    				.replace("ACCESS_TOKEN",ao.getAccess_token()).replace("OPENID", ao.getOpenid()));
    		chatUser = JsonUtils.jsonToPojo(userinfojson, WeChatUser.class);
    		weChatUserService.insert(chatUser);
    	}
    	httpSession.setAttribute("user",chatUser);
    	httpServletResponse.sendRedirect(URLDecoder.decode(redirect_url, "UTF-8"));//跳转用户最原始访问的连接
    }
 
}
里面有一些需要完善的地方,需要各位大佬自己修改一下,我写不出优雅的代码,就这样吧,仅此记录而已 --Sam

2019-04-28 22:00:16 weixin_43764814 阅读数 538
  • 微信支付开发-微信公众号开发12-微信开发php

    微信公众平台开发之微信支付开发是子恒老师《微信公众平台开发》视频教程的第12部。详细讲解了用php进行微信支付的开发。内容包含获取支付密钥,微信公众号支付开发,扫码支付,微信刷卡支付,异步处理支付结果等等。欢迎反馈,微信/QQ:68183131

    28870 人正在学习 去看看 秦子恒

QQ:634196762 只聊技术的群.没有任何广告.欢迎前端后端加入

获取签名工具类(httpclient和sha1加密)

package com.luo.util;
 
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
 
public class HttpXmlClient {
 
    public static String post(String url, Map<String, String> params) {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        String body = null;
        HttpPost post = postForm(url, params);
        body = invoke(httpclient, post);
        httpclient.getConnectionManager().shutdown();
        return body;
    }
 
    public static String get(String url) {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        String body = null;
        HttpGet get = new HttpGet(url);
        body = invoke(httpclient, get);
        httpclient.getConnectionManager().shutdown();
        return body;
    }
 
    private static String invoke(DefaultHttpClient httpclient,
            HttpUriRequest httpost) {
        HttpResponse response = sendRequest(httpclient, httpost);
        String body = paseResponse(response);
        return body;
    }
 
    private static String paseResponse(HttpResponse response) {
        HttpEntity entity = response.getEntity();
        String charset = EntityUtils.getContentCharSet(entity);
        String body = null;
        try {
            body = EntityUtils.toString(entity);
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return body;
    }
 
    private static HttpResponse sendRequest(DefaultHttpClient httpclient,
            HttpUriRequest httpost) {
        HttpResponse response = null;
        try {
            response = httpclient.execute(httpost);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;
    }
 
    private static HttpPost postForm(String url, Map<String, String> params) {
 
        HttpPost httpost = new HttpPost(url);
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
 
        Set<String> keySet = params.keySet();
        for (String key : keySet) {
            nvps.add(new BasicNameValuePair(key, params.get(key)));
        }
 
        try {
            httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
 
        return httpost;
    }
 
    public static void main(String[] args) {
 
        //获取access_token
        Map<String, String> params = new HashMap<String, String>();
        params.put("corpid","wx5f24fa0db1819ea2");
        params.put("corpsecret","uQtWzF0bQtl2KRHX0amekjpq8L0aO96LSpSNfctOBLRbuYPO4DUBhMn0_v2jHS-9");
        String xml = HttpXmlClient.post("https://qyapi.weixin.qq.com/cgi-bin/gettoken",params);
        JSONObject jsonMap  = JSONObject.fromObject(xml);
        Map<String, String> map = new HashMap<String, String>();
        Iterator<String> it = jsonMap.keys();  
        while(it.hasNext()) {  
            String key = (String) it.next();  
            String u = jsonMap.get(key).toString();
            map.put(key, u);  
        }
        String access_token = map.get("access_token");
        System.out.println("access_token=" + access_token);
 
        //获取ticket
        params.put("access_token",access_token);
        xml = HttpXmlClient.post("https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket",params); 
        jsonMap  = JSONObject.fromObject(xml);
        map = new HashMap<String, String>();
        it = jsonMap.keys();  
        while(it.hasNext()) {  
            String key = (String) it.next();  
            String u = jsonMap.get(key).toString();
            map.put(key, u);  
        }
        String jsapi_ticket = map.get("ticket");
        System.out.println("jsapi_ticket=" + jsapi_ticket);
 
        //获取签名signature
        String noncestr = UUID.randomUUID().toString();
        String timestamp = Long.toString(System.currentTimeMillis() / 1000);
        String url="http://mp.weixin.qq.com";
        String str = "jsapi_ticket=" + jsapi_ticket +
                "&noncestr=" + noncestr +
                "&timestamp=" + timestamp +
                "&url=" + url;
        //sha1加密
        String signature = SHA1(str);
        System.out.println("noncestr=" + noncestr);
        System.out.println("timestamp=" + timestamp);
        System.out.println("signature=" + signature);
        //最终获得调用微信js接口验证需要的三个参数noncestr、timestamp、signature
    }
 
       /** 
     * @author:罗国辉 
     * @date: 2015年12月17日 上午9:24:43 
     * @description: SHA、SHA1加密
     * @parameter:   str:待加密字符串
     * @return:  加密串
    **/
    public static String SHA1(String str) {
        try {
            MessageDigest digest = java.security.MessageDigest
                    .getInstance("SHA-1"); //如果是SHA加密只需要将"SHA-1"改成"SHA"即可
            digest.update(str.getBytes());
            byte messageDigest[] = digest.digest();
            // Create Hex String
            StringBuffer hexStr = new StringBuffer();
            // 字节数组转换为 十六进制 数
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexStr.append(0);
                }
                hexStr.append(shaHex);
            }
            return hexStr.toString();
 
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }
}

controller代码(尽可能仔细阅读下面的每一行代码,特别是url部分)

package com.luo.controller;
 
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
 
import com.luo.util.HttpXmlClient;
 
@Controller 
public class UserController {  
 
    @RequestMapping("/")    
    public ModelAndView getIndex(HttpServletRequest request){  
 
        ModelAndView mav = new ModelAndView("index");  
        //获取access_token
        Map<String, String> params = new HashMap<String, String>();
        params.put("corpid","wx7099477f2de8aded");
        params.put("corpsecret","4clWzENvHVmpcyuA4toys0URkfYanIqWtxZ5plbisn6Cd5AVTF0thpaK6UAhjIvN");
        String xml = HttpXmlClient.post("https://qyapi.weixin.qq.com/cgi-bin/gettoken",params);
        JSONObject jsonMap  = JSONObject.fromObject(xml);
        Map<String, String> map = new HashMap<String, String>();
        Iterator<String> it = jsonMap.keys();  
        while(it.hasNext()) {  
            String key = (String) it.next();  
            String u = jsonMap.get(key).toString();
            map.put(key, u);  
        }
        String access_token = map.get("access_token");
 
        //获取ticket
        params.put("access_token",access_token);
        xml = HttpXmlClient.post("https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket",params); 
        jsonMap  = JSONObject.fromObject(xml);
        map = new HashMap<String, String>();
        it = jsonMap.keys();  
        while(it.hasNext()) {  
            String key = (String) it.next();  
            String u = jsonMap.get(key).toString();
            map.put(key, u);  
        }
        String jsapi_ticket = map.get("ticket");
 
        //获取签名signature
        String noncestr = UUID.randomUUID().toString();
        String timestamp = Long.toString(System.currentTimeMillis() / 1000);
        //获取请求url
        String path = request.getContextPath();
        //以为我配置的菜单是http://yo.bbdfun.com/first_maven_project/,最后是有"/"的,所以url也加上了"/"
        String url = request.getScheme() + "://" + request.getServerName() +  path + "/";  
        String str = "jsapi_ticket=" + jsapi_ticket +
                "&noncestr=" + noncestr +
                "&timestamp=" + timestamp +
                "&url=" + url;
        //sha1加密
        String signature = HttpXmlClient.SHA1(str);
        mav.addObject("signature", signature);   
        mav.addObject("timestamp", timestamp);   
        mav.addObject("noncestr", noncestr);   
        mav.addObject("appId", "wx7099477f2de8aded"); 
        System.out.println("jsapi_ticket=" + jsapi_ticket);
        System.out.println("noncestr=" + noncestr);
        System.out.println("timestamp=" + timestamp);
        System.out.println("url=" + url);
        System.out.println("str=" + str);
        System.out.println("signature=" + signature);
        return mav;    
 
    }    
}

前端js代码(尽可能仔细阅读下面的每一行代码)

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
<script>
    wx.config({
     beta: true,// 必须这么写,否则在微信插件有些jsapi会有问题
        debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
        appId: '${appId}', // 必填,企业号的唯一标识,此处填写企业号corpid
        timestamp: parseInt("${timestamp}",10), // 必填,生成签名的时间戳
        nonceStr: '${noncestr}', // 必填,生成签名的随机串
        signature: '${signature}',// 必填,签名,见附录1
        jsApiList: ['getLocation','openLocation'] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
    });
    wx.ready(function(){
         var isCheck=false;
         wx.checkJsApi({
           jsApiList: [
             'getLocation'
           ],
         })
    });
 
    wx.error(function(res){
    });
</script>
</head>
<body>
<button id="getBBS" style="width:1000px;height:600px;font-size:150px;" onclick="submitOrderInfoClick();">获取地理位置</button>
</body>
<script type="text/javascript">
function submitOrderInfoClick(){
  wx.getLocation({
        success: function (res) {
            alert("经纬度为:(" + res.latitude + "," + res.longitude + ")" );
        },
        fail: function(error) {
            AlertUtil.error("获取地理位置失败,请确保开启GPS且允许微信获取您的地理位置!");
        }
    });
}
</script>
</html>
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server"><title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no;" /> 
<script type="text/javascript" src="../../js/jquery.1.11.1.min.js"></script>
<script type="text/javascript" src="../../js/jweixin-1.0.0.js"></script>
<script type="text/javascript">   
    $(function () {
        wx.config({
            debug: false,
            appId: '<%=app_Id%>',
            timestamp: <%=timestamp%>,
            nonceStr: '<%=nonceStr%>',
            signature: '<%=signature%>',
            jsApiList: [
              'checkJsApi',             
              'getLocation'
            ]
        });
        wx.ready(function () {
            var isCheck=false;
            wx.checkJsApi({
                jsApiList: [
                  'checkJsApi',  
                  'getLocation'
                ],
                success: function (res) {
                    //alert(JSON.stringify(res));
                    isCheck=res.checkResult.getLocation;
                }
            });
            document.querySelector('#btnLocation').onclick = function () {
                if(!isCheck){
                    msgtip("您的微信版本不支持获取位置!");
                    return;
                }
                wx.getLocation({
                    success: function (res) {
                        alert(JSON.stringify(res));
                    },
                    cancel: function (res) {
                        alert('发生错误');
                    }
                });
            };
        });
        wx.error(function (res) {
            alert(res.errMsg);
        });

    });
   
</script>
</head>
<body>
    <form id="form1" runat="server">
        <header class="ui-header ui-header-positive ui-border-b">
            <i class="ui-icon-return" onclick="history.back()"></i><h1>获取地址位置</h1><a href="Default.aspx?open_id=" class="sp-back sp-home"></a> 
        </header>
        <div class="panel-body" style="margin-top:45px;">
             <input type="button" id="btnLocation" value="取得位置" />
            <asp:Literal ID="lblInfo" runat="server"></asp:Literal>
           </div>
        <div class="ui-poptips ui-poptips-warn" id="divInfo" style="display:none;">
            <div class="ui-poptips-cnt"><i></i><span id="spntool"></span></div><input type="hidden" id="hideCard_no" />
        </div><div id="datePlugin"></div><asp:HiddenField ID="hideOpen_id" runat="server" />            
    </form>
</body>
</html>

2019-04-22 22:07:02 Aero_K 阅读数 1828
  • 微信支付开发-微信公众号开发12-微信开发php

    微信公众平台开发之微信支付开发是子恒老师《微信公众平台开发》视频教程的第12部。详细讲解了用php进行微信支付的开发。内容包含获取支付密钥,微信公众号支付开发,扫码支付,微信刷卡支付,异步处理支付结果等等。欢迎反馈,微信/QQ:68183131

    28870 人正在学习 去看看 秦子恒

如上图

从最新的微信小程序开发文档中查阅,通过微信小程序接口 wx.getLocation() 依然不能够直接获取到用户具体城市信息。本文写的主要是如何通过从微信API获取的经纬度信息转化为具体的城市街道信息。

首先如果开发者想要获取用户当前的位置,地理信息等,需要先在app.json中配置permission字段,如果用wepy开发的话,需在app.wpy做相应的配置:如下

permission: {
  "scope.userLocation": {
     "desc": "你的位置信息将用于小程序位置接口的效果展示"
  }

第二步:进入页面,调用wx.getSetting拿到用户的授权情况。

第三步:调用wx.getLocation API 获取返回的经纬度,速度等信息

第四步:因为微信没有将经纬度直接转换为地理位置,因此这里需要通过借助微信位置服务,或者百度地图开放平台的全球逆地址编码。(这里本人利用的是百度开放平台,这里ak码是需要向百度地图开放平台获取的~,请求时填入相应的ak码,经纬度等信息。

第五步:用户进入页面的时候,可在页面的onShow方法中执行wx.getLocation让用户进行相应的授权,以后每次进入该页面时,通过wx.getSetting接口,返回用户授权具体信息。

具体代码如下:

onShow() {
    this._getUserLocation();
}
  _getUserLocation () {
    var self = this
    wx.getSetting({
      success: (res) => {
        console.log('用户授权情况', res)
        //未授权
        if(res.authSetting['scope.userLocation'] !== undefined &&     
         res.authSetting['scope.userLocation'] !== true) {
          wx.showModal({
            title: '请求授权当前位置',
            content: '需要获取您的地理位置,请确认授权',
            success: function (res) {
              console.log(res)
              if(res.cancel){
                wx.showToast({
                  title: '拒绝授权',
                  icon: 'none',
                  duration: 1000
                })
              } else if (res.confirm) { //确认授权, 通过wx.openSetting发起授权请求
                wx.openSetting({
                  success: function (res) {
                    if(res.authSetting["scope.userLocation"] == true) {
                      wx.showModal({
                        title: '授权成功',
                        icon: 'success',
                        duration: 1000
                      })
                      self._getCityLocation()
                    } else {
                      wx.showModal({
                        title: '授权失败',
                        icon: 'none',
                        duration: 1000
                      })
                    }
                  }
                })
              }
            }
          })
        } else if (res.authSetting['scope.userLocation'] == undefined) {
          self._getCityLocation()
          console.log('这个为undefined')
        } else {
          console.log('授权成功')
          self._getCityLocation()
        }
      }
    })
  }
  _getCityLocation(){
    let self = this
    wx.getLocation({
      type: 'wgx84',
      success: (res) => {
        let latitude = res.latitude
        let longitude = res.longitude
        let speed = res.speed
        wx.request({
          url: 'http://api.map.baidu.com/geocoder/v2/?ak=Vh0ALNzHjjEm5RP0Ie16dlBhZbdEQip9&location=' + res.latitude + ',' + res.longitude + '&output=json',
          data: {},
          header: { 'Content-type': 'application/json' },
          success: function (ops){ 
            console.log(ops)
            self.address = ops.data.result.addressComponent.city + 
            ops.data.result.addressComponent.district
          },
          fail: function (resq) {
            wx.showModal({
              title: '信息提示',
              content: '请求失败',
              showCancel: false,
              confirmColor: '#f37938'
            });
          }
        })
      },
      fail: (res) => {
        wx.showModal({
          title: '信息提示',
          content: '请求失败',
          showCancel: false,
          comfirmColor: '#f37938'
        })
      }
    })
  }

效果如下

用户首次进入页面时会先先请求用户授权地理位置权限

用户拒绝授权后

用户拒绝授权后再次进入该页面:

用户同意授权后:

 

2018-05-26 02:16:10 weixin_42262436 阅读数 61626
  • 微信支付开发-微信公众号开发12-微信开发php

    微信公众平台开发之微信支付开发是子恒老师《微信公众平台开发》视频教程的第12部。详细讲解了用php进行微信支付的开发。内容包含获取支付密钥,微信公众号支付开发,扫码支付,微信刷卡支付,异步处理支付结果等等。欢迎反馈,微信/QQ:68183131

    28870 人正在学习 去看看 秦子恒

    微信小程序-获取当前城市位置

   1, 获取当前地理位置,首先要拿到用户的授权wx.openSetting;

    2,微信的getLocation接口,获取当前用户的地理位置(微信返回的是经纬度,速度等参数);

    3,微信没有将经纬度直接转换为地理位置,借用腾讯位置服务中关于微信小程序的地理转换JS SDK 的API(返回信息中包括国家,省,市,区,经纬度等地理位置)

步骤描述清楚以后,下面就开始按步骤操作了;(本文仅仅讲述如何获取用户地理位置的授权)

图示为获取用户地理位置授权弹窗


在用户首次进入某页面(需要地理位置授权)时候,在页面进行onLoad,onShow时候,进行调用wx.getLocation要求用户进行授权;以后每次进入该页面时,通过wx.getSetting接口,返回用户授权具体信息。

wx.getSetting接口具体API地址链接为点击打开链接


上图中scope.userLocation就是地理授权的标志;

当该标志是underfind,表示用户初次进入该页面,当该标志是false,表示用户初次进入该页面拒绝了地理授权,应进行重新要求获取授权。

    wx.getSetting({
      success: (res) => {
        console.log(JSON.stringify(res))
        // res.authSetting['scope.userLocation'] == undefined    表示 初始化进入该页面
        // res.authSetting['scope.userLocation'] == false    表示 非初始化进入该页面,且未授权
        // res.authSetting['scope.userLocation'] == true    表示 地理位置授权
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
          wx.showModal({
            title: '请求授权当前位置',
            content: '需要获取您的地理位置,请确认授权',
            success: function (res) {
              if (res.cancel) {
                wx.showToast({
                  title: '拒绝授权',
                  icon: 'none',
                  duration: 1000
                })
              } else if (res.confirm) {
                wx.openSetting({
                  success: function (dataAu) {
                    if (dataAu.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 1000
                      })
                      //再次授权,调用wx.getLocation的API
                      
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'none',
                        duration: 1000
                      })
                    }
                  }
                })
              }
            }
          })
        } else if (res.authSetting['scope.userLocation'] == undefined) {
          //调用wx.getLocation的API
        }
        else {
          //调用wx.getLocation的API
        }
      }
    })

在拿到用户授权以后,使用微信的API获取当前位置的经纬度微信获取位置API


这里,我们进行使用的是腾讯位置服务;专为小程序开发者提供LBS数据服务工具包,可以在小程序中调用腾讯位置服务的POI检索、关键词输入提示、地址解析、逆地址解析、行政区划和距离计算等数据。
    1,得到开发者秘钥

    2,下载微信小程序javaScriptSDK,

    3,安全域名设置,在“设置” -> “开发设置”中设置request合法域名,添加http://api.map.qq.com

在文件中引入对应的javaScriptSDK文件

var QQMapWX = require('../../../utils/qqmap-wx-jssdk.js');
var qqmapsdk;

在文件中进行js调用,


最后的结果就是可以获得自己所在城市的具体位置了



index.js部分的代码

//index.js
//获取应用实例
const app = getApp();
var QQMapWX = require('../../../utils/qqmap-wx-jssdk.js');
var qqmapsdk;
Page({
  data: {
    province: '',
    city: '',
    latitude: '',
    longitude: ''
  },
  onLoad: function () {
    qqmapsdk = new QQMapWX({
      key: 'XXXX-XXXX-XXXX-XXXX' //这里自己的key秘钥进行填充
    });
  },
  onShow: function () {
    let vm = this;
    vm.getUserLocation();
  },
  getUserLocation: function () {
    let vm = this;
    wx.getSetting({
      success: (res) => {
        console.log(JSON.stringify(res))
        // res.authSetting['scope.userLocation'] == undefined    表示 初始化进入该页面
        // res.authSetting['scope.userLocation'] == false    表示 非初始化进入该页面,且未授权
        // res.authSetting['scope.userLocation'] == true    表示 地理位置授权
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
          wx.showModal({
            title: '请求授权当前位置',
            content: '需要获取您的地理位置,请确认授权',
            success: function (res) {
              if (res.cancel) {
                wx.showToast({
                  title: '拒绝授权',
                  icon: 'none',
                  duration: 1000
                })
              } else if (res.confirm) {
                wx.openSetting({
                  success: function (dataAu) {
                    if (dataAu.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 1000
                      })
                      //再次授权,调用wx.getLocation的API
                      vm.getLocation();
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'none',
                        duration: 1000
                      })
                    }
                  }
                })
              }
            }
          })
        } else if (res.authSetting['scope.userLocation'] == undefined) {
          //调用wx.getLocation的API
          vm.getLocation();
        }
        else {
          //调用wx.getLocation的API
          vm.getLocation();
        }
      }
    })
  },
  // 微信获得经纬度
  getLocation: function () {
    let vm = this;
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        console.log(JSON.stringify(res))
        var latitude = res.latitude
        var longitude = res.longitude
        var speed = res.speed
        var accuracy = res.accuracy;
        vm.getLocal(latitude, longitude)
      },
      fail: function (res) {
        console.log('fail' + JSON.stringify(res))
      }
    })
  },
  // 获取当前地理位置
  getLocal: function (latitude, longitude) {
    let vm = this;
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: latitude,
        longitude: longitude
      },
      success: function (res) {
        console.log(JSON.stringify(res));
        let province = res.result.ad_info.province
        let city = res.result.ad_info.city
        vm.setData({
          province: province,
          city: city,
          latitude: latitude,
          longitude: longitude
        })

      },
      fail: function (res) {
        console.log(res);
      },
      complete: function (res) {
        // console.log(res);
      }
    });
  }
})

页面展示部分的代码

<!--index.wxml-->
<view class="retailStore">
   <view class="cnaps  borderBottom">
    <text>所在城市</text>
    <input class='m-bbt' placeholder-class='plhStyle' type='number' maxlength='50' placeholder='' bindinput="bindKeyInput" value='{{province}} {{city}}' disabled></input>
  </view>
</view>


2019-02-19 17:00:18 weixin_41263632 阅读数 40
  • 微信支付开发-微信公众号开发12-微信开发php

    微信公众平台开发之微信支付开发是子恒老师《微信公众平台开发》视频教程的第12部。详细讲解了用php进行微信支付的开发。内容包含获取支付密钥,微信公众号支付开发,扫码支付,微信刷卡支付,异步处理支付结果等等。欢迎反馈,微信/QQ:68183131

    28870 人正在学习 去看看 秦子恒

获取用户基本信息(UnionID机制)

在关注者与公众号产生消息交互后,公众号可获得关注者的OpenID(加密后的微信号,每个用户对每个公众号的OpenID是唯一的。对于不同公众号,同一用户的openid不同)。公众号可通过本接口来根据OpenID获取用户基本信息,包括昵称、头像、性别、所在城市、语言和关注时间。
请注意,如果开发者有在多个公众号,或在公众号、移动应用之间统一用户帐号的需求,需要前往微信开放平台(open.weixin.qq.com)绑定公众号后,才可利用UnionID机制来满足上述需求。

UnionID机制说明:

开发者可通过OpenID来获取用户基本信息。特别需要注意的是,如果开发者拥有多个移动应用、网站应用和公众帐号,可通过获取用户基本信息中的unionid来区分用户的唯一性,因为只要是同一个微信开放平台帐号下的移动应用、网站应用和公众帐号,用户的unionid是唯一的。换句话说,同一用户,对同一个微信开放平台下的不同应用,unionid是相同的。

获取用户基本信息(包括UnionID机制)
开发者可通过OpenID来获取用户基本信息。请使用https协议。
接口调用请求说明

http请求方式: GET
https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN

获取微信的类
``
public class WXUserInfo {

private int subscribe;
private String openid;
private String unionid;
private int sex;
private String nickname;
private String language;
private String headimgurl;
private String remark;
private Long subscribe_time;
private String city;
private String province;
private String country;

``

没有更多推荐了,返回首页