zoukankan      html  css  js  c++  java
  • 微信/支付宝调用获取用户信息(服务号/小程序)

    目录

    1 微信静默/非静默授权登录(获取用户的openId和用户信息)

    认识几个概念术语。openIdaccess_tokenAppIDAppSecret

    • openId
      openId是用户在当前公众号下的唯一标识,通过这个openId,就能区分在这个公众号下具体是哪个用户。
    • access_token
      access_token是公众号的全局唯一接口调用凭据,公众号调用各接口时都需使用access_token。access_token的有效期目前为2个小时,需定时刷新,重复获取将导致上次获取的access_token失效。

      公众号和小程序均可以使用AppID和AppSecret调用本接口来获取access_token,接口调用请求说明:
    https请求方式: GET https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
    
    • AppID
      AppID是公众号开发识别码,配合开发者密码(及AppSecret)可调用公众号的接口能力。

      登录微信公众平台后台获取公众号的AppID

    • AppSecret
      AppSecret是微信公众平台服务号AppID对应的密钥。
      登录微信公众平台后台获取公众号的AppSecret

    1.1 获取token

    测试号管理如下

    # 测试号信息
    appID wx6aebfafd85eebac6
    appsecret 599f2dd3ec74e23a86f6d33cfc4495f3
    # 接口配置信息
    URL: http://www.test.artstoneusa.com/wx_mjs_test/hello
    Token TEST
    

    注:需要在测试号管理配置相关信息。

    以下方法用来获取token

    https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx6aebfafd85eebac6&secret=599f2dd3ec74e23a86f6d33cfc4495f3
    

    返回

    {
    	"access_token": "32_Voimg9iSQvG21tlHl3hZrqLz23Ibj0n8gaKE-Y3TnG4Fp_8Qjo2KK6dzBjicPk4Wb4451--dlJKhmBe7UdPQ3zFR_9YTe7U8whFFU4NkMH0xAPmrgsmBDaNWENR-Xm9UySz8LwT6XDa7FTwQLSOcABAGNJ",
    	"expires_in": 7200
    }
    

    1.2 网页授权登录

    1.2.1 静默方式获取

    • 获取 code
    # scope为snsapi_base
    
    https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx6aebfafd85eebac6&redirect_uri=http://47.105.182.126/wx_mjs_test/&response_type=code&scope=snsapi_base&state=123#wechat_redirect
    

    用户同意授权,页面将跳转至 redirect_uri/?code=CODE&state=STATE。

     http://47.105.182.126/wx_mjs_test/?code=001TyL0B0ueakj20zSYA0b8w0B0TyL0T&state=123
    # code说明 : code作为换取access_token的票据,每次用户授权带上的code将不一样,code只能使用一次,5分钟未被使用自动过期。
    
    • 获取 access_token(网页授权接口调用凭证)

    通过code换取网页授权access_token

    https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx6aebfafd85eebac6&secret=599f2dd3ec74e23a86f6d33cfc4495f3&code=001TyL0B0ueakj20zSYA0b8w0B0TyL0T&grant_type=authorization_code
    

    以下为返回内容。

    {
    	"access_token": "32_MyDQJoDRBWB8TKUD7N3mCVAkAicaStWQAGe3JC_ypP0F-RJXQw5BxttWb89zXaaVrvwz1tU2BbAAFQmsirAGrQ",
    	"expires_in": 7200,
    	"refresh_token": "32_0HC3L6XiFdccHxeO5hGd7WFYG82aJsl4Ln9gVCGHfAjkI9E3nTAyKRS7gvey201QbS0BDJeJ8LhfngcEKuz45A",
    	"openid": "ogu1Hs1aGa81rydfrqgZQYjHWym0",
    	"scope": "snsapi_base"
    }
    

    1.2.2 非静默方式获取用户信息

    • 获取 code
      首先在微信开发者工具打开以下地址。
    https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx6aebfafd85eebac6&redirect_uri=http://47.105.182.126/wx_mjs_test/&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
    

    打开同意授权页面,客户通过同意授权。页面跳转至redirect_uri获取code。以下为返回内容。

    http://47.105.182.126/wx_mjs_test/?code=061Oj9de0KHUgv1Utbge0Gnzde0Oj9dG&state=STATE
    
    • 获取 access_token(网页授权接口调用凭证)
    https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx6aebfafd85eebac6&secret=599f2dd3ec74e23a86f6d33cfc4495f3&code=061Oj9de0KHUgv1Utbge0Gnzde0Oj9dG&grant_type=authorization_code
    

    以下为返回内容。

    {
    	"access_token": "32_vOXx9kp_vaHObQ9rW8wBCm4pNjPdMTr9PZJbY69wZusYsqObo8QmmwD5EOxtRLsBp-5MbVKuOgDah1vhEY3DWw",
    	"expires_in": 7200,
    	"refresh_token": "32_j5CMDa49f4VevgHSMiO3yVWBKy4zz2OVZNFpsEiOODjJCAx9oUj1A891rWjSfCqoMdeN9sD2MZJ2CUdn7pPYug",
    	"openid": "ogu1Hs1aGa81rydfrqgZQYjHWym0",
    	"scope": "snsapi_userinfo"
    }
    
    • 拉取用户信息(需scopesnsapi_userinfo)
      如果网页授权作用域为snsapi_userinfo,则此时开发者可以通过access_tokenopenid拉取用户信息了。
    https://api.weixin.qq.com/sns/userinfo?access_token=32_vOXx9kp_vaHObQ9rW8wBCm4pNjPdMTr9PZJbY69wZusYsqObo8QmmwD5EOxtRLsBp-5MbVKuOgDah1vhEY3DWw&openid=ogu1Hs1aGa81rydfrqgZQYjHWym0&lang=zh_CN
    

    返回内容如下。

    {
    	"openid": "ogu1Hs1aGa81rydfrqgZQYjHWym0",
    	"nickname": "(^з^)輕淺初夏",
    	"sex": 1,
    	"language": "zh_CN",
    	"city": "",
    	"province": "",
    	"country": "中国",
    	"headimgurl": "http://thirdwx.qlogo.cn/mmopen/vi_32/ONlgatwdckJO2sVUQKibiajk7I6WC6U5VtmngAVicPeWFylAiaPdnytTTC5KP21npKSe5TGeia54CAcMpbHcXbuUTug/132",
    	"privilege": []
    }
    

    2 支付宝获取用户信息

    2.1 使用沙箱环境

    测试号信息

    APPID:    2016102200738242
    支付宝网关:      https://openapi.alipaydev.com/gateway.do
    
    商家信息
    商家账号ppqvpq0078@sandbox.com
    商户UID2088102180635888
    登录密码111111
    
    买家信息
    买家账号sywjdn9957@sandbox.com
    登录密码111111
    支付密码111111
    用户名称沙箱环境
    证件类型身份证(IDENTITY_CARD)
    证件号码44223919010216914X
    

    2.2 获取用户信息

    • 通过appId 获取 code
    https://openauth.alipaydev.com/oauth2/publicAppAuthorize.htm?app_id=2016102200738242&scope=auth_user&redirect_uri=http://47.105.182.126:8082/wx_mjs_test/getcode
    

    以下为通过redirect_uri回调返回

    http://47.105.182.126:8082/wx_mjs_test/getcode?app_id=2016102200738242&source=alipay_wallet&scope=auth_user&auth_code=c60d87e2d2c34c52b7b42b0d8c9cZX52
    
    • 使用code换取access_tokenuserId
      以下给出主要源码。该源码需要依赖alipay-sdk-java-3.0.0.jarcommons-logging-1.1.1.jar
      AlipayConfig.java主要字段下。
     /**
         * 支付宝分配给开发者的应用ID
         */
        private String appId;
        /**
         * 开发者私钥
         */
        private String appPrivateKey;
        /**
         * 支付宝公钥,由支付宝生成
         */
        private String alipayPublicKey;
        /**
         * 商户生成签名字符串所使用的签名算法类型,目前支持 RSA2 和 RSA
         */
        private String signType;
        /**
         * 字符编码格式
         */
        private String charset;
        /**
         * 参数返回格式
         */
        private String format;
        /**
         * 支付宝网关url
         */
        private String serverUrl;
    
    /**
         * 通过code换取 access_token 和 userId
         *
         * @param config 商户支付宝配置信息
         * @param code   授权码
         * @return
         */
        public static AlipaySystemOauthTokenResponse getOauth2AccessToken(AlipayConfig config, String code) {
            AlipayClient alipayClient = new DefaultAlipayClient(config.getServerUrl(), config.getAppId(), config.getAppPrivateKey(), config.getFormat(), config.getCharset(), config.getAlipayPublicKey(), config.getSignType());
            AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
            request.setCode(code);
            request.setGrantType("authorization_code");
            try {
                AlipaySystemOauthTokenResponse oauthTokenResponse = alipayClient.execute(request);
                if (ObjectUtils.isNotEmpty(oauthTokenResponse.getAccessToken())) {
                    return oauthTokenResponse;
                }
                log.error("alipay-通过code换取 access_token 和 userId失败 code:{} msg:{}", oauthTokenResponse.getCode(), oauthTokenResponse.getMsg());
            } catch (AlipayApiException e) {
                //处理异常
                log.error("alipay-通过code换取 access_token 和 userId异常", e);
            }
            return null;
        }
    
    • 获取用户信息
     /**
         * alipay-获取用户信息
         *
         * @param config      商户支付宝配置信息
         * @param accessToken 授权令牌
         * @return
         */
        public static AlipayUserInfoShareResponse getUserInfo(AlipayConfig config, String accessToken) {
            AlipayClient alipayClient = new DefaultAlipayClient(config.getServerUrl(), config.getAppId(), config.getAppPrivateKey(), config.getFormat(), config.getCharset(), config.getAlipayPublicKey(), config.getSignType());
            AlipayUserInfoShareRequest request = new AlipayUserInfoShareRequest();
            try {
                AlipayUserInfoShareResponse userinfoShareResponse = alipayClient.execute(request, accessToken);
                if (userinfoShareResponse.getCode().equals("10000")) {
                    return userinfoShareResponse;
                }
                log.error("alipay-获取用户信息失败 code:{} msg:{}", userinfoShareResponse.getCode(), userinfoShareResponse.getMsg());
            } catch (AlipayApiException e) {
                //处理异常
                log.error("alipay-获取用户信息异常", e);
            }
            return null;
    
        }
    

    感谢

  • 相关阅读:
    Linux下安装配置词典GoldenDict
    ubuntu 安装LaTex
    ubuntu 安装Opencv2.4.7
    Ubuntu 安装Matlab2010a
    Ubuntu 挂载ISO文件的方法
    ubuntu安装Java jdk1.7.0
    VDI转vmdk(VirtualBox与VMware硬盘格式转换)[转]
    oracle忘记密码,修改密码,解锁
    SQL Server 2008中文企业版下载地址和序列号[转]
    HTTP 错误 500.19 – Internal Server Error web.config 文件的 system.webServer/httpErrors 节中不允许绝对物理路径“C:inetpubcusterr”[转]
  • 原文地址:https://www.cnblogs.com/mjs154/p/12787960.html
Copyright © 2011-2022 走看看