微信支付:JSAPI拉起支付,無效的openid

開發場景:

  1. 同一開放平臺下的公衆號、小程序。
  2. 然後小程序里拉起支付時,當用戶未關注公衆號時,會報錯 “無效的openid”;當關注之後正常拉起,無報錯。

此錯排查:

  1. 前後臺使用的APPID是否一致
  2. 調用統一下單接口,傳入參數openid是否openid(別傳個訂單id)
  3. 最有可能的原因:openid獲取方式不正確,具體表現爲:使用了登錄接口(即下圖)返回的openid。

下面介紹獲取openid的正確方式,拉起授權獲取

  • 小程序端: 調用getUserInfo接口,獲取用戶授權後,獲取到用戶數據,包含敏感數據(openid,unionID),傳給後臺進行解密
  • 服務端:對前臺傳來的敏感數據進行解密,獲取openid 

實現(本人不會前臺,前臺略過):

  1. 前臺調用wx.login 接口獲得臨時登錄憑證 code。小程序wx.login 官方文檔,點擊查看
  2. 前臺調用getUserInfo 獲得的敏感數據。小程序getUserInfo官方文檔,點擊查看

服務端(java):

  1. 調用auth.code2Session,登錄憑證校驗。前臺調用wx.login 接口獲得臨時登錄憑證 code 後,傳到後臺調用此接口完成登錄。
  2. 取出上面接口返回的session_key,用以解密數據。
  3. 對前臺調用getUserInfo獲得的敏感數據進行解密,獲取到授權後正確的openid。
/**
 * @Description: 小程序:獲取微信授權信息
 * @auther: Hanweihu
 * @date: 16:13 2019/6/18
 * @return: cn.shangze.boot.common.vo.Result<java.lang.Object>
 */
@ApiOperation(value = "小程序:獲取微信授權信息")
@RequestMapping(value = "/getAuthInfoForSignUp", method = RequestMethod.GET)
public Result<Object> getAuthInfoForSignUp(String code,
                                @RequestParam(required = false) String encryptedData,
                                @RequestParam(required = false)String iv) {
    if (StringUtils.isBlank(code)){
        return  new ResultUtil<Object>().setErrorMsg("code不可爲空");
    }
    Map<String, String> requestUrlParam = new HashMap<>();
    WxPayConfig wxPayConfig = wxPayConfigMapper.selectById(wxProId);
    requestUrlParam.put("appid", 小程序 appId);
    requestUrlParam.put("secret", 小程序 appSecret);
    requestUrlParam.put("js_code", code); // 前臺獲取的 code
    requestUrlParam.put("grant_type", "authorization_code"); //授權類型 
    // 發送post請求,調用微信接口
    JSONObject jsonObject = JSONObject.fromObject(HttpClientUtil.doPost("https://api.weixin.qq.com/sns/jscode2session", requestUrlParam));
    if (jsonObject.has("errcode")) {
        String errcode = jsonObject.getString("errcode");
        if (errcode.equals("0") == false) {
            // 微信返回失敗,返回微信報錯信息
            return new ResultUtil<Object>().setErrorMsg(jsonObject.getString("errmsg"));
        }
    }
    log.info("小程序:獲取用戶授權返回:" + jsonObject);
    // session_key,用以解密數據
    String sessionkey = jsonObject.getString("session_key");
    if (StringUtils.isBlank(iv) || StringUtils.isBlank(encryptedData)){
        // 這倆參數值爲空,說明,已授權不用再次重複授權,此時,上面接口獲取openid就是對的。直接返回
        return  new ResultUtil<Object>().setData(jsonObject,"獲取微信授權成功");
    }
    // 參數不爲空,則爲第一次授權,需要解密獲取。
    JSONObject jsonObject2 = getUserInfo(encryptedData , sessionkey, iv);
    Map<String, String> res = new HashMap<>();
    res.put("openid", jsonObject2.getString("openId"));
    res.put("unionid", jsonObject2.getString("unionId"));
    res.put("session_key", sessionkey);
    log.info("解密結果:"+jsonObject2.toString());
    return new ResultUtil<Object>().setData(res,"獲取微信授權成功");
}


/**
 * 解密用戶敏感數據獲取用戶信息
 *
 * @param sessionKey    數據進行加密簽名的密鑰
 * @param encryptedData 包括敏感數據在內的完整用戶信息的加密數據
 * @param iv            加密算法的初始向量
 * @return
 */
public JSONObject getUserInfo(String encryptedData, String sessionKey, String iv) {
    // 被加密的數據
    byte[] dataByte = Base64.decode(encryptedData);
    // 加密祕鑰
    byte[] keyByte = Base64.decode(sessionKey);
    // 偏移量
    byte[] ivByte = Base64.decode(iv);
    try {
        // 如果密鑰不足16位,那麼就補足.  這個if 中的內容很重要
        int base = 16;
        if (keyByte.length % base != 0) {
            int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
            byte[] temp = new byte[groups * base];
            Arrays.fill(temp, (byte) 0);
            System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
            keyByte = temp;
        }
        // 初始化
        Security.addProvider(new BouncyCastleProvider());
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding","BC");
        SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
        AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
        parameters.init(new IvParameterSpec(ivByte));
        cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
        byte[] resultByte = cipher.doFinal(dataByte);
        if (null != resultByte && resultByte.length > 0) {
            String result = new String(resultByte, "UTF-8");
            return JSONObject.fromObject(result);
        }
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (NoSuchPaddingException e) {
        e.printStackTrace();
    } catch (InvalidParameterSpecException e) {
        e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
        e.printStackTrace();
    } catch (BadPaddingException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (InvalidAlgorithmParameterException e) {
        e.printStackTrace();
    } catch (NoSuchProviderException e) {
        e.printStackTrace();
    }
    return null;
}

解密方法中,maven依賴:

<dependency>
    <groupId>org.bouncycastle</groupId>
    <artifactId>bcprov-jdk15on</artifactId>
    <version>1.56</version>
</dependency>

HttpClientUtil

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpClientUtil {

    public static String doGet(String url, Map<String, String> param) {

        // 創建Httpclient對象
        CloseableHttpClient httpclient = HttpClients.createDefault();

        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 創建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();

            // 創建http GET請求
            HttpGet httpGet = new HttpGet(uri);

            // 執行請求
            response = httpclient.execute(httpGet);
            // 判斷返回狀態是否爲200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    public static String doGet(String url) {
        return doGet(url, null);
    }

    public static String doPost(String url, Map<String, String> param) {
        // 創建Httpclient對象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 創建Http Post請求
            HttpPost httpPost = new HttpPost(url);
            // 創建參數列表
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key)));
                }
                // 模擬表單
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
                httpPost.setEntity(entity);
            }
            // 執行http請求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return resultString;
    }

    public static String doPost(String url) {
        return doPost(url, null);
    }

    public static String doPostJson(String url, String json) {
        // 創建Httpclient對象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 創建Http Post請求
            HttpPost httpPost = new HttpPost(url);
            // 創建請求內容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 執行http請求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return resultString;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章