微信/支付寶調用獲取用戶信息(服務號/小程序)


目錄

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;

    }

感謝


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM